diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index b2f732a97..5215d1e1f 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -997,922 +997,1545 @@ } /** - * CryptoJS implementation. + * Utilities for hex, bytes, CSPRNG. + * @module + */ + /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ + /** + * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. + * @param a - Value to inspect. + * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`. + * @example + * Guards a value before treating it as raw key material. + * + * ```ts + * isBytes(new Uint8Array()); + * ``` + */ + function isBytes$1(a) { + // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / + // cross-realm cases. The fallback still requires a real ArrayBuffer view + // so plain JSON-deserialized `{ constructor: ... }` + // spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views. + return (a instanceof Uint8Array || + (ArrayBuffer.isView(a) && + a.constructor.name === 'Uint8Array' && + 'BYTES_PER_ELEMENT' in a && + a.BYTES_PER_ELEMENT === 1)); + } + // Shared error-message prefix builder. Only called on throw paths, so assert + // success paths never pay for the string concatenation. + const atitle$1 = (title) => (title ? `"${title}" ` : ''); + /** + * Asserts something is a non-negative safe integer. + * @param n - Value to validate. + * @returns The validated number. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validates a non-negative length or counter. + * + * ```ts + * anumber(1); + * ``` + */ + function anumber(n, title = '') { + if (typeof n !== 'number') + throw new TypeError(atitle$1(title) + 'expected number, got ' + typeof n); + if (!Number.isSafeInteger(n) || n < 0) + throw new RangeError(atitle$1(title) + 'expected integer >= 0, got ' + n); + return n; + } + /** + * Asserts something is Uint8Array. + * @param value - Value to validate. + * @param length - Expected byte length. + * @param title - Optional label used in error messages. + * @returns The validated byte array. + * On Node, `Buffer` is accepted too because it is a Uint8Array view. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument lengths. {@link RangeError} + * @example + * Validates a fixed-length nonce or key buffer. + * + * ```ts + * abytes(new Uint8Array([1, 2]), 2); + * ``` + */ + function abytes$1(value, length, title = '') { + // Success path first: this runs at the start of every update() / digestInto(), and the + // common `abytes(data)` form must not pay for length handling it does not use. + if (isBytes$1(value) && (length === undefined || value.length === length)) + return value; + // Error path: recompute freely to build the exact message. + if (length !== undefined) + anumber(length, 'length'); + const bytes = isBytes$1(value); + const ofLen = length !== undefined ? ` of length ${length}` : ''; + const got = bytes ? `length=${value.length}` : `type=${typeof value}`; + const message = atitle$1(title) + 'expected Uint8Array' + ofLen + ', got ' + got; + if (!bytes) + throw new TypeError(message); + throw new RangeError(message); + } + /** + * Casts a typed-array view to Uint32Array. + * @param arr - Typed-array view to reinterpret. + * @returns Uint32Array view over the same bytes. Callers are expected to provide a + * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped. + * @example + * Views a byte buffer as 32-bit words for block processing. * - * @internal + * ```ts + * u32(new Uint8Array(4)); + * ``` */ - - /*eslint-disable */ - - /* - CryptoJS v3.1.2 - code.google.com/p/crypto-js - (c) 2009-2013 by Jeff Mott. All rights reserved. - code.google.com/p/crypto-js/wiki/License - */ - var CryptoJS = - CryptoJS || - (function (h, s) { - var f = {}, - g = (f.lib = {}), - q = function () {}, - m = (g.Base = { - extend: function (a) { - q.prototype = this; - var c = new q(); - a && c.mixIn(a); - c.hasOwnProperty('init') || - (c.init = function () { - c.$super.init.apply(this, arguments); - }); - c.init.prototype = c; - c.$super = this; - return c; - }, - create: function () { - var a = this.extend(); - a.init.apply(a, arguments); - return a; - }, - init: function () {}, - mixIn: function (a) { - for (var c in a) a.hasOwnProperty(c) && (this[c] = a[c]); - a.hasOwnProperty('toString') && (this.toString = a.toString); - }, - clone: function () { - return this.init.prototype.extend(this); - }, - }), - r = (g.WordArray = m.extend({ - init: function (a, c) { - a = this.words = a || []; - this.sigBytes = c != s ? c : 4 * a.length; - }, - toString: function (a) { - return (a || k).stringify(this); - }, - concat: function (a) { - var c = this.words, - d = a.words, - b = this.sigBytes; - a = a.sigBytes; - this.clamp(); - if (b % 4) - for (var e = 0; e < a; e++) - c[(b + e) >>> 2] |= ((d[e >>> 2] >>> (24 - 8 * (e % 4))) & 255) << (24 - 8 * ((b + e) % 4)); - else if (65535 < d.length) for (e = 0; e < a; e += 4) c[(b + e) >>> 2] = d[e >>> 2]; - else c.push.apply(c, d); - this.sigBytes += a; - return this; - }, - clamp: function () { - var a = this.words, - c = this.sigBytes; - a[c >>> 2] &= 4294967295 << (32 - 8 * (c % 4)); - a.length = h.ceil(c / 4); - }, - clone: function () { - var a = m.clone.call(this); - a.words = this.words.slice(0); - return a; - }, - random: function (a) { - for (var c = [], d = 0; d < a; d += 4) c.push((4294967296 * h.random()) | 0); - return new r.init(c, a); - }, - })), - l = (f.enc = {}), - k = (l.Hex = { - stringify: function (a) { - var c = a.words; - a = a.sigBytes; - for (var d = [], b = 0; b < a; b++) { - var e = (c[b >>> 2] >>> (24 - 8 * (b % 4))) & 255; - d.push((e >>> 4).toString(16)); - d.push((e & 15).toString(16)); - } - return d.join(''); - }, - parse: function (a) { - for (var c = a.length, d = [], b = 0; b < c; b += 2) - d[b >>> 3] |= parseInt(a.substr(b, 2), 16) << (24 - 4 * (b % 8)); - return new r.init(d, c / 2); - }, - }), - n = (l.Latin1 = { - stringify: function (a) { - var c = a.words; - a = a.sigBytes; - for (var d = [], b = 0; b < a; b++) d.push(String.fromCharCode((c[b >>> 2] >>> (24 - 8 * (b % 4))) & 255)); - return d.join(''); - }, - parse: function (a) { - for (var c = a.length, d = [], b = 0; b < c; b++) d[b >>> 2] |= (a.charCodeAt(b) & 255) << (24 - 8 * (b % 4)); - return new r.init(d, c); - }, - }), - j = (l.Utf8 = { - stringify: function (a) { - try { - return decodeURIComponent(escape(n.stringify(a))); - } catch (c) { - throw Error('Malformed UTF-8 data'); - } - }, - parse: function (a) { - return n.parse(unescape(encodeURIComponent(a))); - }, - }), - u = (g.BufferedBlockAlgorithm = m.extend({ - reset: function () { - this._data = new r.init(); - this._nDataBytes = 0; - }, - _append: function (a) { - 'string' == typeof a && (a = j.parse(a)); - this._data.concat(a); - this._nDataBytes += a.sigBytes; - }, - _process: function (a) { - var c = this._data, - d = c.words, - b = c.sigBytes, - e = this.blockSize, - f = b / (4 * e), - f = a ? h.ceil(f) : h.max((f | 0) - this._minBufferSize, 0); - a = f * e; - b = h.min(4 * a, b); - if (a) { - for (var g = 0; g < a; g += e) this._doProcessBlock(d, g); - g = d.splice(0, a); - c.sigBytes -= b; - } - return new r.init(g, b); - }, - clone: function () { - var a = m.clone.call(this); - a._data = this._data.clone(); - return a; - }, - _minBufferSize: 0, - })); - g.Hasher = u.extend({ - cfg: m.extend(), - init: function (a) { - this.cfg = this.cfg.extend(a); - this.reset(); - }, - reset: function () { - u.reset.call(this); - this._doReset(); - }, - update: function (a) { - this._append(a); - this._process(); - return this; - }, - finalize: function (a) { - a && this._append(a); - return this._doFinalize(); - }, - blockSize: 16, - _createHelper: function (a) { - return function (c, d) { - return new a.init(d).finalize(c); - }; - }, - _createHmacHelper: function (a) { - return function (c, d) { - return new t.HMAC.init(a, d).finalize(c); - }; - }, - }); - var t = (f.algo = {}); - return f; - })(Math); - - // SHA256 - (function (h) { - for ( - var s = CryptoJS, - f = s.lib, - g = f.WordArray, - q = f.Hasher, - f = s.algo, - m = [], - r = [], - l = function (a) { - return (4294967296 * (a - (a | 0))) | 0; - }, - k = 2, - n = 0; - 64 > n; - - ) { - var j; - a: { - j = k; - for (var u = h.sqrt(j), t = 2; t <= u; t++) - if (!(j % t)) { - j = !1; - break a; + function u32(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + } + /** + * Zeroizes typed arrays in place. + * Warning: JS provides no guarantees. + * @param arrays - Arrays to wipe. + * @example + * Wipes a temporary key buffer after use. + * + * ```ts + * const bytes = new Uint8Array([1]); + * clean(bytes); + * ``` + */ + function clean$1(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } + } + /** + * Whether the current platform is little-endian. + * Most are; some IBM systems are not. + */ + const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)(); + /** + * Reverses byte order of one 32-bit word. + * @param word - Unsigned 32-bit word to swap. + * @returns The same word with bytes reversed. + * @example + * Swaps a big-endian word into little-endian byte order. + * + * ```ts + * byteSwap(0x11223344); + * ``` + */ + function byteSwap(word) { + return (((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff)); + } + /** + * Byte-swaps every word of a Uint32Array in place. + * @param arr - Uint32Array whose words should be swapped. + * @returns The same array after in-place byte swapping. + * @example + * Swaps every 32-bit word in a word-view buffer. + * + * ```ts + * byteSwap32(new Uint32Array([0x11223344])); + * ``` + */ + function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } + return arr; + } + /** + * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores. + * @param u - Word view to normalize in place. + * @returns Little-endian normalized word view. + * @example + * Normalizes a word-view buffer before block processing. + * + * ```ts + * swap32IfBE(new Uint32Array([0x11223344])); + * ``` + */ + const swap32IfBE = isLE + ? (u) => u + : byteSwap32; + /** + * Checks if two U8A use same underlying buffer and overlaps. + * This is invalid and can corrupt data. + * @param a - First byte view. + * @param b - Second byte view. + * @returns `true` when the views overlap in memory. + * @example + * Detects whether two slices alias the same backing buffer. + * + * ```ts + * overlapBytes(new Uint8Array(4), new Uint8Array(4)); + * ``` + */ + function overlapBytes(a, b) { + // Zero-length views cannot overwrite anything, even if their offset sits inside another range. + if (!a.byteLength || !b.byteLength) + return false; + return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy + a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end + b.byteOffset < a.byteOffset + a.byteLength // b starts before a end + ); + } + /** + * If input and output overlap and input starts before output, we will overwrite end of input before + * we start processing it, so this is not supported by forward-processing ciphers. + * @param input - Input bytes. + * @param output - Output bytes. + * @throws If the output view would overwrite unread input bytes. {@link Error} + * @example + * Rejects an in-place layout that would overwrite unread input bytes. + * + * ```ts + * const buffer = new Uint8Array(8); + * complexOverlapBytes(buffer.subarray(0, 4), buffer.subarray(2, 6)); + * ``` + */ + function complexOverlapBytes(input, output) { + // This is very cursed. It works somehow, but I'm completely unsure, + // reasoning about overlapping aligned windows is very hard. + if (overlapBytes(input, output) && input.byteOffset < output.byteOffset) + throw new Error('complex overlap of input and output is not supported'); + } + /** + * Wraps a cipher: validates args, ensures encrypt() can only be called once. + * Used internally by the exported cipher constructors. + * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt` + * arity (`fn.length === 2`), so wrapped output-capable methods must use a normal + * second parameter, not a default/rest parameter. AAD support is explicit in + * `params.withAAD`; optional AAD starts after the nonce slot when one is present. + * @__NO_SIDE_EFFECTS__ + * @param params - Static cipher metadata. See {@link CipherParams}. + * @param constructor - Cipher constructor. + * @returns Wrapped constructor with validation. + */ + const wrapCipher = (params, constructor) => { + function wrappedCipher(key, ...args) { + // Validate key + abytes$1(key, undefined, 'key'); + // Validate nonce if nonceLength is present + if (params.nonceLength !== undefined) { + const nonce = args[0]; + abytes$1(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce'); } - j = !0; - } - j && (8 > n && (m[n] = l(h.pow(k, 0.5))), (r[n] = l(h.pow(k, 1 / 3))), n++); - k++; - } - var a = [], - f = (f.SHA256 = q.extend({ - _doReset: function () { - this._hash = new g.init(m.slice(0)); - }, - _doProcessBlock: function (c, d) { - for ( - var b = this._hash.words, - e = b[0], - f = b[1], - g = b[2], - j = b[3], - h = b[4], - m = b[5], - n = b[6], - q = b[7], - p = 0; - 64 > p; - p++ - ) { - if (16 > p) a[p] = c[d + p] | 0; - else { - var k = a[p - 15], - l = a[p - 2]; - a[p] = - (((k << 25) | (k >>> 7)) ^ ((k << 14) | (k >>> 18)) ^ (k >>> 3)) + - a[p - 7] + - (((l << 15) | (l >>> 17)) ^ ((l << 13) | (l >>> 19)) ^ (l >>> 10)) + - a[p - 16]; - } - k = - q + - (((h << 26) | (h >>> 6)) ^ ((h << 21) | (h >>> 11)) ^ ((h << 7) | (h >>> 25))) + - ((h & m) ^ (~h & n)) + - r[p] + - a[p]; - l = - (((e << 30) | (e >>> 2)) ^ ((e << 19) | (e >>> 13)) ^ ((e << 10) | (e >>> 22))) + - ((e & f) ^ (e & g) ^ (f & g)); - q = n; - n = m; - m = h; - h = (j + k) | 0; - j = g; - g = f; - f = e; - e = (k + l) | 0; + // Keep tag length available for decrypt-size checks after constructor validation. + const tagl = params.tagLength; + const aadStart = params.nonceLength !== undefined ? 1 : 0; + // No-AAD constructors otherwise silently ignore byte args meant as AAD. + if (!params.withAAD) { + for (let i = aadStart; i < args.length; i++) + if (isBytes$1(args[i])) + throw new Error('AAD not supported'); } - b[0] = (b[0] + e) | 0; - b[1] = (b[1] + f) | 0; - b[2] = (b[2] + g) | 0; - b[3] = (b[3] + j) | 0; - b[4] = (b[4] + h) | 0; - b[5] = (b[5] + m) | 0; - b[6] = (b[6] + n) | 0; - b[7] = (b[7] + q) | 0; - }, - _doFinalize: function () { - var a = this._data, - d = a.words, - b = 8 * this._nDataBytes, - e = 8 * a.sigBytes; - d[e >>> 5] |= 128 << (24 - (e % 32)); - d[(((e + 64) >>> 9) << 4) + 14] = h.floor(b / 4294967296); - d[(((e + 64) >>> 9) << 4) + 15] = b; - a.sigBytes = 4 * d.length; - this._process(); - return this._hash; - }, - clone: function () { - var a = q.clone.call(this); - a._hash = this._hash.clone(); - return a; - }, - })); - s.SHA256 = q._createHelper(f); - s.HmacSHA256 = q._createHmacHelper(f); - })(Math); - - // HMAC SHA256 - (function () { - var h = CryptoJS, - s = h.enc.Utf8; - h.algo.HMAC = h.lib.Base.extend({ - init: function (f, g) { - f = this._hasher = new f.init(); - 'string' == typeof g && (g = s.parse(g)); - var h = f.blockSize, - m = 4 * h; - g.sigBytes > m && (g = f.finalize(g)); - g.clamp(); - for (var r = (this._oKey = g.clone()), l = (this._iKey = g.clone()), k = r.words, n = l.words, j = 0; j < h; j++) - (k[j] ^= 1549556828), (n[j] ^= 909522486); - r.sigBytes = l.sigBytes = m; - this.reset(); - }, - reset: function () { - var f = this._hasher; - f.reset(); - f.update(this._iKey); - }, - update: function (f) { - this._hasher.update(f); - return this; - }, - finalize: function (f) { - var g = this._hasher; - f = g.finalize(f); - g.reset(); - return g.finalize(this._oKey.clone().concat(f)); - }, - }); - })(); + // Validate the first AAD slot early; rest-arg AAD constructors validate the tail themselves. + if (params.withAAD && args[aadStart] !== undefined) + abytes$1(args[aadStart], undefined, 'AAD'); + const cipher = constructor(key, ...args); + const checkOutput = (fnLength, output) => { + if (output !== undefined) { + if (fnLength !== 2) + throw new Error('cipher output not supported'); + abytes$1(output, undefined, 'output'); + } + }; + // Create wrapped cipher with validation and single-use encryption + let called = false; + const wrCipher = { + encrypt(data, output) { + if (called) + throw new Error('cannot encrypt() twice with same key + nonce'); + // Any encrypt attempt consumes the instance, even if validation rejects below. + called = true; + abytes$1(data, undefined, 'data'); + checkOutput(cipher.encrypt.length, output); + return cipher.encrypt(data, output); + }, + decrypt(data, output) { + abytes$1(data, undefined, 'data'); + if (tagl && data.length < tagl) + throw new Error('"ciphertext" expected length >= tagLength=' + tagl); + checkOutput(cipher.decrypt.length, output); + return cipher.decrypt(data, output); + }, + }; + return wrCipher; + } + Object.assign(wrappedCipher, params); + return wrappedCipher; + }; + /** + * By default, returns u8a of length. + * When out is available, it checks it for validity and uses it. + * @param expectedLength - Required output length. + * @param out - Optional destination buffer. + * @param onlyAligned - Whether `out` must be 4-byte aligned. + * @returns Output buffer ready for writing. + * @throws On wrong argument types. {@link TypeError} + * @throws If the provided output buffer has the wrong size. {@link RangeError} + * @throws If the provided output buffer has the wrong alignment. {@link Error} + * @example + * Reuses a caller-provided output buffer when lengths match. + * + * ```ts + * getOutput(16, new Uint8Array(16)); + * ``` + */ + function getOutput(expectedLength, out, onlyAligned = true) { + if (out === undefined) + return new Uint8Array(expectedLength); + // Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object. + abytes$1(out, expectedLength, 'output'); + if (onlyAligned && !isAligned32(out)) + throw new Error('invalid output, must be aligned'); + return out; + } + /** + * Checks whether a byte array is aligned to a 4-byte offset. + * @param bytes - Byte array to inspect. + * @returns `true` when the view is 4-byte aligned. + * @example + * Checks whether a buffer can be safely viewed as Uint32Array. + * + * ```ts + * isAligned32(new Uint8Array(4)); + * ``` + */ + function isAligned32(bytes) { + return bytes.byteOffset % 4 === 0; + } + /** + * Copies bytes into a new Uint8Array. + * @param bytes - Bytes to copy. + * @returns Copied byte array. + * @throws On wrong argument types. {@link TypeError} + * @example + * Copies input into an aligned Uint8Array before block processing. + * + * ```ts + * copyBytes(new Uint8Array([1, 2])); + * ``` + */ + function copyBytes(bytes) { + // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict + // because callers use it at byte-validation boundaries before mutating the detached copy. + return Uint8Array.from(abytes$1(bytes)); + } + /** + * Cryptographically secure PRNG backed by `crypto.getRandomValues`. + * @param bytesLength - number of random bytes to generate + * @returns Random bytes. + * The platform `getRandomValues()` implementation still defines any + * single-call length cap, and this helper rejects oversize requests + * with a stable library `RangeError` instead of host-specific errors. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error} + * @example + * Generate a fresh random key or nonce. + * ```ts + * const key = randomBytes(16); + * ``` + */ + function randomBytes(bytesLength = 32) { + // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion. + anumber(bytesLength, 'bytesLength'); + const cr = typeof globalThis === 'object' ? globalThis.crypto : null; + if (typeof cr?.getRandomValues !== 'function') + throw new Error('crypto.getRandomValues must be defined'); + // Web Cryptography API Level 2 §10.1.1: + // if `byteLength > 65536`, throw `QuotaExceededError`. + // Keep the guard explicit so callers can see the quota in code + // instead of discovering it by reading the spec or host errors. + // This wrapper surfaces the same quota as a stable library RangeError. + if (bytesLength > 65536) + throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`); + return cr.getRandomValues(new Uint8Array(bytesLength)); + } - // Base64 - (function () { - var u = CryptoJS, - p = u.lib.WordArray; - u.enc.Base64 = { - stringify: function (d) { - var l = d.words, - p = d.sigBytes, - t = this._map; - d.clamp(); - d = []; - for (var r = 0; r < p; r += 3) - for ( - var w = - (((l[r >>> 2] >>> (24 - 8 * (r % 4))) & 255) << 16) | - (((l[(r + 1) >>> 2] >>> (24 - 8 * ((r + 1) % 4))) & 255) << 8) | - ((l[(r + 2) >>> 2] >>> (24 - 8 * ((r + 2) % 4))) & 255), - v = 0; - 4 > v && r + 0.75 * v < p; - v++ - ) - d.push(t.charAt((w >>> (6 * (3 - v))) & 63)); - if ((l = t.charAt(64))) for (; d.length % 4; ) d.push(l); - return d.join(''); - }, - parse: function (d) { - var l = d.length, - s = this._map, - t = s.charAt(64); - t && ((t = d.indexOf(t)), -1 != t && (l = t)); - for (var t = [], r = 0, w = 0; w < l; w++) - if (w % 4) { - var v = s.indexOf(d.charAt(w - 1)) << (2 * (w % 4)), - b = s.indexOf(d.charAt(w)) >>> (6 - 2 * (w % 4)); - t[r >>> 2] |= (v | b) << (24 - 8 * (r % 4)); - r++; - } - return p.create(t, r); - }, - _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', - }; + /** + * {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard | AES} + * a.k.a. Advanced Encryption Standard + * is a variant of Rijndael block cipher, standardized by NIST in 2001. + * We provide the fastest available pure JS implementation. + * + * `cipher = encrypt(block, key)` + * + * Data is split into 128-bit blocks. + * Encrypted in 10/12/14 rounds (128/192/256 bits). In every round: + * 1. **S-box**, table substitution + * 2. **Shift rows**, cyclic shift left of all rows of data array + * 3. **Mix columns**, multiplying every column by fixed polynomial + * 4. **Add round key**, round_key xor i-th column of array + * + * Check out + * {@link https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf | FIPS-197}, + * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G}, + * and {@link https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf | original proposal}. + * @module + */ + const BLOCK_SIZE = 16; + const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8 + // Validates plain AES key sizes only; AES-SIV's doubled-key contract is checked elsewhere. + function validateKeyLength(key) { + if (![16, 24, 32].includes(key.length)) + throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length=' + key.length); + } + // TODO: remove multiplication, binary ops only + // Doubles one GF(2^8) field element; callers are expected to stay in byte range. + // FIPS 197 upd1 §4.3 equation (4.5): XTIMES(b) left-shifts by one and, when + // b7=1, reduces by m(x); using POLY=0x11b here yields the same byte result + // as XORing with {1b} after the shift. + function mul2(n) { + return (n << 1) ^ (POLY & -(n >> 7)); + } + // Shift-and-add multiplication in GF(2^8); callers are expected to pass byte values. + // FIPS 197 upd1 §4.3 equation (4.7): general products are XORs of repeated + // XTIMES() multiples, e.g. {57}•{13} = {57}⊕{ae}⊕{07}. + function mul(a, b) { + let res = 0; + for (; b > 0; b >>= 1) { + // Usual shift-and-add step in GF(2^8), not a scalar-multiplication ladder. + res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time). + a = mul2(a); // a = 2*a + } + return res; + } + // AES S-box is generated using finite field inversion, + // an affine transform, and xor of a constant 0x63. + const sbox = /* @__PURE__ */ (() => { + const t = new Uint8Array(256); + // Repeated multiplication by {03} walks all 255 nonzero field elements + // once, so t[255 - i] is the multiplicative inverse of t[i] for the + // affine step. + for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) + t[i] = x; + const box = new Uint8Array(256); + // FIPS 197 upd1 §5.1.1: SBOX({00}) = {63} because the inverse step leaves + // {00} at {00}, then the affine transform xors in c = {63}. + box[0] = 0x63; + for (let i = 0; i < 255; i++) { + let x = t[255 - i]; + x |= x << 8; + box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff; + } + clean$1(t); + return box; })(); - - // BlockCipher - (function (u) { - function p(b, n, a, c, e, j, k) { - b = b + ((n & a) | (~n & c)) + e + k; - return ((b << j) | (b >>> (32 - j))) + n; - } - function d(b, n, a, c, e, j, k) { - b = b + ((n & c) | (a & ~c)) + e + k; - return ((b << j) | (b >>> (32 - j))) + n; - } - function l(b, n, a, c, e, j, k) { - b = b + (n ^ a ^ c) + e + k; - return ((b << j) | (b >>> (32 - j))) + n; - } - function s(b, n, a, c, e, j, k) { - b = b + (a ^ (n | ~c)) + e + k; - return ((b << j) | (b >>> (32 - j))) + n; - } - for (var t = CryptoJS, r = t.lib, w = r.WordArray, v = r.Hasher, r = t.algo, b = [], x = 0; 64 > x; x++) - b[x] = (4294967296 * u.abs(u.sin(x + 1))) | 0; - r = r.MD5 = v.extend({ - _doReset: function () { - this._hash = new w.init([1732584193, 4023233417, 2562383102, 271733878]); - }, - _doProcessBlock: function (q, n) { - for (var a = 0; 16 > a; a++) { - var c = n + a, - e = q[c]; - q[c] = (((e << 8) | (e >>> 24)) & 16711935) | (((e << 24) | (e >>> 8)) & 4278255360); - } - var a = this._hash.words, - c = q[n + 0], - e = q[n + 1], - j = q[n + 2], - k = q[n + 3], - z = q[n + 4], - r = q[n + 5], - t = q[n + 6], - w = q[n + 7], - v = q[n + 8], - A = q[n + 9], - B = q[n + 10], - C = q[n + 11], - u = q[n + 12], - D = q[n + 13], - E = q[n + 14], - x = q[n + 15], - f = a[0], - m = a[1], - g = a[2], - h = a[3], - f = p(f, m, g, h, c, 7, b[0]), - h = p(h, f, m, g, e, 12, b[1]), - g = p(g, h, f, m, j, 17, b[2]), - m = p(m, g, h, f, k, 22, b[3]), - f = p(f, m, g, h, z, 7, b[4]), - h = p(h, f, m, g, r, 12, b[5]), - g = p(g, h, f, m, t, 17, b[6]), - m = p(m, g, h, f, w, 22, b[7]), - f = p(f, m, g, h, v, 7, b[8]), - h = p(h, f, m, g, A, 12, b[9]), - g = p(g, h, f, m, B, 17, b[10]), - m = p(m, g, h, f, C, 22, b[11]), - f = p(f, m, g, h, u, 7, b[12]), - h = p(h, f, m, g, D, 12, b[13]), - g = p(g, h, f, m, E, 17, b[14]), - m = p(m, g, h, f, x, 22, b[15]), - f = d(f, m, g, h, e, 5, b[16]), - h = d(h, f, m, g, t, 9, b[17]), - g = d(g, h, f, m, C, 14, b[18]), - m = d(m, g, h, f, c, 20, b[19]), - f = d(f, m, g, h, r, 5, b[20]), - h = d(h, f, m, g, B, 9, b[21]), - g = d(g, h, f, m, x, 14, b[22]), - m = d(m, g, h, f, z, 20, b[23]), - f = d(f, m, g, h, A, 5, b[24]), - h = d(h, f, m, g, E, 9, b[25]), - g = d(g, h, f, m, k, 14, b[26]), - m = d(m, g, h, f, v, 20, b[27]), - f = d(f, m, g, h, D, 5, b[28]), - h = d(h, f, m, g, j, 9, b[29]), - g = d(g, h, f, m, w, 14, b[30]), - m = d(m, g, h, f, u, 20, b[31]), - f = l(f, m, g, h, r, 4, b[32]), - h = l(h, f, m, g, v, 11, b[33]), - g = l(g, h, f, m, C, 16, b[34]), - m = l(m, g, h, f, E, 23, b[35]), - f = l(f, m, g, h, e, 4, b[36]), - h = l(h, f, m, g, z, 11, b[37]), - g = l(g, h, f, m, w, 16, b[38]), - m = l(m, g, h, f, B, 23, b[39]), - f = l(f, m, g, h, D, 4, b[40]), - h = l(h, f, m, g, c, 11, b[41]), - g = l(g, h, f, m, k, 16, b[42]), - m = l(m, g, h, f, t, 23, b[43]), - f = l(f, m, g, h, A, 4, b[44]), - h = l(h, f, m, g, u, 11, b[45]), - g = l(g, h, f, m, x, 16, b[46]), - m = l(m, g, h, f, j, 23, b[47]), - f = s(f, m, g, h, c, 6, b[48]), - h = s(h, f, m, g, w, 10, b[49]), - g = s(g, h, f, m, E, 15, b[50]), - m = s(m, g, h, f, r, 21, b[51]), - f = s(f, m, g, h, u, 6, b[52]), - h = s(h, f, m, g, k, 10, b[53]), - g = s(g, h, f, m, B, 15, b[54]), - m = s(m, g, h, f, e, 21, b[55]), - f = s(f, m, g, h, v, 6, b[56]), - h = s(h, f, m, g, x, 10, b[57]), - g = s(g, h, f, m, t, 15, b[58]), - m = s(m, g, h, f, D, 21, b[59]), - f = s(f, m, g, h, z, 6, b[60]), - h = s(h, f, m, g, C, 10, b[61]), - g = s(g, h, f, m, j, 15, b[62]), - m = s(m, g, h, f, A, 21, b[63]); - a[0] = (a[0] + f) | 0; - a[1] = (a[1] + m) | 0; - a[2] = (a[2] + g) | 0; - a[3] = (a[3] + h) | 0; - }, - _doFinalize: function () { - var b = this._data, - n = b.words, - a = 8 * this._nDataBytes, - c = 8 * b.sigBytes; - n[c >>> 5] |= 128 << (24 - (c % 32)); - var e = u.floor(a / 4294967296); - n[(((c + 64) >>> 9) << 4) + 15] = (((e << 8) | (e >>> 24)) & 16711935) | (((e << 24) | (e >>> 8)) & 4278255360); - n[(((c + 64) >>> 9) << 4) + 14] = (((a << 8) | (a >>> 24)) & 16711935) | (((a << 24) | (a >>> 8)) & 4278255360); - b.sigBytes = 4 * (n.length + 1); - this._process(); - b = this._hash; - n = b.words; - for (a = 0; 4 > a; a++) - (c = n[a]), (n[a] = (((c << 8) | (c >>> 24)) & 16711935) | (((c << 24) | (c >>> 8)) & 4278255360)); - return b; - }, - clone: function () { - var b = v.clone.call(this); - b._hash = this._hash.clone(); - return b; - }, - }); - t.MD5 = v._createHelper(r); - t.HmacMD5 = v._createHmacHelper(r); - })(Math); - (function () { - var u = CryptoJS, - p = u.lib, - d = p.Base, - l = p.WordArray, - p = u.algo, - s = (p.EvpKDF = d.extend({ - cfg: d.extend({ keySize: 4, hasher: p.MD5, iterations: 1 }), - init: function (d) { - this.cfg = this.cfg.extend(d); - }, - compute: function (d, r) { - for ( - var p = this.cfg, s = p.hasher.create(), b = l.create(), u = b.words, q = p.keySize, p = p.iterations; - u.length < q; - - ) { - n && s.update(n); - var n = s.update(d).finalize(r); - s.reset(); - for (var a = 1; a < p; a++) (n = s.finalize(n)), s.reset(); - b.concat(n); + // FIPS 197 upd1 §5.3.2: INVSBOX() is derived from SBOX() by swapping input + // and output roles (Table 6). + // `indexOf` is only used once at module init, so the quadratic setup cost stays off hot paths. + const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j)); + // FIPS 197 upd1 §5.2: ROTWORD([a0,a1,a2,a3]) = [a1,a2,a3,a0]; with this LE + // word packing that is a right rotate by 8 bits. + const rotr32_8 = (n) => (n << 24) | (n >>> 8); + // LE T-table helper: rotates one precomputed word by one byte so T1/T2/T3 + // reuse T0's substitution/mix result in the other byte lanes. + const rotl32_8 = (n) => (n << 8) | (n >>> 24); + // T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes: + // - LE instead of BE + // - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23; + // so index is u16, instead of u8. This speeds up things, unexpectedly + function genTtable(sbox, fn) { + if (sbox.length !== 256) + throw new Error('wrong sbox length'); + const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j])); + const T1 = T0.map(rotl32_8); + const T2 = T1.map(rotl32_8); + const T3 = T2.map(rotl32_8); + // Pre-xor adjacent lanes so apply0123/applySbox can fetch two substituted + // byte lanes per lookup in the LE round layout. + const T01 = new Uint32Array(256 * 256); + const T23 = new Uint32Array(256 * 256); + const sbox2 = new Uint16Array(256 * 256); + for (let i = 0; i < 256; i++) { + for (let j = 0; j < 256; j++) { + const idx = i * 256 + j; + T01[idx] = T0[i] ^ T1[j]; + T23[idx] = T2[i] ^ T3[j]; + sbox2[idx] = (sbox[i] << 8) | sbox[j]; } - b.sigBytes = 4 * q; - return b; - }, - })); - u.EvpKDF = function (d, l, p) { - return s.create(p).compute(d, l); - }; + } + return { sbox, sbox2, T0, T1, T2, T3, T01, T23 }; + } + // Forward round precompute: the packed word stores the MIXCOLUMNS row + // [{02},{01},{01},{03}] in LE byte-lane order, and the returned `sbox2` + // is also reused by key expansion and the final round. + const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)); + // Inverse round precompute: the packed word stores the INVMIXCOLUMNS row + // [{0e},{09},{0d},{0b}] in LE byte-lane order, and the tables are reused + // by decrypt() and expandKeyDecLE(). + const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)); + // FIPS 197 upd1 §5.2 Table 5: left-most bytes of Rcon[j] = x^(j-1), generated by repeated XTIMES(). + const xPowers = /* @__PURE__ */ (() => { + const p = new Uint8Array(16); + for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) + p[i] = x; + return p; })(); - - // Cipher - CryptoJS.lib.Cipher || - (function (u) { - var p = CryptoJS, - d = p.lib, - l = d.Base, - s = d.WordArray, - t = d.BufferedBlockAlgorithm, - r = p.enc.Base64, - w = p.algo.EvpKDF, - v = (d.Cipher = t.extend({ - cfg: l.extend(), - createEncryptor: function (e, a) { - return this.create(this._ENC_XFORM_MODE, e, a); - }, - createDecryptor: function (e, a) { - return this.create(this._DEC_XFORM_MODE, e, a); - }, - init: function (e, a, b) { - this.cfg = this.cfg.extend(b); - this._xformMode = e; - this._key = a; - this.reset(); - }, - reset: function () { - t.reset.call(this); - this._doReset(); - }, - process: function (e) { - this._append(e); - return this._process(); - }, - finalize: function (e) { - e && this._append(e); - return this._doFinalize(); - }, - keySize: 4, - ivSize: 4, - _ENC_XFORM_MODE: 1, - _DEC_XFORM_MODE: 2, - _createHelper: function (e) { - return { - encrypt: function (b, k, d) { - return ('string' == typeof k ? c : a).encrypt(e, b, k, d); - }, - decrypt: function (b, k, d) { - return ('string' == typeof k ? c : a).decrypt(e, b, k, d); - }, - }; - }, - })); - d.StreamCipher = v.extend({ - _doFinalize: function () { - return this._process(!0); - }, - blockSize: 1, - }); - var b = (p.mode = {}), - x = function (e, a, b) { - var c = this._iv; - c ? (this._iv = u) : (c = this._prevBlock); - for (var d = 0; d < b; d++) e[a + d] ^= c[d]; - }, - q = (d.BlockCipherMode = l.extend({ - createEncryptor: function (e, a) { - return this.Encryptor.create(e, a); - }, - createDecryptor: function (e, a) { - return this.Decryptor.create(e, a); + /** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */ + function expandKeyLE(key) { + abytes$1(key); + const len = key.length; + validateKeyLength(key); + const { sbox2 } = tableEncoding; + const toClean = []; + // Copy on BE or misaligned inputs so the LE word normalization below never + // mutates caller key bytes in place. + if (!isLE || !isAligned32(key)) + toClean.push((key = copyBytes(key))); + const k32 = swap32IfBE(u32(key)); + const Nk = k32.length; + // `applySbox` normally reads one byte lane from each argument; repeating + // `n` across all four lanes turns it into SUBWORD(n). + const subByte = (n) => applySbox(sbox2, n, n, n, n); + // AES key sizes are 16/24/32 bytes, so len + 28 yields the 44/52/60 + // schedule words from FIPS 197 §5.2 / Table 3. + const xk = new Uint32Array(len + 28); // expanded key + xk.set(k32); + // 4.3.1 Key expansion + for (let i = Nk; i < xk.length; i++) { + let t = xk[i - 1]; + if (i % Nk === 0) + t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1]; + else if (Nk > 6 && i % Nk === 4) + t = subByte(t); + xk[i] = xk[i - Nk] ^ t; + } + clean$1(...toClean); + return xk; + } + function expandKeyDecLE(key) { + const encKey = expandKeyLE(key); + const xk = encKey.slice(); + const Nk = encKey.length; + const { sbox2 } = tableEncoding; + const { T0, T1, T2, T3 } = tableDecoding; + // Local decrypt() walks round keys forward from xk[0], so reverse the + // encryption round-key blocks first before applying the equivalent-inverse + // middle-round transform. + for (let i = 0; i < Nk; i += 4) { + for (let j = 0; j < 4; j++) + xk[i + j] = encKey[Nk - i - 4 + j]; + } + clean$1(encKey); + // Apply InvMixColumn to the reversed round keys using the same LE sbox2 + // packing as the forward path. + // apply InvMixColumn except first & last round + for (let i = 4; i < Nk - 4; i++) { + const x = xk[i]; + const w = applySbox(sbox2, x, x, x, x); + xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24]; + } + return xk; + } + // Apply tables + function apply0123(T01, T23, s0, s1, s2, s3) { + // `T01` takes the low byte lane from `s0` plus the next lane from `s1`; + // `T23` does the same for `s2`/`s3`. + // Equivalent to `T0[s0&0xff] ^ T1[(s1>>>8)&0xff] ^ T2[(s2>>>16)&0xff] ^ + // T3[s3>>>24]`, but with two merged-table fetches. + return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^ + T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]); + } + function applySbox(sbox2, s0, s1, s2, s3) { + // `sbox2` packs two substituted byte lanes at a time in the same LE + // layout used by the round code. + // Equivalent to `SBOX(byte0(s0)) | SBOX(byte1(s1))<<8 | + // SBOX(byte2(s2))<<16 | SBOX(byte3(s3))<<24`. + return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] | + (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)); + } + function encrypt(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableEncoding; + let k = 0; + ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++])); + // `xk` has Nr+1 round-key blocks, so after the initial AddRoundKey and the + // final S-box-only round there are Nr-1 full table/MixColumns rounds left. + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2); + ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3)); + } + // last round (without mixcolumns, so using SBOX2 table) + const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; + } + // Can't be merged with encrypt: arg positions for apply0123 / applySbox are different + function decrypt(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableDecoding; + let k = 0; + ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++])); + // With `expandKeyDecLE()` the round keys are already reversed and middle + // rounds are InvMixColumns-adjusted, so this loop follows the equivalent + // inverse cipher order directly. + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0); + ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3)); + } + // Final equivalent-inverse round omits InvMixColumns, so use inverse + // S-box lanes in InvShiftRows order. + const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; + } + function validateBlockDecrypt(data, dst) { + abytes$1(data); + // ECB/CBC decryption always consumes whole ciphertext blocks; PKCS#7/CMS + // padding, when enabled, is removed only after decrypting the final block. + if (data.length % BLOCK_SIZE !== 0) { + throw new Error('ciphertext must be multiple of ' + BLOCK_SIZE); + } + // Validate caller-provided output before key expansion; allocation happens after it. + if (dst !== undefined) { + getOutput(data.length, dst); + complexOverlapBytes(data, dst); + } + } + // ECB/CBC core modes operate on whole blocks; `pkcs5` enables the library's + // PKCS#7/CMS-compatible final-block padding convenience before encryption. + function validateBlockEncrypt(plaintext, pkcs5, dst) { + abytes$1(plaintext); + let outLen = plaintext.length; + const remaining = outLen % BLOCK_SIZE; + if (!pkcs5 && remaining !== 0) + throw new Error('plaintext must be multiple of ' + BLOCK_SIZE); + if (pkcs5) { + let left = BLOCK_SIZE - remaining; + // RFC 5652 pads even already-aligned inputs, so a full extra block is + // appended when the plaintext length is already a multiple of 16 bytes. + if (!left) + left = BLOCK_SIZE; // if no bytes left, create empty padding block + outLen = outLen + left; + } + // Validate caller-provided output before key expansion; allocation happens after it. + if (dst !== undefined) { + getOutput(outLen, dst); + complexOverlapBytes(plaintext, dst); + } + return outLen; + } + function prepareBlockEncrypt(plaintext, outLen, dst) { + if (dst === undefined) + dst = new Uint8Array(outLen); + // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization never + // mutates caller plaintext bytes in place before ECB/CBC processing. + if (!isLE || !isAligned32(plaintext)) + plaintext = copyBytes(plaintext); + const o = u32(dst); + // Keep the full byte owner so callers can wipe a conditional copy without rebuilding a view. + return { b: plaintext, o, out: dst }; + } + // `pkcs5` is the historical option name; for AES's 16-byte block this is the + // generic PKCS#7/CMS-style block-padding rule on decrypt. + function validatePKCS(data, pkcs5) { + if (!pkcs5) + return data; + const len = data.length; + // RFC 5652 pads even empty / already-aligned inputs, so a valid padded + // ECB/CBC ciphertext is never empty when PKCS#7/CMS unpadding is enabled. + // AES-CBC/ECB ciphertext should be full blocks before unpadding + if (len === 0) + throw new Error('pkcs7: empty ciphertext not allowed'); + const lastByte = data[len - 1]; + let valid = 1; + valid &= ((lastByte - 1) >>> 31) ^ 1; // pad >= 1 + valid &= ((16 - lastByte) >>> 31) ^ 1; // pad <= 16 + // Check exactly 16 tail bytes in constant-shape loop + // For i < pad: byte must equal pad + // For i >= pad: ignore byte + for (let i = 0; i < 16; i++) { + // const b = data[len - 1 - i]; + const shouldCheck = (i - lastByte) >>> 31; // 1 if i < pad else 0 + const eq = (data[len - 1 - i] ^ lastByte) === 0 ? 1 : 0; // 1 if equal + valid &= eq | (shouldCheck ^ 1); // pass if equal OR not checked + } + // if (invalidLen) throw new Error('aes/pkcs7: ciphertext length must be multiple of 16'); + // Padding rejection is observable as a decrypt failure; authenticate CBC/ECB + // ciphertexts before decrypting or use `disablePadding` in a higher-level protocol. + if (!valid) + throw new Error('aes: bad decrypt'); + return data.subarray(0, len - lastByte); + } + // ECB/CBC callers only pass the final short block here, so `left.length` is + // 0..15 and the helper always emits exactly one padded 16-byte block. + function padPCKS(left) { + const tmp = new Uint8Array(16); + const tmp32 = u32(tmp); + tmp.set(left); + const paddingByte = BLOCK_SIZE - left.length; + // RFC 5652 §6.3 fills the whole suffix with the padding length byte: + // e.g. `aa 0f..0f` for a 1-byte tail, or `10..10` for a full extra block. + for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) + tmp[i] = paddingByte; + return tmp32; + } + /** + * **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the + * previous block of ciphertext before encryption. + * Hard to use: requires proper padding and an unpredictable IV. Unauthenticated: needs MAC. + * Bad padding is reported as decrypt failure, which can be a padding oracle if exposed. + * @param key - AES key bytes. + * @param iv - 16-byte unpredictable initialization vector. + * @param opts - Padding options. See {@link BlockOpts}. + * @returns Cipher instance with `encrypt()` and `decrypt()`. + * @example + * Encrypts a padded message with a fresh key and 16-byte IV. + * + * ```ts + * import { cbc } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const iv = randomBytes(16); + * const cipher = cbc(key, iv); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ + const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) { + const pkcs5 = !opts.disablePadding; + return { + encrypt(plaintext, dst) { + // Validate inputs before expanding the key, so a validation throw + // never leaves an unwiped expanded key behind. + const outLen = validateBlockEncrypt(plaintext, pkcs5, dst); + const xk = expandKeyLE(key); + const { b: input, o, out: _out } = prepareBlockEncrypt(plaintext, outLen, dst); + const b = u32(input); + swap32IfBE(b); + let _iv = iv; + const toClean = [xk]; + // Copy on BE or misaligned inputs so IV normalization and the mutable + // local chaining state never write back into caller IV bytes. + if (!isLE || !isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32(_iv); + swap32IfBE(n32); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + let i = 0; + for (; i + 4 <= b.length;) { + ((s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3])); + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3)); + } + if (pkcs5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + swap32IfBE(tmp32); + ((s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3])); + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3)); + // The padding scratch contains the final plaintext tail; wipe it as soon as consumed. + clean$1(tmp32); + } + swap32IfBE(o); + clean$1(...toClean); + if (input !== plaintext) + clean$1(input); + return _out; }, - init: function (e, a) { - this._cipher = e; - this._iv = a; + decrypt(ciphertext, dst) { + // Validate inputs before expanding the key, so a validation throw + // never leaves an unwiped expanded key behind. + validateBlockDecrypt(ciphertext, dst); + const xk = expandKeyDecLE(key); + if (dst === undefined) + dst = new Uint8Array(ciphertext.length); + let _iv = iv; + const toClean = [xk]; + // Copy on BE or misaligned inputs so IV normalization and the mutable + // local chaining state never write back into caller IV bytes. + if (!isLE || !isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32(_iv); + swap32IfBE(n32); + // Copy on BE or misaligned ciphertext so u32()/swap32IfBE() + // normalization never mutates caller bytes in place before decrypt(). + if (!isLE || !isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const b = u32(ciphertext); + const o = u32(dst); + swap32IfBE(b); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= b.length;) { + // prettier-ignore + const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3; + ((s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3])); + const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3); + ((o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3)); + } + swap32IfBE(o); + clean$1(...toClean); + return validatePKCS(dst, pkcs5); }, - })).extend(); - q.Encryptor = q.extend({ - processBlock: function (e, a) { - var b = this._cipher, - c = b.blockSize; - x.call(this, e, a, c); - b.encryptBlock(e, a); - this._prevBlock = e.slice(a, a + c); - }, - }); - q.Decryptor = q.extend({ - processBlock: function (e, a) { - var b = this._cipher, - c = b.blockSize, - d = e.slice(a, a + c); - b.decryptBlock(e, a); - x.call(this, e, a, c); - this._prevBlock = d; - }, - }); - b = b.CBC = q; - q = (p.pad = {}).Pkcs7 = { - pad: function (a, b) { - for ( - var c = 4 * b, c = c - (a.sigBytes % c), d = (c << 24) | (c << 16) | (c << 8) | c, l = [], n = 0; - n < c; - n += 4 - ) - l.push(d); - c = s.create(l, c); - a.concat(c); - }, - unpad: function (a) { - a.sigBytes -= a.words[(a.sigBytes - 1) >>> 2] & 255; - }, }; - d.BlockCipher = v.extend({ - cfg: v.cfg.extend({ mode: b, padding: q }), - reset: function () { - v.reset.call(this); - var a = this.cfg, - b = a.iv, - a = a.mode; - if (this._xformMode == this._ENC_XFORM_MODE) var c = a.createEncryptor; - else (c = a.createDecryptor), (this._minBufferSize = 1); - this._mode = c.call(a, this, b && b.words); - }, - _doProcessBlock: function (a, b) { - this._mode.processBlock(a, b); - }, - _doFinalize: function () { - var a = this.cfg.padding; - if (this._xformMode == this._ENC_XFORM_MODE) { - a.pad(this._data, this.blockSize); - var b = this._process(!0); - } else (b = this._process(!0)), a.unpad(b); - return b; - }, - blockSize: 4, - }); - var n = (d.CipherParams = l.extend({ - init: function (a) { - this.mixIn(a); - }, - toString: function (a) { - return (a || this.formatter).stringify(this); - }, - })), - b = ((p.format = {}).OpenSSL = { - stringify: function (a) { - var b = a.ciphertext; - a = a.salt; - return (a ? s.create([1398893684, 1701076831]).concat(a).concat(b) : b).toString(r); - }, - parse: function (a) { - a = r.parse(a); - var b = a.words; - if (1398893684 == b[0] && 1701076831 == b[1]) { - var c = s.create(b.slice(2, 4)); - b.splice(0, 4); - a.sigBytes -= 16; - } - return n.create({ ciphertext: a, salt: c }); - }, - }), - a = (d.SerializableCipher = l.extend({ - cfg: l.extend({ format: b }), - encrypt: function (a, b, c, d) { - d = this.cfg.extend(d); - var l = a.createEncryptor(c, d); - b = l.finalize(b); - l = l.cfg; - return n.create({ - ciphertext: b, - key: c, - iv: l.iv, - algorithm: a, - mode: l.mode, - padding: l.padding, - blockSize: a.blockSize, - formatter: d.format, - }); - }, - decrypt: function (a, b, c, d) { - d = this.cfg.extend(d); - b = this._parse(b, d.format); - return a.createDecryptor(c, d).finalize(b.ciphertext); - }, - _parse: function (a, b) { - return 'string' == typeof a ? b.parse(a, this) : a; - }, - })), - p = ((p.kdf = {}).OpenSSL = { - execute: function (a, b, c, d) { - d || (d = s.random(8)); - a = w.create({ keySize: b + c }).compute(a, d); - c = s.create(a.words.slice(b), 4 * c); - a.sigBytes = 4 * b; - return n.create({ key: a, iv: c, salt: d }); - }, - }), - c = (d.PasswordBasedCipher = a.extend({ - cfg: a.cfg.extend({ kdf: p }), - encrypt: function (b, c, d, l) { - l = this.cfg.extend(l); - d = l.kdf.execute(d, b.keySize, b.ivSize); - l.iv = d.iv; - b = a.encrypt.call(this, b, c, d.key, l); - b.mixIn(d); - return b; - }, - decrypt: function (b, c, d, l) { - l = this.cfg.extend(l); - c = this._parse(c, l.format); - d = l.kdf.execute(d, b.keySize, b.ivSize, c.salt); - l.iv = d.iv; - return a.decrypt.call(this, b, c, d.key, l); - }, - })); - })(); - - // AES - (function () { - for ( - var u = CryptoJS, - p = u.lib.BlockCipher, - d = u.algo, - l = [], - s = [], - t = [], - r = [], - w = [], - v = [], - b = [], - x = [], - q = [], - n = [], - a = [], - c = 0; - 256 > c; - c++ - ) - a[c] = 128 > c ? c << 1 : (c << 1) ^ 283; - for (var e = 0, j = 0, c = 0; 256 > c; c++) { - var k = j ^ (j << 1) ^ (j << 2) ^ (j << 3) ^ (j << 4), - k = (k >>> 8) ^ (k & 255) ^ 99; - l[e] = k; - s[k] = e; - var z = a[e], - F = a[z], - G = a[F], - y = (257 * a[k]) ^ (16843008 * k); - t[e] = (y << 24) | (y >>> 8); - r[e] = (y << 16) | (y >>> 16); - w[e] = (y << 8) | (y >>> 24); - v[e] = y; - y = (16843009 * G) ^ (65537 * F) ^ (257 * z) ^ (16843008 * e); - b[k] = (y << 24) | (y >>> 8); - x[k] = (y << 16) | (y >>> 16); - q[k] = (y << 8) | (y >>> 24); - n[k] = y; - e ? ((e = z ^ a[a[a[G ^ z]]]), (j ^= a[a[j]])) : (e = j = 1); - } - var H = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54], - d = (d.AES = p.extend({ - _doReset: function () { - for ( - var a = this._key, - c = a.words, - d = a.sigBytes / 4, - a = 4 * ((this._nRounds = d + 6) + 1), - e = (this._keySchedule = []), - j = 0; - j < a; - j++ - ) - if (j < d) e[j] = c[j]; - else { - var k = e[j - 1]; - j % d - ? 6 < d && - 4 == j % d && - (k = (l[k >>> 24] << 24) | (l[(k >>> 16) & 255] << 16) | (l[(k >>> 8) & 255] << 8) | l[k & 255]) - : ((k = (k << 8) | (k >>> 24)), - (k = (l[k >>> 24] << 24) | (l[(k >>> 16) & 255] << 16) | (l[(k >>> 8) & 255] << 8) | l[k & 255]), - (k ^= H[(j / d) | 0] << 24)); - e[j] = e[j - d] ^ k; - } - c = this._invKeySchedule = []; - for (d = 0; d < a; d++) - (j = a - d), - (k = d % 4 ? e[j] : e[j - 4]), - (c[d] = - 4 > d || 4 >= j ? k : b[l[k >>> 24]] ^ x[l[(k >>> 16) & 255]] ^ q[l[(k >>> 8) & 255]] ^ n[l[k & 255]]); - }, - encryptBlock: function (a, b) { - this._doCryptBlock(a, b, this._keySchedule, t, r, w, v, l); - }, - decryptBlock: function (a, c) { - var d = a[c + 1]; - a[c + 1] = a[c + 3]; - a[c + 3] = d; - this._doCryptBlock(a, c, this._invKeySchedule, b, x, q, n, s); - d = a[c + 1]; - a[c + 1] = a[c + 3]; - a[c + 3] = d; - }, - _doCryptBlock: function (a, b, c, d, e, j, l, f) { - for ( - var m = this._nRounds, - g = a[b] ^ c[0], - h = a[b + 1] ^ c[1], - k = a[b + 2] ^ c[2], - n = a[b + 3] ^ c[3], - p = 4, - r = 1; - r < m; - r++ - ) - var q = d[g >>> 24] ^ e[(h >>> 16) & 255] ^ j[(k >>> 8) & 255] ^ l[n & 255] ^ c[p++], - s = d[h >>> 24] ^ e[(k >>> 16) & 255] ^ j[(n >>> 8) & 255] ^ l[g & 255] ^ c[p++], - t = d[k >>> 24] ^ e[(n >>> 16) & 255] ^ j[(g >>> 8) & 255] ^ l[h & 255] ^ c[p++], - n = d[n >>> 24] ^ e[(g >>> 16) & 255] ^ j[(h >>> 8) & 255] ^ l[k & 255] ^ c[p++], - g = q, - h = s, - k = t; - q = ((f[g >>> 24] << 24) | (f[(h >>> 16) & 255] << 16) | (f[(k >>> 8) & 255] << 8) | f[n & 255]) ^ c[p++]; - s = ((f[h >>> 24] << 24) | (f[(k >>> 16) & 255] << 16) | (f[(n >>> 8) & 255] << 8) | f[g & 255]) ^ c[p++]; - t = ((f[k >>> 24] << 24) | (f[(n >>> 16) & 255] << 16) | (f[(g >>> 8) & 255] << 8) | f[h & 255]) ^ c[p++]; - n = ((f[n >>> 24] << 24) | (f[(g >>> 16) & 255] << 16) | (f[(h >>> 8) & 255] << 8) | f[k & 255]) ^ c[p++]; - a[b] = q; - a[b + 1] = s; - a[b + 2] = t; - a[b + 3] = n; - }, - keySize: 8, - })); - u.AES = p._createHelper(d); - })(); - - // Mode ECB - CryptoJS.mode.ECB = (function () { - var ECB = CryptoJS.lib.BlockCipherMode.extend(); + }); - ECB.Encryptor = ECB.extend({ - processBlock: function (words, offset) { - this._cipher.encryptBlock(words, offset); - }, - }); + // Split a JS number into u32 halves without a BigInt allocation. Exact only for integers + // `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below + // that (an ArrayBuffer cannot exceed 2**53 - 1 bytes). + const fromNumH = (n) => (n / 2 ** 32) | 0; + const fromNumL = (n) => n >>> 0; + // Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call + // BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`. + function setU64FromNum(view, byteOffset, n, isLE) { + const h = fromNumH(n); + const l = fromNumL(n); + view.setUint32(byteOffset, isLE ? l : h, isLE); + view.setUint32(byteOffset + 4, isLE ? h : l, isLE); + } - ECB.Decryptor = ECB.extend({ - processBlock: function (words, offset) { - this._cipher.decryptBlock(words, offset); - }, - }); + /** + * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. + * @param a - value to test + * @returns `true` when the value is a Uint8Array-compatible view. + * @example + * Check whether a value is a Uint8Array-compatible view. + * ```ts + * isBytes(new Uint8Array([1, 2, 3])); + * ``` + */ + function isBytes(a) { + // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. + // The fallback still requires a real ArrayBuffer view, so plain + // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and + // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views. + return (a instanceof Uint8Array || + (ArrayBuffer.isView(a) && + a.constructor.name === 'Uint8Array' && + 'BYTES_PER_ELEMENT' in a && + a.BYTES_PER_ELEMENT === 1)); + } + // Shared error-message prefix builder. Only called on throw paths, so assert + // success paths never pay for the string concatenation. + const atitle = (title) => (title ? `"${title}" ` : ''); + /** + * Asserts something is Uint8Array. + * @param value - value to validate + * @param length - optional exact length constraint + * @param title - label included in thrown errors + * @returns The validated byte array. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate that a value is a byte array. + * ```ts + * abytes(new Uint8Array([1, 2, 3])); + * ``` + */ + function abytes(value, length, title = '') { + // Success path first: this runs at the start of every update() / digestInto(), and the + // common `abytes(data)` form must not pay for length handling it does not use. + if (isBytes(value) && (length === undefined)) + return value; + const bytes = isBytes(value); + const ofLen = ''; + const got = bytes ? `length=${value.length}` : `type=${typeof value}`; + const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got; + if (!bytes) + throw new TypeError(message); + throw new RangeError(message); + } + const aobject = (value, label) => { + if (value === null || typeof value !== 'object' || Array.isArray(value)) + throw new TypeError((label === 'object' ? '' : `"${label}" `) + 'expected object, got type=' + typeof value); + }; + const aopts = (value, label) => { + aobject(value, label); + const proto = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== null) + throw new TypeError(`"${label}" expected plain object`); + // Object.assign() treats an own "__proto__" source key as a write to the target's legacy + // prototype setter. Reject it before merging so inherited option values cannot be injected. + if (Object.hasOwn(value, '__proto__')) + throw new TypeError(`"${label}.__proto__" is not allowed`); + }; + /** + * Asserts a hash instance has not been destroyed or finished. + * @param instance - hash instance to validate + * @param checkFinished - whether to reject finalized instances + * @throws If the hash instance has already been destroyed or finalized. {@link Error} + * @example + * Validate that a hash instance is still usable. + * ```ts + * import { aexists } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hash = sha256.create(); + * aexists(hash); + * ``` + */ + function aexists(instance, checkFinished = true) { + // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their + // truthiness is checked - re-validating their type per call was pure hot-path overhead. + if (instance.destroyed) + throw new Error('hash was destroyed'); + if (checkFinished && instance.finished) + throw new Error('digest() was already called'); + } + /** + * Asserts output is a sufficiently-sized byte array. + * @param out - destination buffer + * @param instance - hash instance providing output length + * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a caller-provided digest buffer. + * ```ts + * import { aoutput } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hash = sha256.create(); + * aoutput(new Uint8Array(hash.outputLen), hash); + * ``` + */ + function aoutput(out, instance) { + abytes(out, undefined, 'output'); + // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast + // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call. + const min = instance.outputLen; + if (!(out.length >= min)) { + throw new RangeError('"output" expected length >= ' + min); + } + } + /** + * Zeroizes typed arrays in place. Warning: JS provides no guarantees. + * @param arrays - arrays to overwrite with zeros + * @example + * Zeroize sensitive buffers in place. + * ```ts + * clean(new Uint8Array([1, 2, 3])); + * ``` + */ + function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } + } + /** + * Creates a DataView for byte-level manipulation. + * @param arr - source typed array + * @returns DataView over the same buffer region. + * @example + * Create a DataView over an existing buffer. + * ```ts + * createView(new Uint8Array(4)); + * ``` + */ + function createView(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + } + /** + * Rotate-right operation for uint32 values. + * @param word - source word + * @param shift - shift amount in bits + * @returns Rotated word. + * @example + * Rotate a 32-bit word to the right. + * ```ts + * rotr(0x12345678, 8); + * ``` + */ + function rotr(word, shift) { + return (word << (32 - shift)) | (word >>> shift); + } + /** + * Merges default options and passed options. + * @param defaults - base option object + * @param opts - user overrides + * @param title - label included in thrown override errors + * @returns Fresh merged option object with a null prototype. + * @throws On wrong argument types. {@link TypeError} + * @example + * Merge user overrides onto default options. + * ```ts + * checkOpts({ dkLen: 32 }, { asyncTick: 10 }); + * ``` + */ + function checkOpts(defaults, opts, title = 'opts') { + aopts(defaults, 'defaults'); + if (opts !== undefined) + aopts(opts, title); + // Callers read optional fields directly, so omitted values must not fall through to ambient + // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output). + const merged = Object.assign(Object.create(null), defaults, opts); + return merged; + } + /** + * Creates a callable hash function from a stateful class constructor. + * @param hashCons - hash constructor or factory + * @param info - optional metadata such as DER OID + * @returns Frozen callable hash wrapper with `.create()`. + * Wrapper construction eagerly calls `hashCons(undefined)` once to read + * `outputLen` / `blockLen`, so constructor side effects happen at module + * init time. + * @throws On wrong argument types. {@link TypeError} + * @example + * Wrap a stateful hash constructor into a callable helper. + * ```ts + * import { createHasher } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const wrapped = createHasher(sha256.create, { oid: sha256.oid }); + * wrapped(new Uint8Array([1])); + * ``` + */ + function createHasher(hashCons, info = {}) { + if (typeof hashCons !== 'function') + throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons); + info = checkOpts({}, info, 'info'); + const hashC = (msg, opts) => hashCons(opts) + .update(msg) + .digest(); + const tmp = hashCons(undefined); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.canXOF = tmp.canXOF; + hashC.create = (opts) => hashCons(opts); + Object.assign(hashC, info); + return Object.freeze(hashC); + } + /** + * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`. + * @param suffix - final OID byte for the selected hash. + * The helper accepts any byte even though only the documented NIST hash + * suffixes are meaningful downstream. + * @returns Object containing the DER-encoded OID. + * @example + * Build OID metadata for a NIST hash. + * ```ts + * oidNist(0x01); + * ``` + */ + const oidNist = (suffix) => ({ + // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet. + // Larger suffix values would need base-128 OID encoding and a different length byte. + oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]), + }); - return ECB; - })(); + /** + * Internal Merkle-Damgard hash utils. + * @module + */ + /** + * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`. + * Returns bits from `b` when `a` is set, otherwise from `c`. + * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never + * set the same bit. + * @param a - selector word + * @param b - word chosen when selector bit is set + * @param c - word chosen when selector bit is clear + * @returns Mixed 32-bit word. + * @example + * Combine three words with the shared 32-bit choice primitive. + * ```ts + * Chi(0xffffffff, 0x12345678, 0x87654321); + * ``` + */ + function Chi(a, b, c) { + return (a & b) ^ (~a & c); + } + /** + * Shared 32-bit majority primitive reused by SHA-256 and SHA-1. + * Returns bits shared by at least two inputs. + * @param a - first input word + * @param b - second input word + * @param c - third input word + * @returns Mixed 32-bit word. + * @example + * Combine three words with the shared 32-bit majority primitive. + * ```ts + * Maj(0xffffffff, 0x12345678, 0x87654321); + * ``` + */ + function Maj(a, b, c) { + return (a & b) ^ (a & c) ^ (b & c); + } + /** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit + * strings with partial-byte tails. + * @param blockLen - internal block size in bytes + * @param outputLen - digest size in bytes + * @param padOffset - trailing length field size in bytes + * @param isLE - whether length and state words are encoded in little-endian + * @example + * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow. + * ```ts + * import { _SHA1 } from '@noble/hashes/legacy.js'; + * const hash = new _SHA1(); + * hash.update(new Uint8Array([97, 98, 99])); + * hash.digest(); + * ``` + */ + class HashMD { + blockLen; + outputLen; + canXOF = false; + padOffset; + isLE; + // For partial updates less than block size + buffer; + view; + finished = false; + length = 0; + pos = 0; + destroyed = false; + constructor(blockLen, outputLen, padOffset, isLE) { + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + aexists(this); + abytes(data); + const { view, buffer, blockLen } = this; + const len = data.length; + let processed = false; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path only when there is no buffered partial block: `take === blockLen` implies + // `this.pos === 0`, so we can process full blocks directly from the input view. + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + processed = true; + continue; + } + // When the whole input is buffered in one go (common for short messages), passing `data` + // directly avoids allocating a subarray view. + buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + processed = true; + } + } + this.length += data.length; + // Shared schedule buffers only pick up input-derived words inside process(); if everything + // was buffered without processing, there is nothing to zero. + if (processed) + this.roundClean(); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message, then zero-pad the rest of the block + buffer[pos++] = 0b10000000; + buffer.fill(0, pos); + // we have less than padOffset left in buffer, so we cannot put length in + // current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + buffer.fill(0); + } + // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from + // the padding fill above, and JS will overflow before user input can make that half non-zero. + // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an + // integer below 2**53, so the split inside the helper stays exact). + setU64FromNum(view, blockLen - 8, this.length * 8, isLE); + this.process(view, 0); + // The final block above is processed outside update(), so the shared message-schedule + // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest(). + this.roundClean(); + // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one. + const oview = out === buffer ? view : createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT + const outLen = len / 4; + const state = this.get(); + // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state. + if (len % 4 || outLen > state.length) + throw new Error('invalid outputLen'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return + // fresh bytes to the caller. + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneIntoMeta(to) { + const { buffer, length, finished, destroyed, pos } = this; + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and + // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it. + if (pos) + to.buffer.set(buffer); // Avoid a hot modulo guard. + return to; + } + clone() { + return this._cloneInto(); + } + } + /** + * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53. + * Check out `test/misc/sha2-gen-iv.js` for recomputation guide. + */ + /** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the + * square roots of the first eight prime numbers. Exported as a shared table; callers must treat + * it as read-only because constructors copy words from it by index. */ + const SHA256_IV = /* @__PURE__ */ Uint32Array.from([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, + ]); - var hmacSha256 = CryptoJS; + /** + * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256. + * SHA256 is the fastest hash implementable in JS, even faster than Blake3. + * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and + * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}. + * @module + */ + /** + * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits + * of the cube roots of the first 64 primes (2..311). + */ + // prettier-ignore + const SHA256_K = /* @__PURE__ */ Uint32Array.from([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + ]); + /** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */ + const SHA256_W = /* @__PURE__ */ new Uint32Array(64); + /** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */ + class SHA2_32B extends HashMD { + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + // Numeric initializers matter: starting the fields as `undefined` changes + // V8's field representation and makes sha256 3x slower (measured). + A = 0; + B = 0; + C = 0; + D = 0; + E = 0; + F = 0; + G = 0; + H = 0; + constructor(outputLen, IV) { + super(64, outputLen, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + _cloneInto(to) { + (to ||= new this.constructor()).set(...this.get()); + return this._cloneIntoMeta(to); + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + clean(SHA256_W); + } + destroy() { + // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves + // update()/digest() callable on reused instances. + this.destroyed = true; + this.set(0, 0, 0, 0, 0, 0, 0, 0); + clean(this.buffer); + } + } + /** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */ + class _SHA256 extends SHA2_32B { + constructor() { + super(32, SHA256_IV); + } + } + /** + * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info: + * + * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack. + * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025. + * - Each sha256 hash is executing 2^18 bit operations. + * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule. + * @param msg - message bytes to hash + * @param opts - Reserved hash options. + * @returns Digest bytes. + * @example + * Hash a message with SHA2-256. + * ```ts + * sha256(new Uint8Array([97, 98, 99])); + * ``` + */ + const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), + /* @__PURE__ */ oidNist(0x01)); - var CryptoJS$1 = /*@__PURE__*/getDefaultExportFromCjs(hmacSha256); + /** + * Platform-agnostic cryptography primitives contract and byte helpers. + * + * @internal + */ + /** + * Encode string to UTF-8 bytes. + * + * **Note:** Strings with lone surrogates are rejected (as CryptoJS `Utf8.parse` did through `encodeURIComponent`) + * instead of being silently replaced with `U+FFFD` by `TextEncoder`. + * + * @param string - Source string. + * + * @returns UTF-8 bytes. + * + * @throws URIError if `string` contains lone surrogates. + * + * @internal + */ + const encodeUtf8 = (string) => { + for (let i = 0; i < string.length; i++) { + const code = string.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff) { + const next = i + 1 < string.length ? string.charCodeAt(i + 1) : 0; + if (next < 0xdc00 || next > 0xdfff) + throw new URIError('URI malformed'); + i++; + } + else if (code >= 0xdc00 && code <= 0xdfff) + throw new URIError('URI malformed'); + } + return new TextEncoder().encode(string); + }; + /** + * Check whether bytes are well-formed UTF-8 (Unicode Table 3-7). + * + * Rejects the same sequences as `decodeURIComponent` (used by CryptoJS `Utf8.stringify`): invalid lead and + * continuation bytes, truncated, overlong, surrogate (`U+D800`–`U+DFFF`) and out of range (> `U+10FFFF`) sequences. + * + * **Note:** Bytes are validated (rather than decoded `U+FFFD` characters) because `U+FFFD` can be legitimate input. + * + * @param bytes - Bytes which should be validated. + * + * @returns `true` if `bytes` are well-formed UTF-8. + * + * @internal + */ + const isWellFormedUtf8 = (bytes) => { + const length = bytes.length; + let i = 0; + while (i < length) { + const lead = bytes[i]; + if (lead <= 0x7f) { + i++; + continue; + } + let count; + let min = 0x80; + let max = 0xbf; + if (lead >= 0xc2 && lead <= 0xdf) + count = 1; + else if (lead >= 0xe0 && lead <= 0xef) { + count = 2; + if (lead === 0xe0) + min = 0xa0; + else if (lead === 0xed) + max = 0x9f; + } + else if (lead >= 0xf0 && lead <= 0xf4) { + count = 3; + if (lead === 0xf0) + min = 0x90; + else if (lead === 0xf4) + max = 0x8f; + } + else + return false; + // Truncated sequence. + if (i + count >= length) + return false; + if (bytes[i + 1] < min || bytes[i + 1] > max) + return false; + for (let j = 2; j <= count; j++) + if (bytes[i + j] < 0x80 || bytes[i + j] > 0xbf) + return false; + i += count + 1; + } + return true; + }; + /** + * Decode UTF-8 bytes to string. + * + * Preserves CryptoJS `Utf8.stringify` contract: + * - malformed UTF-8 is rejected (React Native `TextDecoder` polyfill doesn't support `fatal` option, so bytes + * validated with {@link isWellFormedUtf8}); + * - leading BOM is preserved (native `TextDecoder` strips it by default, the polyfill keeps it). + * + * @param bytes - UTF-8 bytes. + * + * @returns Decoded string. + * + * @throws Error if `bytes` aren't well-formed UTF-8. + * + * @internal + */ + const decodeUtf8 = (bytes) => { + if (!isWellFormedUtf8(bytes)) + throw new Error('Malformed UTF-8 data'); + const string = new TextDecoder().decode(bytes); + const hasBOM = bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf; + return hasBOM && string.charCodeAt(0) !== 0xfeff ? `${string}` : string; + }; + /** + * Remove block cipher padding leniently. + * + * Mirrors CryptoJS `Pkcs7.unpad`: strips the number of bytes stored in the last byte without validating padding + * bytes (so data padded with ANSI X.923 or ISO 10126 schemes still decrypts as before). + * + * @param bytes - Decrypted bytes with padding. + * + * @returns Bytes without padding (empty if padding length exceeds data length). + * + * @internal + */ + const unpadLegacy = (bytes) => { + const padding = bytes.length ? bytes[bytes.length - 1] : 0; + return padding > bytes.length ? new Uint8Array(0) : bytes.subarray(0, bytes.length - padding); + }; + /** + * Convert bytes to lowercase hex string. + * + * @param bytes - Source bytes. + * + * @returns Hex string. + * + * @internal + */ + const bytesToHex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); + /** + * Convert hex string to bytes. + * + * @param hex - Hex string. + * + * @returns Decoded bytes. + * + * @internal + */ + const hexToBytes = (hex) => { var _a; return Uint8Array.from((_a = hex.match(/.{1,2}/g)) !== null && _a !== void 0 ? _a : [], (byte) => parseInt(byte, 16)); }; + /** + * Concatenate two bytes arrays. + * + * @param a - First bytes array. + * @param b - Second bytes array. + * + * @returns Concatenated bytes. + * + * @internal + */ + const concatBytes = (a, b) => { + const result = new Uint8Array(a.length + b.length); + result.set(a); + result.set(b, a.length); + return result; + }; + /** + * Copy bytes into standalone `ArrayBuffer`. + * + * **Important:** Primitives may return views into larger buffers (noble subarrays, Node.js `Buffer` pool), so the + * underlying `.buffer` must never be used directly. + * + * @param bytes - Source bytes (possibly a view). + * + * @returns `ArrayBuffer` with exactly `bytes` content. + * + * @internal + */ + const toArrayBuffer = (bytes) => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength); /** * AES-CBC cryptor module. @@ -1925,8 +2548,7 @@ class AesCbcCryptor { constructor({ cipherKey }) { this.cipherKey = cipherKey; - this.CryptoJS = CryptoJS$1; - this.encryptedKey = this.CryptoJS.SHA256(cipherKey); + this.encryptedKey = sha256(encodeUtf8(cipherKey)); } // -------------------------------------------------------- // --------------------- Encryption ----------------------- @@ -1937,13 +2559,8 @@ if (stringData.length === 0) throw new Error('encryption error. empty content'); const abIv = this.getIv(); - return { - metadata: abIv, - data: decode(this.CryptoJS.AES.encrypt(data, this.encryptedKey, { - iv: this.bufferToWordArray(abIv), - mode: this.CryptoJS.mode.CBC, - }).ciphertext.toString(this.CryptoJS.enc.Base64)), - }; + const plaintext = typeof data === 'string' ? encodeUtf8(data) : new Uint8Array(data); + return { metadata: abIv, data: toArrayBuffer(cbc(this.encryptedKey, abIv).encrypt(plaintext)) }; } encryptFileData(data) { return __awaiter(this, void 0, void 0, function* () { @@ -1963,12 +2580,13 @@ decrypt(encryptedData) { if (typeof encryptedData.data === 'string') throw new Error('Decryption error: data for decryption should be ArrayBuffed.'); - const iv = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.metadata)); - const data = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.data)); - return AesCbcCryptor.encoder.encode(this.CryptoJS.AES.decrypt({ ciphertext: data }, this.encryptedKey, { - iv, - mode: this.CryptoJS.mode.CBC, - }).toString(this.CryptoJS.enc.Utf8)).buffer; + const iv = new Uint8Array(encryptedData.metadata); + const data = new Uint8Array(encryptedData.data); + // Padding removed leniently and decrypted data must be well-formed UTF-8 (CryptoJS-compatible). + const plaintext = unpadLegacy(cbc(this.encryptedKey, iv, { disablePadding: true }).decrypt(data)); + if (!isWellFormedUtf8(plaintext)) + throw new Error('Malformed UTF-8 data'); + return toArrayBuffer(plaintext); } decryptFileData(encryptedData) { return __awaiter(this, void 0, void 0, function* () { @@ -2014,21 +2632,6 @@ return crypto.subtle.importKey('raw', abHash, this.algo, true, ['encrypt', 'decrypt']); }); } - /** - * Convert bytes array to words array. - * - * @param b - Bytes array (buffer) which should be converted. - * - * @returns Word sized array. - */ - bufferToWordArray(b) { - const wa = []; - let i; - for (i = 0; i < b.length; i += 1) { - wa[(i / 4) | 0] |= b[i] << (24 - 8 * i); - } - return this.CryptoJS.lib.WordArray.create(wa, b.length); - } /** * Serialize cryptor information to string. * @@ -2051,6 +2654,47 @@ */ AesCbcCryptor.decoder = new TextDecoder(); + /** + * Cryptography primitives backed by `@noble` (Web, React Native). + * + * @internal + */ + /** + * Prepare AES-CBC cipher instance. + * + * **Note:** AES-ECB isn't reachable through public API and intentionally not bundled. + * + * @param mode - AES block cipher mode. + * @param key - AES key. + * @param iv - Initialization vector. + * + * @returns AES-CBC cipher. + * + * @internal + */ + const aesCipher = (mode, key, iv, decrypt = false) => { + if (mode === 'ecb') + throw new Error('AES-ECB is not supported'); + // Padding removed leniently by `unpadLegacy` on decryption (CryptoJS-compatible). + return cbc(key, iv, decrypt ? { disablePadding: true } : undefined); + }; + /** + * `@noble`-based cryptography primitives. + * + * **Note:** Request signature (HMAC-SHA256) is Node.js-only and intentionally not bundled. + * + * @internal + */ + const noblePrimitives = { + sha256: (data) => sha256(data), + hmacSha256: () => { + throw new Error('HMAC-SHA256 is not supported on this platform'); + }, + aesEncrypt: (mode, key, iv, data) => aesCipher(mode, key, iv).encrypt(data), + aesDecrypt: (mode, key, iv, data) => unpadLegacy(aesCipher(mode, key, iv, true).decrypt(data)), + randomBytes: (length) => randomBytes(length), + }; + /** * PubNub package utilities module. * @@ -2241,35 +2885,25 @@ /** * Legacy cryptography module. * + * Platform-agnostic implementation which relies on platform-provided crypto primitives. + * * @internal */ /** - * Convert bytes array to words array. - * - * @param b - Bytes array (buffer) which should be converted. - * - * @returns Word sized array. + * Whether insecure random initialization vector fallback warning has been printed. * * @internal */ - /* eslint-disable @typescript-eslint/no-explicit-any */ - function bufferToWordArray(b) { - const wa = []; - let i; - for (i = 0; i < b.length; i += 1) { - wa[(i / 4) | 0] |= b[i] << (24 - 8 * i); - } - // @ts-expect-error Bundled library without types. - return CryptoJS$1.lib.WordArray.create(wa, b.length); - } + let insecureRandomWarningShown = false; /** * Legacy cryptography module for files and signature. * * @internal */ - class Crypto { - constructor(configuration) { + class LegacyCrypto { + constructor(configuration, primitives) { this.configuration = configuration; + this.primitives = primitives; /** * Crypto initialization vector. */ @@ -2328,10 +2962,9 @@ * @returns HMAC-SHA256 hash from provided `data`. */ HMACSHA256(data) { - // @ts-expect-error Bundled library without types. - const hash = CryptoJS$1.HmacSHA256(data, this.configuration.secretKey); - // @ts-expect-error Bundled library without types. - return hash.toString(CryptoJS$1.enc.Base64); + var _a; + const hash = this.primitives.hmacSha256(encodeUtf8((_a = this.configuration.secretKey) !== null && _a !== void 0 ? _a : ''), encodeUtf8(data)); + return encode(toArrayBuffer(hash)); } /** * Generate SHA256 hash from input data. @@ -2341,8 +2974,7 @@ * @returns SHA256 hash from provided `data`. */ SHA256(data) { - // @ts-expect-error Bundled library without types. - return CryptoJS$1.SHA256(data).toString(CryptoJS$1.enc.Hex); + return bytesToHex(this.primitives.sha256(encodeUtf8(data))); } /** * Encrypt provided data. @@ -2399,21 +3031,19 @@ ignoredKeys: isSensitiveLogKey, })); } + if (typeof data !== 'string') + throw new Error('Encryption error: data should be a string'); options = this.parseOptions(options); const mode = this.getMode(options); const cipherKey = this.getPaddedKey(decidedCipherKey, options); + const plaintext = encodeUtf8(data); if (this.configuration.useRandomIVs) { - const waIv = this.getRandomIV(); - // @ts-expect-error Bundled library without types. - const waPayload = CryptoJS$1.AES.encrypt(data, cipherKey, { iv: waIv, mode }).ciphertext; - // @ts-expect-error Bundled library without types. - return waIv.clone().concat(waPayload.clone()).toString(CryptoJS$1.enc.Base64); + const iv = this.getRandomIV(); + const payload = this.primitives.aesEncrypt(mode, cipherKey, iv, plaintext); + return encode(toArrayBuffer(concatBytes(iv, payload))); } - const iv = this.getIV(options); - // @ts-expect-error Bundled library without types. - const encryptedHexArray = CryptoJS$1.AES.encrypt(data, cipherKey, { iv, mode }).ciphertext; - // @ts-expect-error Bundled library without types. - const base64Encrypted = encryptedHexArray.toString(CryptoJS$1.enc.Base64); + const encrypted = this.primitives.aesEncrypt(mode, cipherKey, this.getIV(options), plaintext); + const base64Encrypted = encode(toArrayBuffer(encrypted)); return base64Encrypted || data; } /** @@ -2441,14 +3071,11 @@ const mode = this.getMode(options); const cipherKey = this.getPaddedKey(decidedCipherKey, options); if (this.configuration.useRandomIVs) { - const ciphertext = new Uint8ClampedArray(decode(data)); - const iv = bufferToWordArray(ciphertext.slice(0, 16)); - const payload = bufferToWordArray(ciphertext.slice(16)); + const ciphertext = new Uint8Array(decode(data)); + const iv = ciphertext.slice(0, 16); + const payload = ciphertext.slice(16); try { - // @ts-expect-error Bundled library without types. - const plainJSON = CryptoJS$1.AES.decrypt({ ciphertext: payload }, cipherKey, { iv, mode }).toString( - // @ts-expect-error Bundled library without types. - CryptoJS$1.enc.Utf8); + const plainJSON = decodeUtf8(this.primitives.aesDecrypt(mode, cipherKey, iv, payload)); return JSON.parse(plainJSON); } catch (e) { @@ -2460,10 +3087,8 @@ else { const iv = this.getIV(options); try { - // @ts-expect-error Bundled library without types. - const ciphertext = CryptoJS$1.enc.Base64.parse(data); - // @ts-expect-error Bundled library without types. - const plainJSON = CryptoJS$1.AES.decrypt({ ciphertext }, cipherKey, { iv, mode }).toString(CryptoJS$1.enc.Utf8); + const ciphertext = new Uint8Array(decode(data)); + const plainJSON = decodeUtf8(this.primitives.aesDecrypt(mode, cipherKey, iv, ciphertext)); return JSON.parse(plainJSON); } catch (e) { @@ -2506,16 +3131,14 @@ * @param key - Key in `encoding` provided by `options`. * @param options - Crypto configuration options with cipher key details. * - * @returns Array buffer with decoded key. + * @returns Bytes array with decoded key. */ decodeKey(key, options) { - // @ts-expect-error Bundled library without types. if (options.keyEncoding === 'base64') - return CryptoJS$1.enc.Base64.parse(key); - // @ts-expect-error Bundled library without types. + return new Uint8Array(decode(key)); if (options.keyEncoding === 'hex') - return CryptoJS$1.enc.Hex.parse(key); - return key; + return hexToBytes(key); + return encodeUtf8(key); } /** * Add padding to the cipher key. @@ -2526,11 +3149,10 @@ * @returns Properly padded cipher key. */ getPaddedKey(key, options) { - key = this.decodeKey(key, options); - // @ts-expect-error Bundled library without types. + const decodedKey = this.decodeKey(key, options); if (options.encryptKey) - return CryptoJS$1.enc.Utf8.parse(this.SHA256(key).slice(0, 32)); - return key; + return encodeUtf8(bytesToHex(this.primitives.sha256(decodedKey)).slice(0, 32)); + return decodedKey; } /** * Cipher mode. @@ -2540,11 +3162,7 @@ * @returns Crypto cipher mode. */ getMode(options) { - // @ts-expect-error Bundled library without types. - if (options.mode === 'ecb') - return CryptoJS$1.mode.ECB; - // @ts-expect-error Bundled library without types. - return CryptoJS$1.mode.CBC; + return options.mode === 'ecb' ? 'ecb' : 'cbc'; } /** * Cipher initialization vector. @@ -2554,17 +3172,44 @@ * @returns Initialization vector. */ getIV(options) { - // @ts-expect-error Bundled library without types. - return options.mode === 'cbc' ? CryptoJS$1.enc.Utf8.parse(this.iv) : null; + return options.mode === 'cbc' ? encodeUtf8(this.iv) : null; } /** * Random initialization vector. * + * Falls back to the insecure `Math.random()` source (previous behavior) when the platform doesn't provide + * `crypto.getRandomValues` (for example, React Native without polyfill). + * * @returns Generated random initialization vector. */ getRandomIV() { - // @ts-expect-error Bundled library without types. - return CryptoJS$1.lib.WordArray.random(16); + try { + return this.primitives.randomBytes(16); + } + catch (_) { + if (!insecureRandomWarningShown && this.logger) { + insecureRandomWarningShown = true; + this.logger.warn('Crypto', "'crypto.getRandomValues' is unavailable; falling back to insecure Math.random() IV. " + + "Install 'react-native-get-random-values'."); + } + return Uint8Array.from({ length: 16 }, () => Math.floor(Math.random() * 256)); + } + } + } + + /** + * Legacy cryptography module (`@noble`-backed: Web, React Native). + * + * @internal + */ + /** + * Legacy cryptography module for data encryption / decryption. + * + * @internal + */ + class Crypto extends LegacyCrypto { + constructor(configuration) { + super(configuration, noblePrimitives); } } diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 2fca410b4..a8f83ed2c 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -1,2 +1,3 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s={exports:{}};!function(t){!function(e,s){var n=Math.pow(2,-24),i=Math.pow(2,32),r=Math.pow(2,53);var a={encode:function(e){var t,n=new ArrayBuffer(256),a=new DataView(n),o=0;function c(e){for(var s=n.byteLength,i=o+e;s>2,u=0;u>6),i.push(128|63&a)):a<55296?(i.push(224|a>>12),i.push(128|a>>6&63),i.push(128|63&a)):(a=(1023&a)<<10,a|=1023&t.charCodeAt(++n),a+=65536,i.push(240|a>>18),i.push(128|a>>12&63),i.push(128|a>>6&63),i.push(128|63&a))}return d(3,i.length),h(i);default:var p;if(Array.isArray(t))for(d(4,p=t.length),n=0;n>5!==e)throw"Invalid indefinite length element";return s}function y(e,t){for(var s=0;s>10),e.push(56320|1023&n))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof r&&(r=function(){return s});var m=function e(){var i,d,m=l(),f=m>>5,v=31&m;if(7===f)switch(v){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),s=h(),i=32768&s,r=31744&s,a=1023&s;if(31744===r)r=261120;else if(0!==r)r+=114688;else if(0!==a)return a*n;return t.setUint32(0,i<<16|r<<13|a<<13),t.getFloat32(0)}();case 26:return c(a.getFloat32(o),4);case 27:return c(a.getFloat64(o),8)}if((d=g(v))<0&&(f<2||6=0;)S+=d,O.push(u(d));var j=new Uint8Array(S),w=0;for(i=0;i=0;)y(k,d);else y(k,d);return String.fromCharCode.apply(null,k);case 4:var C;if(d<0)for(C=[];!p();)C.push(e());else for(C=new Array(d),i=0;ie.toString())).join(", ")}]}`}}a.encoder=new TextEncoder,a.decoder=new TextDecoder;class o{static create(e){return new o(e)}constructor(e){let t,s,n,i;if(e instanceof File)i=e,n=e.name,s=e.type,t=e.size;else if("data"in e){const r=e.data;s=e.mimeType,n=e.name,i=new File([r],n,{type:s}),t=i.size}if(void 0===i)throw new Error("Couldn't construct a file out of supplied options.");if(void 0===n)throw new Error("Couldn't guess filename out of the options. Please provide one.");t&&(this.contentLength=t),this.mimeType=s,this.data=i,this.name=n}toBuffer(){return r(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toArrayBuffer(){return r(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if(s.result instanceof ArrayBuffer)return e(s.result)})),s.addEventListener("error",(()=>t(s.error))),s.readAsArrayBuffer(this.data)}))}))}toString(){return r(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if("string"==typeof s.result)return e(s.result)})),s.addEventListener("error",(()=>{t(s.error)})),s.readAsBinaryString(this.data)}))}))}toStream(){return r(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return r(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return r(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return r(this,void 0,void 0,(function*(){return this.data}))}}o.supportsBlob="undefined"!=typeof Blob,o.supportsFile="undefined"!=typeof File,o.supportsBuffer=!1,o.supportsStream=!1,o.supportsString=!0,o.supportsArrayBuffer=!0,o.supportsEncryptFile=!0,o.supportsFileUri=!1;function c(e){const t=e.replace(/==?$/,""),s=Math.floor(t.length/4*3),n=new ArrayBuffer(s),i=new Uint8Array(n);let r=0;function a(){const e=t.charAt(r++),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===s)throw new Error(`Illegal character at ${r}: ${t.charAt(r-1)}`);return s}for(let e=0;e>4,c=(15&s)<<4|n>>2,u=(3&n)<<6|r;i[e]=o,64!=n&&(i[e+1]=c),64!=r&&(i[e+2]=u)}return n}function u(e){let t="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(e),i=n.byteLength,r=i%3,a=i-r;let o,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=s[o]+s[c]+s[u]+s[l];return 1==r?(h=n[a],o=(252&h)>>2,c=(3&h)<<4,t+=s[o]+s[c]+"=="):2==r&&(h=n[a]<<8|n[a+1],o=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=s[o]+s[c]+s[u]+"="),t}var l;!function(e){e.PNNetworkIssuesCategory="PNNetworkIssuesCategory",e.PNTimeoutCategory="PNTimeoutCategory",e.PNCancelledCategory="PNCancelledCategory",e.PNBadRequestCategory="PNBadRequestCategory",e.PNAccessDeniedCategory="PNAccessDeniedCategory",e.PNValidationErrorCategory="PNValidationErrorCategory",e.PNAcknowledgmentCategory="PNAcknowledgmentCategory",e.PNMalformedResponseCategory="PNMalformedResponseCategory",e.PNServerErrorCategory="PNServerErrorCategory",e.PNUnknownCategory="PNUnknownCategory",e.PNNetworkUpCategory="PNNetworkUpCategory",e.PNNetworkDownCategory="PNNetworkDownCategory",e.PNReconnectedCategory="PNReconnectedCategory",e.PNConnectedCategory="PNConnectedCategory",e.PNSubscriptionChangedCategory="PNSubscriptionChangedCategory",e.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",e.PNDisconnectedCategory="PNDisconnectedCategory",e.PNConnectionErrorCategory="PNConnectionErrorCategory",e.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory",e.PNSharedWorkerUpdatedCategory="PNSharedWorkerUpdatedCategory"}(l||(l={}));var h=l;class d extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function p(e,t){var s;return null!==(s=e.statusCode)&&void 0!==s||(e.statusCode=0),Object.assign(Object.assign({},e),{statusCode:e.statusCode,category:t,error:!0})}function g(e,t){return p(Object.assign(Object.assign({message:"Unable to deserialize service response"},void 0!==e?{responseText:e}:{}),void 0!==t?{statusCode:t}:{}),h.PNMalformedResponseCategory)}var b,y,m,f,v,O=O||function(e){var t={},s=t.lib={},n=function(){},i=s.Base={extend:function(e){n.prototype=this;var t=new n;return e&&t.mixIn(e),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},r=s.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||o).stringify(this)},concat:function(e){var t=this.words,s=e.words,n=this.sigBytes;if(e=e.sigBytes,this.clamp(),n%4)for(var i=0;i>>2]|=(s[i>>>2]>>>24-i%4*8&255)<<24-(n+i)%4*8;else if(65535>>2]=s[i>>>2];else t.push.apply(t,s);return this.sigBytes+=e,this},clamp:function(){var t=this.words,s=this.sigBytes;t[s>>>2]&=4294967295<<32-s%4*8,t.length=e.ceil(s/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var s=[],n=0;n>>2]>>>24-n%4*8&255;s.push((i>>>4).toString(16)),s.push((15&i).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new r.init(s,t/2)}},c=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var s=[],n=0;n>>2]>>>24-n%4*8&255));return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new r.init(s,t)}},u=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},l=s.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new r.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=u.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var s=this._data,n=s.words,i=s.sigBytes,a=this.blockSize,o=i/(4*a);if(t=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*a,i=e.min(4*t,i),t){for(var c=0;cu;){var l;e:{l=c;for(var h=e.sqrt(l),d=2;d<=h;d++)if(!(l%d)){l=!1;break e}l=!0}l&&(8>u&&(r[u]=o(e.pow(c,.5))),a[u]=o(e.pow(c,1/3)),u++),c++}var p=[];i=i.SHA256=n.extend({_doReset:function(){this._hash=new s.init(r.slice(0))},_doProcessBlock:function(e,t){for(var s=this._hash.words,n=s[0],i=s[1],r=s[2],o=s[3],c=s[4],u=s[5],l=s[6],h=s[7],d=0;64>d;d++){if(16>d)p[d]=0|e[t+d];else{var g=p[d-15],b=p[d-2];p[d]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[d-7]+((b<<15|b>>>17)^(b<<13|b>>>19)^b>>>10)+p[d-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&l)+a[d]+p[d],b=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&i^n&r^i&r),h=l,l=u,u=c,c=o+g|0,o=r,r=i,i=n,n=g+b|0}s[0]=s[0]+n|0,s[1]=s[1]+i|0,s[2]=s[2]+r|0,s[3]=s[3]+o|0,s[4]=s[4]+c|0,s[5]=s[5]+u|0,s[6]=s[6]+l|0,s[7]=s[7]+h|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;return s[i>>>5]|=128<<24-i%32,s[14+(i+64>>>9<<4)]=e.floor(n/4294967296),s[15+(i+64>>>9<<4)]=n,t.sigBytes=4*s.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(i),t.HmacSHA256=n._createHmacHelper(i)}(Math),y=(b=O).enc.Utf8,b.algo.HMAC=b.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=y.parse(t));var s=e.blockSize,n=4*s;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var i=this._oKey=t.clone(),r=this._iKey=t.clone(),a=i.words,o=r.words,c=0;c>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,a=0;4>a&&i+.75*a>>6*(3-a)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,s=this._map;(n=s.charAt(64))&&-1!=(n=e.indexOf(n))&&(t=n);for(var n=[],i=0,r=0;r>>6-r%4*2;n[i>>>2]|=(a|o)<<24-i%4*8,i++}return f.create(n,i)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,s,n,i,r,a){return((e=e+(t&s|~t&n)+i+a)<>>32-r)+t}function s(e,t,s,n,i,r,a){return((e=e+(t&n|s&~n)+i+a)<>>32-r)+t}function n(e,t,s,n,i,r,a){return((e=e+(t^s^n)+i+a)<>>32-r)+t}function i(e,t,s,n,i,r,a){return((e=e+(s^(t|~n))+i+a)<>>32-r)+t}for(var r=O,a=(c=r.lib).WordArray,o=c.Hasher,c=r.algo,u=[],l=0;64>l;l++)u[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=o.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,r){for(var a=0;16>a;a++){var o=e[c=r+a];e[c]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8)}a=this._hash.words;var c=e[r+0],l=(o=e[r+1],e[r+2]),h=e[r+3],d=e[r+4],p=e[r+5],g=e[r+6],b=e[r+7],y=e[r+8],m=e[r+9],f=e[r+10],v=e[r+11],O=e[r+12],S=e[r+13],j=e[r+14],w=e[r+15],k=t(k=a[0],N=a[1],P=a[2],C=a[3],c,7,u[0]),C=t(C,k,N,P,o,12,u[1]),P=t(P,C,k,N,l,17,u[2]),N=t(N,P,C,k,h,22,u[3]);k=t(k,N,P,C,d,7,u[4]),C=t(C,k,N,P,p,12,u[5]),P=t(P,C,k,N,g,17,u[6]),N=t(N,P,C,k,b,22,u[7]),k=t(k,N,P,C,y,7,u[8]),C=t(C,k,N,P,m,12,u[9]),P=t(P,C,k,N,f,17,u[10]),N=t(N,P,C,k,v,22,u[11]),k=t(k,N,P,C,O,7,u[12]),C=t(C,k,N,P,S,12,u[13]),P=t(P,C,k,N,j,17,u[14]),k=s(k,N=t(N,P,C,k,w,22,u[15]),P,C,o,5,u[16]),C=s(C,k,N,P,g,9,u[17]),P=s(P,C,k,N,v,14,u[18]),N=s(N,P,C,k,c,20,u[19]),k=s(k,N,P,C,p,5,u[20]),C=s(C,k,N,P,f,9,u[21]),P=s(P,C,k,N,w,14,u[22]),N=s(N,P,C,k,d,20,u[23]),k=s(k,N,P,C,m,5,u[24]),C=s(C,k,N,P,j,9,u[25]),P=s(P,C,k,N,h,14,u[26]),N=s(N,P,C,k,y,20,u[27]),k=s(k,N,P,C,S,5,u[28]),C=s(C,k,N,P,l,9,u[29]),P=s(P,C,k,N,b,14,u[30]),k=n(k,N=s(N,P,C,k,O,20,u[31]),P,C,p,4,u[32]),C=n(C,k,N,P,y,11,u[33]),P=n(P,C,k,N,v,16,u[34]),N=n(N,P,C,k,j,23,u[35]),k=n(k,N,P,C,o,4,u[36]),C=n(C,k,N,P,d,11,u[37]),P=n(P,C,k,N,b,16,u[38]),N=n(N,P,C,k,f,23,u[39]),k=n(k,N,P,C,S,4,u[40]),C=n(C,k,N,P,c,11,u[41]),P=n(P,C,k,N,h,16,u[42]),N=n(N,P,C,k,g,23,u[43]),k=n(k,N,P,C,m,4,u[44]),C=n(C,k,N,P,O,11,u[45]),P=n(P,C,k,N,w,16,u[46]),k=i(k,N=n(N,P,C,k,l,23,u[47]),P,C,c,6,u[48]),C=i(C,k,N,P,b,10,u[49]),P=i(P,C,k,N,j,15,u[50]),N=i(N,P,C,k,p,21,u[51]),k=i(k,N,P,C,O,6,u[52]),C=i(C,k,N,P,h,10,u[53]),P=i(P,C,k,N,f,15,u[54]),N=i(N,P,C,k,o,21,u[55]),k=i(k,N,P,C,y,6,u[56]),C=i(C,k,N,P,w,10,u[57]),P=i(P,C,k,N,g,15,u[58]),N=i(N,P,C,k,S,21,u[59]),k=i(k,N,P,C,d,6,u[60]),C=i(C,k,N,P,v,10,u[61]),P=i(P,C,k,N,l,15,u[62]),N=i(N,P,C,k,m,21,u[63]);a[0]=a[0]+k|0,a[1]=a[1]+N|0,a[2]=a[2]+P|0,a[3]=a[3]+C|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;s[i>>>5]|=128<<24-i%32;var r=e.floor(n/4294967296);for(s[15+(i+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),s[14+(i+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),t.sigBytes=4*(s.length+1),this._process(),s=(t=this._hash).words,n=0;4>n;n++)i=s[n],s[n]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8);return t},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}}),r.MD5=o._createHelper(c),r.HmacMD5=o._createHmacHelper(c)}(Math),function(){var e,t=O,s=(e=t.lib).Base,n=e.WordArray,i=(e=t.algo).EvpKDF=s.extend({cfg:s.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var s=(o=this.cfg).hasher.create(),i=n.create(),r=i.words,a=o.keySize,o=o.iterations;r.length>>2]}},e.BlockCipher=a.extend({cfg:a.cfg.extend({mode:o,padding:u}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var s=t.createEncryptor;else s=t.createDecryptor,this._minBufferSize=1;this._mode=s.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var l=e.CipherParams=t.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),h=(o=(d.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?s.create([1398893684,1701076831]).concat(e).concat(t):t).toString(i)},parse:function(e){var t=(e=i.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var n=s.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return l.create({ciphertext:e,salt:n})}},e.SerializableCipher=t.extend({cfg:t.extend({format:o}),encrypt:function(e,t,s,n){n=this.cfg.extend(n);var i=e.createEncryptor(s,n);return t=i.finalize(t),i=i.cfg,l.create({ciphertext:t,key:s,iv:i.iv,algorithm:e,mode:i.mode,padding:i.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(s,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),d=(d.kdf={}).OpenSSL={execute:function(e,t,n,i){return i||(i=s.random(8)),e=r.create({keySize:t+n}).compute(e,i),n=s.create(e.words.slice(t),4*n),e.sigBytes=4*t,l.create({key:e,iv:n,salt:i})}},p=e.PasswordBasedCipher=h.extend({cfg:h.cfg.extend({kdf:d}),encrypt:function(e,t,s,n){return s=(n=this.cfg.extend(n)).kdf.execute(s,e.keySize,e.ivSize),n.iv=s.iv,(e=h.encrypt.call(this,e,t,s.key,n)).mixIn(s),e},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),s=n.kdf.execute(s,e.keySize,e.ivSize,t.salt),n.iv=s.iv,h.decrypt.call(this,e,t,s.key,n)}})}(),function(){for(var e=O,t=e.lib.BlockCipher,s=e.algo,n=[],i=[],r=[],a=[],o=[],c=[],u=[],l=[],h=[],d=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var b=0,y=0;for(g=0;256>g;g++){var m=(m=y^y<<1^y<<2^y<<3^y<<4)>>>8^255&m^99;n[b]=m,i[m]=b;var f=p[b],v=p[f],S=p[v],j=257*p[m]^16843008*m;r[b]=j<<24|j>>>8,a[b]=j<<16|j>>>16,o[b]=j<<8|j>>>24,c[b]=j,j=16843009*S^65537*v^257*f^16843008*b,u[m]=j<<24|j>>>8,l[m]=j<<16|j>>>16,h[m]=j<<8|j>>>24,d[m]=j,b?(b=f^p[p[p[S^f]]],y^=p[p[y]]):b=y=1}var w=[0,1,2,4,8,16,32,64,128,27,54];s=s.AES=t.extend({_doReset:function(){for(var e=(s=this._key).words,t=s.sigBytes/4,s=4*((this._nRounds=t+6)+1),i=this._keySchedule=[],r=0;r>>24]<<24|n[a>>>16&255]<<16|n[a>>>8&255]<<8|n[255&a]):(a=n[(a=a<<8|a>>>24)>>>24]<<24|n[a>>>16&255]<<16|n[a>>>8&255]<<8|n[255&a],a^=w[r/t|0]<<24),i[r]=i[r-t]^a}for(e=this._invKeySchedule=[],t=0;tt||4>=r?a:u[n[a>>>24]]^l[n[a>>>16&255]]^h[n[a>>>8&255]]^d[n[255&a]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,r,a,o,c,n)},decryptBlock:function(e,t){var s=e[t+1];e[t+1]=e[t+3],e[t+3]=s,this._doCryptBlock(e,t,this._invKeySchedule,u,l,h,d,i),s=e[t+1],e[t+1]=e[t+3],e[t+3]=s},_doCryptBlock:function(e,t,s,n,i,r,a,o){for(var c=this._nRounds,u=e[t]^s[0],l=e[t+1]^s[1],h=e[t+2]^s[2],d=e[t+3]^s[3],p=4,g=1;g>>24]^i[l>>>16&255]^r[h>>>8&255]^a[255&d]^s[p++],y=n[l>>>24]^i[h>>>16&255]^r[d>>>8&255]^a[255&u]^s[p++],m=n[h>>>24]^i[d>>>16&255]^r[u>>>8&255]^a[255&l]^s[p++];d=n[d>>>24]^i[u>>>16&255]^r[l>>>8&255]^a[255&h]^s[p++],u=b,l=y,h=m}b=(o[u>>>24]<<24|o[l>>>16&255]<<16|o[h>>>8&255]<<8|o[255&d])^s[p++],y=(o[l>>>24]<<24|o[h>>>16&255]<<16|o[d>>>8&255]<<8|o[255&u])^s[p++],m=(o[h>>>24]<<24|o[d>>>16&255]<<16|o[u>>>8&255]<<8|o[255&l])^s[p++],d=(o[d>>>24]<<24|o[u>>>16&255]<<16|o[l>>>8&255]<<8|o[255&h])^s[p++],e[t]=b,e[t+1]=y,e[t+2]=m,e[t+3]=d},keySize:8});e.AES=t._createHelper(s)}(),O.mode.ECB=((v=O.lib.BlockCipherMode.extend()).Encryptor=v.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),v.Decryptor=v.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),v);var S=t(O);class j{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=S,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:j.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:c(this.CryptoJS.AES.encrypt(e,this.encryptedKey,{iv:this.bufferToWordArray(t),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}}encryptFileData(e){return r(this,void 0,void 0,(function*(){const t=yield this.getKey(),s=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:s},t,e),metadata:s}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),s=this.bufferToWordArray(new Uint8ClampedArray(e.data));return j.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:s},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return r(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(j.BLOCK_SIZE))}getKey(){return r(this,void 0,void 0,(function*(){const e=j.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let s;for(s=0;sw.has(e),C=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),P=(e,t)=>{const s=e.map((e=>C(e)));return s.length?s.join(","):null!=t?t:""},N=(e,t)=>{const s=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!s[e])||(s[e]=!0,!1)))},E=(e,t)=>[...e].filter((s=>t.includes(s)&&e.indexOf(s)===e.lastIndexOf(s)&&t.indexOf(s)===t.lastIndexOf(s))),T=e=>Object.keys(e).map((t=>{const s=e[t];return Array.isArray(s)?s.map((e=>`${t}=${C(e)}`)).join("&"):`${t}=${C(s)}`})).join("&"),_=(e,t)=>{if("0"===t||"0"===e)return;const s=M(`${Date.now()}0000`,t,!1);return M(e,s,!0)},I=(e,t,s)=>{if(e&&0!==e.length){if(t&&t.length>0&&"0"!==t){const n=M(e,t,!1);return M(null!=s?s:`${Date.now()}0000`,n.replace("-",""),Number(n)<0)}return s&&s.length>0&&"0"!==s?s:`${Date.now()}0000`}},M=(e,t,s)=>{t.startsWith("-")&&(t=t.replace("-",""),s=!1),t=t.padStart(17,"0");const n=e.slice(0,10),i=e.slice(10,17),r=t.slice(0,10),a=t.slice(10,17);let o=Number(n),c=Number(i);return o+=Number(r)*(s?1:-1),c+=Number(a)*(s?1:-1),c>=1e7?(o+=Math.floor(c/1e7),c%=1e7):c<0?o>0?(o-=1,c+=1e7):o<0&&(c*=-1):o<0&&c>0&&(o+=1,c=1e7-c),0!==o?`${o}${`${c}`.padStart(7,"0")}`:`${c}`},R=e=>{const t="string"!=typeof e?JSON.stringify(e):e,s=new Uint32Array(1);let n=0,i=t.length;for(;i-- >0;)s[0]=(s[0]<<5)-s[0]+t.charCodeAt(n++);return s[0].toString(16).padStart(8,"0")};function D(e){const t=[];let s;for(s=0;s({messageType:"object",message:this.configuration,details:"Create with configuration:",ignoredKeys:(e,t)=>"function"==typeof t[e]||"logger"===e||k(e)})))}get logger(){return this._logger}HMACSHA256(e){return S.HmacSHA256(e,this.configuration.secretKey).toString(S.enc.Base64)}SHA256(e){return S.SHA256(e).toString(S.enc.Hex)}encrypt(e,t,s){return this.configuration.customEncrypt?(this.logger&&this.logger.warn("Crypto","'customEncrypt' is deprecated. Consult docs for better alternative."),this.configuration.customEncrypt(e)):this.pnEncrypt(e,t,s)}decrypt(e,t,s){return this.configuration.customDecrypt?(this.logger&&this.logger.warn("Crypto","'customDecrypt' is deprecated. Consult docs for better alternative."),this.configuration.customDecrypt(e)):this.pnDecrypt(e,t,s)}pnEncrypt(e,t,s){const n=null!=t?t:this.configuration.cipherKey;if(!n)return e;this.logger&&this.logger.debug("Crypto",(()=>({messageType:"object",message:Object.assign({data:e},null!=s?s:{}),details:"Encrypt with parameters:",ignoredKeys:k}))),s=this.parseOptions(s);const i=this.getMode(s),r=this.getPaddedKey(n,s);if(this.configuration.useRandomIVs){const t=this.getRandomIV(),s=S.AES.encrypt(e,r,{iv:t,mode:i}).ciphertext;return t.clone().concat(s.clone()).toString(S.enc.Base64)}const a=this.getIV(s);return S.AES.encrypt(e,r,{iv:a,mode:i}).ciphertext.toString(S.enc.Base64)||e}pnDecrypt(e,t,s){const n=null!=t?t:this.configuration.cipherKey;if(!n)return e;this.logger&&this.logger.debug("Crypto",(()=>({messageType:"object",message:Object.assign({data:e},null!=s?s:{}),details:"Decrypt with parameters:",ignoredKeys:k}))),s=this.parseOptions(s);const i=this.getMode(s),r=this.getPaddedKey(n,s);if(this.configuration.useRandomIVs){const t=new Uint8ClampedArray(c(e)),s=D(t.slice(0,16)),n=D(t.slice(16));try{const e=S.AES.decrypt({ciphertext:n},r,{iv:s,mode:i}).toString(S.enc.Utf8);return JSON.parse(e)}catch(e){return this.logger&&this.logger.error("Crypto",(()=>({messageType:"error",message:e}))),null}}else{const t=this.getIV(s);try{const s=S.enc.Base64.parse(e),n=S.AES.decrypt({ciphertext:s},r,{iv:t,mode:i}).toString(S.enc.Utf8);return JSON.parse(n)}catch(e){return this.logger&&this.logger.error("Crypto",(()=>({messageType:"error",message:e}))),null}}}parseOptions(e){var t,s,n,i;if(!e)return this.defaultOptions;const r={encryptKey:null!==(t=e.encryptKey)&&void 0!==t?t:this.defaultOptions.encryptKey,keyEncoding:null!==(s=e.keyEncoding)&&void 0!==s?s:this.defaultOptions.keyEncoding,keyLength:null!==(n=e.keyLength)&&void 0!==n?n:this.defaultOptions.keyLength,mode:null!==(i=e.mode)&&void 0!==i?i:this.defaultOptions.mode};return-1===this.allowedKeyEncodings.indexOf(r.keyEncoding.toLowerCase())&&(r.keyEncoding=this.defaultOptions.keyEncoding),-1===this.allowedKeyLengths.indexOf(r.keyLength)&&(r.keyLength=this.defaultOptions.keyLength),-1===this.allowedModes.indexOf(r.mode.toLowerCase())&&(r.mode=this.defaultOptions.mode),r}decodeKey(e,t){return"base64"===t.keyEncoding?S.enc.Base64.parse(e):"hex"===t.keyEncoding?S.enc.Hex.parse(e):e}getPaddedKey(e,t){return e=this.decodeKey(e,t),t.encryptKey?S.enc.Utf8.parse(this.SHA256(e).slice(0,32)):e}getMode(e){return"ecb"===e.mode?S.mode.ECB:S.mode.CBC}getIV(e){return"cbc"===e.mode?S.enc.Utf8.parse(this.iv):null}getRandomIV(){return S.lib.WordArray.random(16)}}class A{encrypt(e,t){return r(this,void 0,void 0,(function*(){if(!(t instanceof ArrayBuffer)&&"string"!=typeof t)throw new Error("Cannot encrypt this file. In browsers file encryption supports only string or ArrayBuffer");const s=yield this.getKey(e);return t instanceof ArrayBuffer?this.encryptArrayBuffer(s,t):this.encryptString(s,t)}))}encryptArrayBuffer(e,t){return r(this,void 0,void 0,(function*(){const s=crypto.getRandomValues(new Uint8Array(16));return this.concatArrayBuffer(s.buffer,yield crypto.subtle.encrypt({name:"AES-CBC",iv:s},e,t))}))}encryptString(e,t){return r(this,void 0,void 0,(function*(){const s=crypto.getRandomValues(new Uint8Array(16)),n=A.encoder.encode(t).buffer,i=yield crypto.subtle.encrypt({name:"AES-CBC",iv:s},e,n),r=this.concatArrayBuffer(s.buffer,i);return A.decoder.decode(r)}))}encryptFile(e,t,s){return r(this,void 0,void 0,(function*(){var n,i;if((null!==(n=t.contentLength)&&void 0!==n?n:0)<=0)throw new Error("encryption error. empty content");const r=yield this.getKey(e),a=yield t.toArrayBuffer(),o=yield this.encryptArrayBuffer(r,a);return s.create({name:t.name,mimeType:null!==(i=t.mimeType)&&void 0!==i?i:"application/octet-stream",data:o})}))}decrypt(e,t){return r(this,void 0,void 0,(function*(){if(!(t instanceof ArrayBuffer)&&"string"!=typeof t)throw new Error("Cannot decrypt this file. In browsers file decryption supports only string or ArrayBuffer");const s=yield this.getKey(e);return t instanceof ArrayBuffer?this.decryptArrayBuffer(s,t):this.decryptString(s,t)}))}decryptArrayBuffer(e,t){return r(this,void 0,void 0,(function*(){const s=t.slice(0,16);if(t.slice(A.IV_LENGTH).byteLength<=0)throw new Error("decryption error: empty content");return yield crypto.subtle.decrypt({name:"AES-CBC",iv:s},e,t.slice(A.IV_LENGTH))}))}decryptString(e,t){return r(this,void 0,void 0,(function*(){const s=A.encoder.encode(t).buffer,n=s.slice(0,16),i=s.slice(16),r=yield crypto.subtle.decrypt({name:"AES-CBC",iv:n},e,i);return A.decoder.decode(r)}))}decryptFile(e,t,s){return r(this,void 0,void 0,(function*(){const n=yield this.getKey(e),i=yield t.toArrayBuffer(),r=yield this.decryptArrayBuffer(n,i);return s.create({name:t.name,mimeType:t.mimeType,data:r})}))}getKey(e){return r(this,void 0,void 0,(function*(){const t=yield crypto.subtle.digest("SHA-256",A.encoder.encode(e)),s=Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join(""),n=A.encoder.encode(s.slice(0,32)).buffer;return crypto.subtle.importKey("raw",n,"AES-CBC",!0,["encrypt","decrypt"])}))}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}}A.IV_LENGTH=16,A.encoder=new TextEncoder,A.decoder=new TextDecoder;class ${constructor(e){this.config=e,this.cryptor=new U(Object.assign({},e)),this.fileCryptor=new A}set logger(e){this.cryptor.logger=e,!1===this.config.useRandomIVs&&e.warn("LegacyCryptor","Setting 'useRandomIVs' to false is insecure and should only be used to support legacy clients.\n Do not disable random IVs in new applications.")}encrypt(e){const t="string"==typeof e?e:$.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return r(this,void 0,void 0,(function*(){var s;if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(s=this.config)||void 0===s?void 0:s.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:u(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return r(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}toString(){return`LegacyCryptor { ${Object.entries(this.config).reduce(((e,[t,s])=>("logger"===t||k(t)||e.push(`${t}: ${"function"==typeof s?"":s}`),e)),[]).join(", ")} }`}}$.encoder=new TextEncoder,$.decoder=new TextDecoder;class F extends a{set logger(e){if(this.defaultCryptor.identifier===F.LEGACY_IDENTIFIER)e.warn("CryptoModule","'legacyCryptoModule' is deprecated. Use 'aesCbcCryptoModule' instead for new applications."),this.defaultCryptor.logger=e;else{const t=this.cryptors.find((e=>e.identifier===F.LEGACY_IDENTIFIER));t&&(t.logger=e)}}static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return e.logger&&(e.logger.warn("CryptoModule","'legacyCryptoModule' is deprecated. Use 'aesCbcCryptoModule' instead for new applications."),!1===e.useRandomIVs&&e.logger.warn("CryptoModule","Setting 'useRandomIVs' to false is insecure and should only be used to support legacy clients.\n Do not disable random IVs in new applications.")),new F({default:new $(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new j({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new F({default:new j({cipherKey:e.cipherKey}),cryptors:[new $(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===F.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(F.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const s=this.getHeaderData(t);return this.concatArrayBuffer(s,t.data)}encryptFile(e,t){return r(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===x.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const s=yield this.getFileData(e),n=yield this.defaultCryptor.encryptFileData(s);if("string"==typeof n.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(n),n.data)})}))}decrypt(e){const t="string"==typeof e?c(e):e,s=x.tryParse(t),n=this.getCryptor(s),i=s.length>0?t.slice(s.length-s.metadataLength,s.length):null;if(t.slice(s.length).byteLength<=0)throw new Error("Decryption error: empty content");return n.decrypt({data:t.slice(s.length),metadata:i})}decryptFile(e,t){return r(this,void 0,void 0,(function*(){const s=yield e.data.arrayBuffer(),n=x.tryParse(s),i=this.getCryptor(n);if((null==i?void 0:i.identifier)===x.LEGACY_IDENTIFIER)return i.decryptFile(e,t);const r=(yield this.getFileData(s)).slice(n.length-n.metadataLength,n.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:s.slice(n.length),metadata:r})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof q)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=x.from(this.defaultCryptor.identifier,e.metadata),s=new Uint8Array(t.length);let n=0;return s.set(t.data,n),n+=t.length-e.metadata.byteLength,s.set(new Uint8Array(e.metadata),n),s.buffer}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}getFileData(e){return r(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof o)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}F.LEGACY_IDENTIFIER="";class x{static from(e,t){if(e!==x.LEGACY_IDENTIFIER)return new q(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let s,n,i=null;if(t.byteLength>=4&&(s=t.slice(0,4),this.decoder.decode(s)!==x.SENTINEL))return F.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(i=t[4],i>x.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let r=5+x.IDENTIFIER_LENGTH;if(!(t.byteLength>=r))throw new Error("Decryption error: invalid crypto identifier");n=t.slice(5,r);let a=null;if(!(t.byteLength>=r+1))throw new Error("Decryption error: invalid metadata length");return a=t[r],r+=1,255===a&&t.byteLength>=r+2&&(a=new Uint16Array(t.slice(r,r+2)).reduce(((e,t)=>(e<<8)+t),0)),new q(this.decoder.decode(n),a)}}x.SENTINEL="PNED",x.LEGACY_IDENTIFIER="",x.IDENTIFIER_LENGTH=4,x.VERSION=1,x.MAX_VERSION=1,x.decoder=new TextDecoder;class q{constructor(e,t){this._identifier=e,this._metadataLength=t}get identifier(){return this._identifier}set identifier(e){this._identifier=e}get metadataLength(){return this._metadataLength}set metadataLength(e){this._metadataLength=e}get version(){return x.VERSION}get length(){return x.SENTINEL.length+1+x.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),s=new TextEncoder;t.set(s.encode(x.SENTINEL)),e+=x.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(s.encode(this.identifier),e);const n=this.metadataLength;return e+=x.IDENTIFIER_LENGTH,n<255?t[e]=n:t.set([255,n>>8,255&n],e),t}}q.IDENTIFIER_LENGTH=4,q.SENTINEL="PNED";class G extends Error{static create(e,t){return G.isErrorObject(e)?G.createFromError(e):G.createFromServiceResponse(e,t)}static createFromError(e){let t=h.PNUnknownCategory,s="Unknown error",n="Error";if(!e)return new G(s,t,0);if(e instanceof G)return e;if(G.isErrorObject(e)&&(s=e.message,n=e.name),"AbortError"===n||-1!==s.indexOf("Aborted"))t=h.PNCancelledCategory,s="Request cancelled";else if(-1!==s.toLowerCase().indexOf("timeout"))t=h.PNTimeoutCategory,s="Request timeout";else if(-1!==s.toLowerCase().indexOf("network"))t=h.PNNetworkIssuesCategory,s="Network issues";else if("TypeError"===n)t=-1!==s.indexOf("Load failed")||-1!=s.indexOf("Failed to fetch")?h.PNNetworkIssuesCategory:h.PNBadRequestCategory;else if("FetchError"===n){const n=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(n)&&(t=h.PNNetworkIssuesCategory),"ECONNREFUSED"===n?s="Connection refused":"ENETUNREACH"===n?s="Network not reachable":"ENOTFOUND"===n?s="Server not found":"ECONNRESET"===n?s="Connection reset by peer":"EAI_AGAIN"===n?s="Name resolution error":"ETIMEDOUT"===n?(t=h.PNTimeoutCategory,s="Request timeout"):s=`Unknown system error: ${e}`}else"Request timeout"===s&&(t=h.PNTimeoutCategory);return new G(s,t,0,e)}static createFromServiceResponse(e,t){let s,n=h.PNUnknownCategory,i="Unknown error",{status:r}=e;if(null!=t||(t=e.body),402===r?i="Not available for used key set. Contact support@pubnub.com":404===r?i="Resource not found":400===r?(n=h.PNBadRequestCategory,i="Bad request"):403===r?(n=h.PNAccessDeniedCategory,i="Access denied"):r>=500&&(n=h.PNServerErrorCategory,i="Internal server error"),"object"==typeof e&&0===Object.keys(e).length&&(n=h.PNMalformedResponseCategory,i="Malformed response (network issues)",r=400),t&&t.byteLength>0){const n=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(n);"object"==typeof e&&(Array.isArray(e)?"number"==typeof e[0]&&0===e[0]&&e.length>1&&"string"==typeof e[1]&&(s=e[1]):("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(s=e,r=e.status):s=e,"error"in e&&e.error instanceof Error&&(s=e.error)))}catch(e){s=n}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(n);i=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else s=n}return new G(i,n,r,s)}constructor(e,t,s,n){super(e),this.category=t,this.statusCode=s,this.errorData=n,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData,toJSON:function(){let e;const t=this.errorData;if(t)try{if("object"==typeof t){const s=Object.assign(Object.assign(Object.assign(Object.assign({},"name"in t?{name:t.name}:{}),"message"in t?{message:t.message}:{}),"stack"in t?{stack:t.stack}:{}),t);e=JSON.parse(JSON.stringify(s,G.circularReplacer()))}else e=t}catch(t){e={error:"Could not serialize the error object"}}const s=i(this,["toJSON"]);return JSON.stringify(Object.assign(Object.assign({},s),{errorData:e}))}}}toPubNubError(e,t){return new d(null!=t?t:this.message,this.toStatus(e))}static circularReplacer(){const e=new WeakSet;return function(t,s){if("object"==typeof s&&null!==s){if(e.has(s))return"[Circular]";e.add(s)}return s}}static isErrorObject(e){return!(!e||"object"!=typeof e)&&(e instanceof Error||("name"in e&&"message"in e&&"string"==typeof e.name&&"string"==typeof e.message||"[object Error]"===Object.prototype.toString.call(e)))}}var L;!function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNCreateDataSyncEntityOperation="PNCreateDataSyncEntityOperation",e.PNGetDataSyncEntityOperation="PNGetDataSyncEntityOperation",e.PNGetDataSyncEntitiesOperation="PNGetDataSyncEntitiesOperation",e.PNSetDataSyncEntityOperation="PNSetDataSyncEntityOperation",e.PNUpdateDataSyncEntityOperation="PNUpdateDataSyncEntityOperation",e.PNRemoveDataSyncEntityOperation="PNRemoveDataSyncEntityOperation",e.PNCreateDataSyncRelationshipOperation="PNCreateDataSyncRelationshipOperation",e.PNGetDataSyncRelationshipOperation="PNGetDataSyncRelationshipOperation",e.PNGetDataSyncRelationshipsOperation="PNGetDataSyncRelationshipsOperation",e.PNSetDataSyncRelationshipOperation="PNSetDataSyncRelationshipOperation",e.PNUpdateDataSyncRelationshipOperation="PNUpdateDataSyncRelationshipOperation",e.PNRemoveDataSyncRelationshipOperation="PNRemoveDataSyncRelationshipOperation",e.PNCreateDataSyncUserOperation="PNCreateDataSyncUserOperation",e.PNGetDataSyncUserOperation="PNGetDataSyncUserOperation",e.PNGetDataSyncUsersOperation="PNGetDataSyncUsersOperation",e.PNSetDataSyncUserOperation="PNSetDataSyncUserOperation",e.PNUpdateDataSyncUserOperation="PNUpdateDataSyncUserOperation",e.PNRemoveDataSyncUserOperation="PNRemoveDataSyncUserOperation",e.PNCreateDataSyncChannelOperation="PNCreateDataSyncChannelOperation",e.PNGetDataSyncChannelOperation="PNGetDataSyncChannelOperation",e.PNGetDataSyncChannelsOperation="PNGetDataSyncChannelsOperation",e.PNSetDataSyncChannelOperation="PNSetDataSyncChannelOperation",e.PNUpdateDataSyncChannelOperation="PNUpdateDataSyncChannelOperation",e.PNRemoveDataSyncChannelOperation="PNRemoveDataSyncChannelOperation",e.PNCreateDataSyncMembershipOperation="PNCreateDataSyncMembershipOperation",e.PNGetDataSyncMembershipOperation="PNGetDataSyncMembershipOperation",e.PNGetDataSyncMembershipsOperation="PNGetDataSyncMembershipsOperation",e.PNSetDataSyncMembershipOperation="PNSetDataSyncMembershipOperation",e.PNUpdateDataSyncMembershipOperation="PNUpdateDataSyncMembershipOperation",e.PNRemoveDataSyncMembershipOperation="PNRemoveDataSyncMembershipOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(L||(L={}));var K=L;class H{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.accessTokensMap={},this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}set emitStatus(e){this._emitStatus=e}onUserIdChange(e){this.configuration.userId=e,this.scheduleEventPost({type:"client-update",heartbeatInterval:this.configuration.heartbeatInterval,clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,workerLogLevel:this.configuration.workerLogLevel})}onPresenceStateChange(e){this.scheduleEventPost({type:"client-presence-state-update",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,workerLogLevel:this.configuration.workerLogLevel,state:e})}onHeartbeatIntervalChange(e){this.configuration.heartbeatInterval=e,this.scheduleEventPost({type:"client-update",heartbeatInterval:this.configuration.heartbeatInterval,clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,workerLogLevel:this.configuration.workerLogLevel})}onTokenChange(e){const t={type:"client-update",heartbeatInterval:this.configuration.heartbeatInterval,clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,workerLogLevel:this.configuration.workerLogLevel};this.parsedAccessToken(e).then((s=>{t.preProcessedToken=s,t.accessToken=e})).then((()=>this.scheduleEventPost(t)))}disconnect(){this.scheduleEventPost({type:"client-disconnect",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,workerLogLevel:this.configuration.workerLogLevel})}terminate(){this.scheduleEventPost({type:"client-unregister",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,workerLogLevel:this.configuration.workerLogLevel})}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/heartbeat")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;this.configuration.logger.debug("SubscriptionWorkerMiddleware","Process request with SharedWorker transport.");const s={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,request:e,workerLogLevel:this.configuration.workerLogLevel};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,identifier:e.identifier,workerLogLevel:this.configuration.workerLogLevel};this.scheduleEventPost(t)}}),[new Promise(((t,n)=>{this.callbacks.set(e.identifier,{resolve:t,reject:n}),this.parsedAccessTokenForRequest(e).then((e=>s.preProcessedToken=e)).then((()=>this.scheduleEventPost(s)))})),t]}request(e){return e}scheduleEventPost(e,t=!1){const s=this.sharedSubscriptionWorker;s?s.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||0===this.workerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.workerEventsQueue.forEach((t=>e.port.postMessage(t))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){if("undefined"!=typeof SharedWorker){try{this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`)}catch(e){throw this.configuration.logger.error("SubscriptionWorkerMiddleware",(()=>({messageType:"error",message:e}))),e}this.subscriptionWorker.port.start(),this.scheduleEventPost({type:"client-register",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,heartbeatInterval:this.configuration.heartbeatInterval,workerOfflineClientsCheckInterval:this.configuration.workerOfflineClientsCheckInterval,workerUnsubscribeOfflineClients:this.configuration.workerUnsubscribeOfflineClients,workerLogLevel:this.configuration.workerLogLevel},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e),this.shouldAnnounceNewerSharedWorkerVersionAvailability()&&localStorage.setItem("PNSubscriptionSharedWorkerVersion",this.configuration.sdkVersion),window.addEventListener("storage",(e=>{"PNSubscriptionSharedWorkerVersion"===e.key&&e.newValue&&this._emitStatus&&this.isNewerSharedWorkerVersion(e.newValue)&&this._emitStatus({error:!1,category:h.PNSharedWorkerUpdatedCategory})}))}}handleWorkerEvent(e){const{data:t}=e;if("shared-worker-ping"===t.type||"shared-worker-connected"===t.type||"shared-worker-console-log"===t.type||"shared-worker-console-dir"===t.type||t.clientIdentifier===this.configuration.clientIdentifier)if("shared-worker-connected"===t.type)this.configuration.logger.trace("SharedWorker","Ready for events processing."),this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if("shared-worker-console-log"===t.type)this.configuration.logger.debug("SharedWorker",(()=>"string"==typeof t.message||"number"==typeof t.message||"boolean"==typeof t.message?{messageType:"text",message:t.message}:t.message));else if("shared-worker-console-dir"===t.type)this.configuration.logger.debug("SharedWorker",(()=>({messageType:"object",message:t.data,details:t.message?t.message:void 0})));else if("shared-worker-ping"===t.type){const{subscriptionKey:e,clientIdentifier:t}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:e,clientIdentifier:t,workerLogLevel:this.configuration.workerLogLevel})}else if("request-process-success"===t.type||"request-process-error"===t.type)if(this.callbacks.has(t.identifier)){const{resolve:e,reject:s}=this.callbacks.get(t.identifier);this.callbacks.delete(t.identifier),"request-process-success"===t.type?e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body}):s(this.errorFromRequestSendingError(t))}else this._emitStatus&&t.url.indexOf("/v2/presence")>=0&&t.url.indexOf("/heartbeat")>=0&&("request-process-success"===t.type&&this.configuration.announceSuccessfulHeartbeats?this._emitStatus({statusCode:t.response.status,error:!1,operation:K.PNHeartbeatOperation,category:h.PNAcknowledgmentCategory}):"request-process-error"===t.type&&this.configuration.announceFailedHeartbeats&&this._emitStatus(this.errorFromRequestSendingError(t).toStatus(K.PNHeartbeatOperation)))}parsedAccessTokenForRequest(e){return r(this,void 0,void 0,(function*(){var t;return this.parsedAccessToken(e.queryParameters?null!==(t=e.queryParameters.auth)&&void 0!==t?t:"":void 0)}))}parsedAccessToken(e){return r(this,void 0,void 0,(function*(){if(e)return this.accessTokensMap[e]?this.accessTokensMap[e]:this.stringifyAccessToken(e).then((([t,s])=>{if(t&&s)return(this.accessTokensMap={[e]:{token:s,expiration:t.timestamp+60*t.ttl}})[e]}))}))}stringifyAccessToken(e){return r(this,void 0,void 0,(function*(){if(!this.configuration.tokenManager)return[void 0,void 0];const t=this.configuration.tokenManager.parseToken(e);if(!t)return[void 0,void 0];const s=e=>e?Object.entries(e).sort((([e],[t])=>e.localeCompare(t))).map((([e,t])=>Object.entries(t||{}).sort((([e],[t])=>e.localeCompare(t))).map((([t,s])=>{return`${e}:${t}=${s?(n=s,Object.entries(n).filter((([e,t])=>t)).map((([e])=>e[0])).sort().join("")):""}`;var n})).join(","))).join(";"):"";let n=[s(t.resources),s(t.patterns),t.authorized_uuid].filter(Boolean).join("|");if("undefined"!=typeof crypto&&crypto.subtle){const e=yield crypto.subtle.digest("SHA-256",(new TextEncoder).encode(n));n=String.fromCharCode(...Array.from(new Uint8Array(e)))}return[t,"undefined"!=typeof btoa?btoa(n):n]}))}errorFromRequestSendingError(e){let t=h.PNUnknownCategory,s="Unknown error";if(e.error)"NETWORK_ISSUE"===e.error.type?t=h.PNNetworkIssuesCategory:"TIMEOUT"===e.error.type?t=h.PNTimeoutCategory:"ABORTED"===e.error.type&&(t=h.PNCancelledCategory),s=`${e.error.message} (${e.identifier})`;else if(e.response){const{url:t,response:s}=e;return G.create({url:t,headers:s.headers,body:s.body,status:s.status},s.body)}return new G(s,t,0,new Error(s))}shouldAnnounceNewerSharedWorkerVersionAvailability(){const e=localStorage.getItem("PNSubscriptionSharedWorkerVersion");return!e||!this.isNewerSharedWorkerVersion(e)}isNewerSharedWorkerVersion(e){const[t,s,n]=this.configuration.sdkVersion.split(".").map(Number),[i,r,a]=e.split(".").map(Number);return i>t||r>s||a>n}}function B(e,t=0){const s=e=>"object"==typeof e&&null!==e&&e.constructor===Object,n=e=>"number"==typeof e&&isFinite(e);if(!s(e))return e;const i={};return Object.keys(e).forEach((r=>{const a=(e=>"string"==typeof e||e instanceof String)(r);let o=r;const c=e[r];if(t<2)if(a&&r.indexOf(",")>=0){o=r.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(n(r)||a&&!isNaN(Number(r)))&&(o=String.fromCharCode(n(r)?r:parseInt(r,10)));i[o]=s(c)?B(c,t+1):c})),i}const W=e=>{var t,s,n,i,r,a;return e.subscriptionWorkerUrl&&"undefined"==typeof SharedWorker&&(e.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,s,n,i,r,a,o,c,u,l,h,p,g,b,y;const m=Object.assign({},e);if(null!==(t=m.ssl)&&void 0!==t||(m.ssl=!0),null!==(s=m.transactionalRequestTimeout)&&void 0!==s||(m.transactionalRequestTimeout=15),null!==(n=m.subscribeRequestTimeout)&&void 0!==n||(m.subscribeRequestTimeout=310),null!==(i=m.fileRequestTimeout)&&void 0!==i||(m.fileRequestTimeout=300),null!==(r=m.restore)&&void 0!==r||(m.restore=!0),null!==(a=m.useInstanceId)&&void 0!==a||(m.useInstanceId=!1),null!==(o=m.suppressLeaveEvents)&&void 0!==o||(m.suppressLeaveEvents=!1),null!==(c=m.requestMessageCountThreshold)&&void 0!==c||(m.requestMessageCountThreshold=100),null!==(u=m.autoNetworkDetection)&&void 0!==u||(m.autoNetworkDetection=!1),null!==(l=m.enableEventEngine)&&void 0!==l||(m.enableEventEngine=!0),null!==(h=m.maintainPresenceState)&&void 0!==h||(m.maintainPresenceState=!0),null!==(p=m.useSmartHeartbeat)&&void 0!==p||(m.useSmartHeartbeat=!1),null!==(g=m.keepAlive)&&void 0!==g||(m.keepAlive=!1),m.userId&&m.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(b=m.userId)&&void 0!==b||(m.userId=m.uuid),!m.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(y=m.userId)||void 0===y?void 0:y.trim().length))throw new d("PubNub client configuration error: 'userId' is empty");m.origin||(m.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const f={subscribeKey:m.subscribeKey,publishKey:m.publishKey,secretKey:m.secretKey};void 0!==m.presenceTimeout&&(m.presenceTimeout>320?(m.presenceTimeout=320,console.warn("WARNING: Presence timeout is larger than the maximum. Using maximum value: ",320)):m.presenceTimeout<=0&&(console.warn("WARNING: Presence timeout should be larger than zero."),delete m.presenceTimeout)),void 0!==m.presenceTimeout?m.heartbeatInterval=m.presenceTimeout/2-1:m.presenceTimeout=300;let v=!1,O=!0,S=5,j=!1,w=100,k=!0;return void 0!==m.dedupeOnSubscribe&&"boolean"==typeof m.dedupeOnSubscribe&&(j=m.dedupeOnSubscribe),void 0!==m.maximumCacheSize&&"number"==typeof m.maximumCacheSize&&(w=m.maximumCacheSize),void 0!==m.useRequestId&&"boolean"==typeof m.useRequestId&&(k=m.useRequestId),void 0!==m.announceSuccessfulHeartbeats&&"boolean"==typeof m.announceSuccessfulHeartbeats&&(v=m.announceSuccessfulHeartbeats),void 0!==m.announceFailedHeartbeats&&"boolean"==typeof m.announceFailedHeartbeats&&(O=m.announceFailedHeartbeats),void 0!==m.fileUploadPublishRetryLimit&&"number"==typeof m.fileUploadPublishRetryLimit&&(S=m.fileUploadPublishRetryLimit),Object.assign(Object.assign({},m),{keySet:f,dedupeOnSubscribe:j,maximumCacheSize:w,useRequestId:k,announceSuccessfulHeartbeats:v,announceFailedHeartbeats:O,fileUploadPublishRetryLimit:S})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,subscriptionWorkerUrl:e.subscriptionWorkerUrl,subscriptionWorkerOfflineClientsCheckInterval:null!==(s=e.subscriptionWorkerOfflineClientsCheckInterval)&&void 0!==s?s:10,subscriptionWorkerUnsubscribeOfflineClients:null!==(n=e.subscriptionWorkerUnsubscribeOfflineClients)&&void 0!==n&&n,subscriptionWorkerLogVerbosity:null!==(i=e.subscriptionWorkerLogVerbosity)&&void 0!==i&&i,transport:null!==(r=e.transport)&&void 0!==r?r:"fetch",keepAlive:null===(a=e.keepAlive)||void 0===a||a})};var V;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warn=3]="Warn",e[e.Error=4]="Error",e[e.None=5]="None"}(V||(V={}));class z{debug(e){this.log(e)}error(e){this.log(e)}info(e){this.log(e)}trace(e){this.log(e)}warn(e){this.log(e)}toString(){return"ConsoleLogger {}"}log(e){const t=V[e.level],s=t.toLowerCase();console["trace"===s?"debug":s](`${e.timestamp.toISOString()} PubNub-${e.pubNubId} ${t.padEnd(5," ")}${e.location?` ${e.location}`:""} ${this.logMessage(e)}`)}logMessage(e){if("text"===e.messageType)return e.message;if("object"===e.messageType)return`${e.details?`${e.details}\n`:""}${this.formattedObject(e)}`;if("network-request"===e.messageType){const t=!!e.canceled||!!e.failed,s=e.minimumLevel!==V.Trace||t?void 0:this.formattedHeaders(e),n=e.message,i=n.queryParameters&&Object.keys(n.queryParameters).length>0?T(n.queryParameters):void 0,r=`${n.origin}${n.path}${i?`?${i}`:""}`,a=t?void 0:this.formattedBody(e);let o="Sending";t&&(o=`${e.canceled?"Canceled":"Failed"}${e.details?` (${e.details})`:""}`);const c=((null==a?void 0:a.formData)?"FormData":"Method").length;return`${o} HTTP request:\n ${this.paddedString("Method",c)}: ${n.method}\n ${this.paddedString("URL",c)}: ${r}${s?`\n ${this.paddedString("Headers",c)}:\n${s}`:""}${(null==a?void 0:a.formData)?`\n ${this.paddedString("FormData",c)}:\n${a.formData}`:""}${(null==a?void 0:a.body)?`\n ${this.paddedString("Body",c)}:\n${a.body}`:""}`}if("network-response"===e.messageType){const t=e.minimumLevel===V.Trace?this.formattedHeaders(e):void 0,s=this.formattedBody(e),n=((null==s?void 0:s.formData)?"Headers":"Status").length,i=e.message;return`Received HTTP response:\n ${this.paddedString("URL",n)}: ${i.url}\n ${this.paddedString("Status",n)}: ${i.status}${e.details?`\n ${this.paddedString("Details",n)}: ${e.details}`:""}${t?`\n ${this.paddedString("Headers",n)}:\n${t}`:""}${(null==s?void 0:s.body)?`\n ${this.paddedString("Body",n)}:\n${s.body}`:""}`}if("error"===e.messageType){const t=this.formattedErrorStatus(e),s=e.message;return`${s.name}: ${s.message}${t?`\n${t}`:""}`}return""}formattedObject(e){const t=(s,n=1,i=!1)=>{const r=10===n,a=" ".repeat(2*n),o=[],c=(t,s)=>!!e.ignoredKeys&&("function"==typeof e.ignoredKeys?e.ignoredKeys(t,s):e.ignoredKeys.includes(t));if("string"==typeof s)o.push(`${a}- ${s}`);else if("number"==typeof s)o.push(`${a}- ${s}`);else if("boolean"==typeof s)o.push(`${a}- ${s}`);else if(null===s)o.push(`${a}- null`);else if(void 0===s)o.push(`${a}- undefined`);else if("function"==typeof s)o.push(`${a}- `);else if("object"==typeof s)if(Array.isArray(s)||"function"!=typeof s.toString||0===s.toString().indexOf("[object"))if(Array.isArray(s))for(const e of s){const s=i?"":a;if(null===e)o.push(`${s}- null`);else if(void 0===e)o.push(`${s}- undefined`);else if("function"==typeof e)o.push(`${s}- `);else if("object"==typeof e){const i=Array.isArray(e),a=r?"...":t(e,n+1,!i);o.push(`${s}-${i&&!r?"\n":" "}${a}`)}else o.push(`${s}- ${e}`);i=!1}else{const e=s,u=Object.keys(e),l=u.reduce(((t,s)=>Math.max(t,c(s,e)?t:s.length)),0);for(const s of u){if(c(s,e))continue;const u=i?"":a,h=e[s],d=s.padEnd(l," ");if(null===h)o.push(`${u}${d}: null`);else if(void 0===h)o.push(`${u}${d}: undefined`);else if("function"==typeof h)o.push(`${u}${d}: `);else if("object"==typeof h){const e=Array.isArray(h),s=e&&0===h.length,i=!(e||h instanceof String||0!==Object.keys(h).length),a=!e&&"function"==typeof h.toString&&0!==h.toString().indexOf("[object"),c=r?"...":s?"[]":i?"{}":t(h,n+1,a);o.push(`${u}${d}:${r||a||s||i?" ":"\n"}${c}`)}else o.push(`${u}${d}: ${h}`);i=!1}}else o.push(`${i?"":a}${s.toString()}`),i=!1;return o.join("\n")};return t(e.message)}formattedHeaders(e){if(!e.message.headers)return;const t=e.message.headers,s=Object.keys(t).reduce(((e,t)=>Math.max(e,t.length)),0);return Object.keys(t).map((e=>` - ${e.toLowerCase().padEnd(s," ")}: ${t[e]}`)).join("\n")}formattedBody(e){var t;if(!e.message.headers)return;let s,n;const i=e.message.headers,r=null!==(t=i["content-type"])&&void 0!==t?t:i["Content-Type"],a="formData"in e.message?e.message.formData:void 0,o=e.message.body;if(a){const e=a.reduce(((e,{key:t})=>Math.max(e,t.length)),0);s=a.map((({key:t,value:s})=>` - ${t.padEnd(e," ")}: ${s}`)).join("\n")}return o?(n="string"==typeof o?` ${o}`:o instanceof ArrayBuffer||"[object ArrayBuffer]"===Object.prototype.toString.call(o)?!r||-1===r.indexOf("javascript")&&-1===r.indexOf("json")?` ArrayBuffer { byteLength: ${o.byteLength} }`:` ${z.decoder.decode(o)}`:` File { name: ${o.name}${o.contentLength?`, contentLength: ${o.contentLength}`:""}${o.mimeType?`, mimeType: ${o.mimeType}`:""} }`,{body:n,formData:s}):{formData:s}}formattedErrorStatus(e){if(!e.message.status)return;const t=e.message.status,s=t.errorData;let n;if(z.isError(s))n=` ${s.name}: ${s.message}`,s.stack&&(n+=`\n${s.stack.split("\n").map((e=>` ${e}`)).join("\n")}`);else if(s)try{n=` ${JSON.stringify(s)}`}catch(e){n=` ${s}`}return` Category : ${t.category}\n Operation : ${t.operation}\n Status : ${t.statusCode}${n?`\n Error data:\n${n}`:""}`}paddedString(e,t){return e.padEnd(t-e.length," ")}static isError(e){return!!e&&(e instanceof Error||"[object Error]"===Object.prototype.toString.call(e))}}z.decoder=new TextDecoder;const J=[404,409];var X;!function(e){e.Unknown="UnknownEndpoint",e.MessageSend="MessageSendEndpoint",e.Subscribe="SubscribeEndpoint",e.Presence="PresenceEndpoint",e.Files="FilesEndpoint",e.MessageStorage="MessageStorageEndpoint",e.ChannelGroups="ChannelGroupsEndpoint",e.DevicePushNotifications="DevicePushNotificationsEndpoint",e.AppContext="AppContextEndpoint",e.MessageReactions="MessageReactionsEndpoint"}(X||(X={}));class Q{static None(){return{shouldRetry:(e,t,s,n,i)=>!1,getDelay:(e,t)=>-1,validate:()=>!0}}static LinearRetryPolicy(e){var t;return{delay:e.delay,maximumRetry:e.maximumRetry,excluded:null!==(t=e.excluded)&&void 0!==t?t:[],shouldRetry(e,t,s,n,i){return Y(e,t,s,null!=n?n:0,this.maximumRetry,this.excluded,i)},getDelay(e,t){let s=-1;return t&&void 0!==t.headers["retry-after"]&&(s=parseInt(t.headers["retry-after"],10)),-1===s&&(s=this.delay),1e3*(s+Math.random())},validate(){if(this.delay<2)throw new Error("Delay can not be set less than 2 seconds for retry")}}}static ExponentialRetryPolicy(e){var t;return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,excluded:null!==(t=e.excluded)&&void 0!==t?t:[],shouldRetry(e,t,s,n,i){return Y(e,t,s,null!=n?n:0,this.maximumRetry,this.excluded,i)},getDelay(e,t){let s=-1;return t&&void 0!==t.headers["retry-after"]&&(s=parseInt(t.headers["retry-after"],10)),-1===s&&(s=Math.min(this.minimumDelay*Math.pow(2,e),this.maximumDelay)),1e3*(s+Math.random())},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry")}}}}const Y=(e,t,s,n,i,r,a)=>{var o;if(s&&(s===h.PNCancelledCategory||s===h.PNBadRequestCategory||s===h.PNAccessDeniedCategory))return!1;if(Z(e,r))return!1;if(n>i)return!1;const c=null!==(o=null==t?void 0:t.status)&&void 0!==o?o:a;return(void 0===c||!J.includes(c))&&(!t||(429===t.status||t.status>=500))},Z=(e,t)=>!!(t&&t.length>0)&&t.includes(ee(e)),ee=e=>{let t=X.Unknown;return e.path.startsWith("/v2/subscribe")?t=X.Subscribe:e.path.startsWith("/publish/")||e.path.startsWith("/signal/")?t=X.MessageSend:e.path.startsWith("/v2/presence")?t=X.Presence:e.path.startsWith("/v2/history")||e.path.startsWith("/v3/history")?t=X.MessageStorage:e.path.startsWith("/v1/message-actions/")?t=X.MessageReactions:e.path.startsWith("/v1/channel-registration/")||e.path.startsWith("/v2/objects/")?t=X.ChannelGroups:e.path.startsWith("/v1/push/")||e.path.startsWith("/v2/push/")?t=X.DevicePushNotifications:e.path.startsWith("/v1/files/")&&(t=X.Files),t};class te{constructor(e,t,s){this.previousEntryTimestamp=0,this.pubNubId=e,this.minLogLevel=t,this.loggers=s}get logLevel(){return this.minLogLevel}trace(e,t){this.log(V.Trace,e,t)}debug(e,t){this.log(V.Debug,e,t)}info(e,t){this.log(V.Info,e,t)}warn(e,t){this.log(V.Warn,e,t)}error(e,t){this.log(V.Error,e,t)}log(e,t,s){if(ee[i](r)))}}var se={exports:{}}; -/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",s={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function n(){var e,t,s="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(s+="-"),s+=(12===e?4:16===e?3&t|8:t).toString(16);return s}function i(e,t){var n=s[t||"all"];return n&&n.test(e)||!1}n.isUUID=i,n.VERSION=t,e.uuid=n,e.isUUID=i}(t),null!==e&&(e.exports=t.uuid)}(se,se.exports);var ne=t(se.exports),ie={createUUID:()=>ne.uuid?ne.uuid():ne()};const re=(e,t)=>{var s,n,i,r;!e.retryConfiguration&&e.enableEventEngine&&(e.retryConfiguration=Q.ExponentialRetryPolicy({minimumDelay:2,maximumDelay:150,maximumRetry:6,excluded:[X.MessageSend,X.Presence,X.Files,X.MessageStorage,X.ChannelGroups,X.DevicePushNotifications,X.AppContext,X.MessageReactions]}));const a=`pn-${ie.createUUID()}`;e.logVerbosity?e.logLevel=V.Debug:void 0===e.logLevel&&(e.logLevel=V.None);const o=new te(oe(a),e.logLevel,[...null!==(s=e.loggers)&&void 0!==s?s:[],new z]);void 0!==e.logVerbosity&&o.warn("Configuration","'logVerbosity' is deprecated. Use 'logLevel' instead."),null===(n=e.retryConfiguration)||void 0===n||n.validate();const c=e.useRandomIVs;null!==(i=e.useRandomIVs)&&void 0!==i||(e.useRandomIVs=true),void 0!==c&&(o.warn("Configuration","'useRandomIVs' is deprecated. Pass it to 'cryptoModule' instead."),!1===c&&o.warn("Configuration","Setting 'useRandomIVs' to false is insecure and should only be used to support legacy clients.\n Do not disable random IVs in new applications.")),e.origin=ae(null!==(r=e.ssl)&&void 0!==r&&r,e.origin);const u=e.cryptoModule;u&&delete e.cryptoModule;const l=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_loggerManager:o,_instanceId:a,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(e.useInstanceId)return this._instanceId},getInstanceId(){if(e.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},logger(){return this._loggerManager},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt(),logger:this.logger()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,isSharedWorkerEnabled:()=>"Web"===e.sdkFamily&&e.subscriptionWorkerUrl,getKeepPresenceChannelsInPresenceRequests:()=>"Web"===e.sdkFamily&&e.subscriptionWorkerUrl,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},getFileTimeout(){return this.fileRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"13.1.3"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?(o.warn("Configuration","'cipherKey' is deprecated. Use 'cryptoModule' instead."),l.setCipherKey(e.cipherKey)):u&&(l._cryptoModule=u),l},ae=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`},oe=e=>{let t=2166136261;for(let s=0;s>>0;return t.toString(16).padStart(8,"0")};class ce{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){var t,s;const n=this.cbor.decodeToken(e);if(void 0!==n){const e=n.res.uuid?Object.keys(n.res.uuid):[],i=n.res.usr?Object.keys(n.res.usr):[],r=Object.keys(n.res.chan),a=Object.keys(n.res.grp),o=n.pat.uuid?Object.keys(n.pat.uuid):[],c=n.pat.usr?Object.keys(n.pat.usr):[],u=Object.keys(n.pat.chan),l=Object.keys(n.pat.grp),h={version:n.v,timestamp:n.t,ttl:n.ttl,authorized_uuid:n.uuid,signature:n.sig},d=e.length>0,p=i.length>0,g=r.length>0,b=a.length>0;if(d||p||g||b){if(h.resources={},d){const t=h.resources.uuids={};e.forEach((e=>t[e]=this.extractPermissions(n.res.uuid[e])))}if(p){const e=h.resources.users={};i.forEach((t=>e[t]=this.extractCrudPermissions(n.res.usr[t])))}if(g){const e=h.resources.channels={};r.forEach((t=>e[t]=this.extractPermissions(n.res.chan[t])))}if(b){const e=h.resources.groups={};a.forEach((t=>e[t]=this.extractPermissions(n.res.grp[t])))}}const y=this.extractDataSyncScopes(n.res);y&&((null!==(t=h.resources)&&void 0!==t?t:h.resources={}).dataSync=y);const m=o.length>0,f=c.length>0,v=u.length>0,O=l.length>0;if(m||f||v||O){if(h.patterns={},m){const e=h.patterns.uuids={};o.forEach((t=>e[t]=this.extractPermissions(n.pat.uuid[t])))}if(f){const e=h.patterns.users={};c.forEach((t=>e[t]=this.extractCrudPermissions(n.pat.usr[t])))}if(v){const e=h.patterns.channels={};u.forEach((t=>e[t]=this.extractPermissions(n.pat.chan[t])))}if(O){const e=h.patterns.groups={};l.forEach((t=>e[t]=this.extractPermissions(n.pat.grp[t])))}}const S=this.extractDataSyncScopes(n.pat);S&&((null!==(s=h.patterns)&&void 0!==s?s:h.patterns={}).dataSync=S);const j=this.extractCategories(n.cat);return j&&(h.categories=j),n.meta&&Object.keys(n.meta).length>0&&(h.meta=n.meta),h}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}extractCategories(e){if(!e)return;const t={};return"number"==typeof e.chan&&(t.channels={get:!(32&~e.chan)}),"number"==typeof e.uuid&&(t.uuids={get:!(32&~e.uuid)}),Object.keys(t).length>0?t:void 0}extractDataSyncScopes(e){let t;return[["entities","datasync:entities"],["relationships","datasync:relationships"],["memberships","datasync:memberships"]].forEach((([s,n])=>{const i=e[n];if(!i)return;const r=Object.keys(i);if(0===r.length)return;const a=(null!=t?t:t={})[s]={};r.forEach((e=>a[e]=this.extractCrudPermissions(i[e])))})),t}extractCrudPermissions(e){return{create:!(16&~e),get:!(32&~e),update:!(64&~e),delete:!(8&~e)}}}var ue;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.PUT="PUT",e.DELETE="DELETE",e.LOCAL="LOCAL"}(ue||(ue={}));class le{constructor(e,t,s,n){this.publishKey=e,this.secretKey=t,this.hasher=s,this.logger=n}signature(e){const t=e.path.startsWith("/publish")?ue.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===ue.POST||t===ue.PATCH||t===ue.PUT){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=le.textDecoder.decode(t):t&&"object"!=typeof t&&(n=t),n&&(s+=n)}return this.logger.trace("RequestSignature",(()=>({messageType:"text",message:`Request signature input:\n${s}`}))),`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((e=>`${t}=${C(e)}`)).join("&"):`${t}=${C(s)}`})).join("&")}}le.textDecoder=new TextDecoder("utf-8");class he{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new le(t.publishKey,t.secretKey,s,this.logger))}get logger(){return this.configuration.clientConfiguration.logger()}makeSendable(e){const t=this.configuration.clientConfiguration.retryConfiguration,s=this.configuration.transport;if(void 0!==t){let n,i,r=!1,a=0;const o={abort:e=>{r=!0,n&&clearTimeout(n),i&&i.abort(e)}};return[new Promise(((o,c)=>{const u=()=>{if(r)return;const[l,h]=s.makeSendable(this.request(e));i=h;const d=(s,i)=>{let r=-1;t.shouldRetry(e,s,null==i?void 0:i.category,a+1,null==i?void 0:i.statusCode)&&(r=t.getDelay(a,s)),r>0?(a++,this.logger.warn("PubNubMiddleware",`HTTP request retry #${a} in ${r}ms.`),n=setTimeout((()=>u()),r)):s?o(s):i&&c(i)};l.then((e=>d(e))).catch((e=>d(void 0,e)))};u()})),i?o:void 0]}return s.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.getInstanceId()),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,i=null!==(t=n&&n.getToken())&&void 0!==t?t:s.authKey;i&&(e.queryParameters.auth=i)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class de{constructor(e,t="fetch"){this.logger=e,this.transport=t,e.debug("WebTransport",`Create with configuration:\n - transport: ${t}`),"fetch"===t&&"undefined"==typeof fetch&&(e.warn("WebTransport",`'${t}' not supported in this browser. Fallback to the 'xhr' transport.`),this.transport="xhr"),"fetch"===this.transport&&(de.originalFetch=de.getOriginalFetch(),this.isFetchMonkeyPatched()&&e.warn("WebTransport","Native Web Fetch API 'fetch' function monkey patched."))}makeSendable(e){const t=new AbortController,s={abortController:t,abort:e=>{t.signal.aborted||(this.logger.trace("WebTransport",`On-demand request aborting: ${e}`),t.abort(e))}};return[this.webTransportRequestFromTransportRequest(e).then((t=>(this.logger.debug("WebTransport",(()=>({messageType:"network-request",message:e}))),this.sendRequest(t,s).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const s=e[1].byteLength>0?e[1]:void 0,{status:n,headers:i}=e[0],r={};i.forEach(((e,t)=>r[t]=e.toLowerCase()));const a={status:n,url:t.url,headers:r,body:s};if(this.logger.debug("WebTransport",(()=>({messageType:"network-response",message:a}))),n>=400)throw G.create(a);return a})).catch((t=>{const s=("string"==typeof t?t:t.message).toLowerCase();let n="string"==typeof t?new Error(t):t;throw s.includes("timeout")?this.logger.warn("WebTransport",(()=>({messageType:"network-request",message:e,details:"Timeout",canceled:!0}))):s.includes("cancel")||s.includes("abort")?(this.logger.debug("WebTransport",(()=>({messageType:"network-request",message:e,details:"Aborted",canceled:!0}))),n=new Error("Aborted"),n.name="AbortError"):s.includes("network")?this.logger.warn("WebTransport",(()=>({messageType:"network-request",message:e,details:"Network error",failed:!0}))):this.logger.warn("WebTransport",(()=>({messageType:"network-request",message:e,details:G.create(n).message,failed:!0}))),G.create(n)}))))),s]}request(e){return e}sendRequest(e,t){return r(this,void 0,void 0,(function*(){return"fetch"===this.transport?this.sendFetchRequest(e,t):this.sendXHRRequest(e,t)}))}sendFetchRequest(e,t){return r(this,void 0,void 0,(function*(){let s;const n=new Promise(((n,i)=>{s=setTimeout((()=>{clearTimeout(s),i(new Error("Request timeout")),t.abort("Cancel because of timeout")}),1e3*e.timeout)})),i=new Request(e.url,{method:e.method,headers:e.headers,redirect:"follow",body:e.body});return Promise.race([de.originalFetch(i,{signal:t.abortController.signal,credentials:"omit",cache:"no-cache"}).then((e=>(s&&clearTimeout(s),e))),n])}))}sendXHRRequest(e,t){return r(this,void 0,void 0,(function*(){return new Promise(((s,n)=>{var i;const r=new XMLHttpRequest;r.open(e.method,e.url,!0);let a=!1;r.responseType="arraybuffer",r.timeout=1e3*e.timeout,t.abortController.signal.onabort=()=>{r.readyState!=XMLHttpRequest.DONE&&r.readyState!=XMLHttpRequest.UNSENT&&(a=!0,r.abort())},Object.entries(null!==(i=e.headers)&&void 0!==i?i:{}).forEach((([e,t])=>r.setRequestHeader(e,t))),r.onabort=()=>{n(new Error("Aborted"))},r.ontimeout=()=>{n(new Error("Request timeout"))},r.onerror=()=>{if(!a){const t=this.transportResponseFromXHR(e.url,r);n(new Error(G.create(t).message))}},r.onload=()=>{const e=new Headers;r.getAllResponseHeaders().split("\r\n").forEach((t=>{const[s,n]=t.split(": ");s.length>1&&n.length>1&&e.append(s,n)})),s(new Response(r.response,{status:r.status,headers:e,statusText:r.statusText}))},r.send(e.body)}))}))}webTransportRequestFromTransportRequest(e){return r(this,void 0,void 0,(function*(){let t,s=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const s=e.body,n=new FormData;for(const{key:t,value:s}of e.formData)n.append(t,s);try{const e=yield s.toArrayBuffer();n.append("file",new Blob([e],{type:"application/octet-stream"}),s.name)}catch(e){this.logger.warn("WebTransport",(()=>({messageType:"error",message:e})));try{const e=yield s.toFileUri();n.append("file",e,s.name)}catch(e){this.logger.error("WebTransport",(()=>({messageType:"error",message:e})))}}t=n}else if(e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer))if(e.compressible&&"undefined"!=typeof CompressionStream){const s="string"==typeof e.body?de.encoder.encode(e.body):e.body,n=s.byteLength,i=new ReadableStream({start(e){e.enqueue(s),e.close()}});t=yield new Response(i.pipeThrough(new CompressionStream("deflate"))).arrayBuffer(),this.logger.trace("WebTransport",(()=>{const e=t.byteLength,s=(e/n).toFixed(2);return{messageType:"text",message:`Body of ${n} bytes, compressed by ${s}x to ${e} bytes.`}}))}else t=e.body;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(s=`${s}?${T(e.queryParameters)}`),{url:`${e.origin}${s}`,method:e.method,headers:e.headers,timeout:e.timeout,body:t}}))}isFetchMonkeyPatched(e){return!(null!=e?e:fetch).toString().includes("[native code]")&&"fetch"!==fetch.name}transportResponseFromXHR(e,t){const s=t.getAllResponseHeaders().split("\n"),n={};for(const e of s){const[t,s]=e.trim().split(":");t&&s&&(n[t.toLowerCase()]=s.trim())}return{status:t.status,url:e,headers:n,body:t.response}}static getOriginalFetch(){if("undefined"==typeof document||!document.body)return fetch.bind(globalThis);let e=document.querySelector('iframe[name="pubnub-context-unpatched-fetch"]');return e||(e=document.createElement("iframe"),e.style.display="none",e.name="pubnub-context-unpatched-fetch",e.src="about:blank",document.body.appendChild(e)),e.contentWindow?e.contentWindow.fetch.bind(e.contentWindow):fetch.bind(globalThis)}}de.encoder=new TextEncoder,de.decoder=new TextDecoder;class pe{constructor(e){this.params=e,this.requestIdentifier=ie.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(e){this&&this.cancellationController&&this.cancellationController.abort(e)}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return r(this,void 0,void 0,(function*(){return this.deserializeResponse(e)}))}request(){var e,t,s,n,i,r;const a={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:ue.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(n=null===(s=this.params)||void 0===s?void 0:s.cancellable)&&void 0!==n&&n,compressible:null!==(r=null===(i=this.params)||void 0===i?void 0:i.compressible)&&void 0!==r&&r,timeout:10,identifier:this.requestIdentifier},o=this.headers;if(o&&(a.headers=o),a.method===ue.POST||a.method===ue.PATCH||a.method===ue.PUT){const[e,t]=[this.body,this.formData];t&&(a.formData=t),e&&(a.body=e)}return a}get headers(){var e,t;return Object.assign({"Accept-Encoding":"gzip, deflate"},null!==(t=null===(e=this.params)||void 0===e?void 0:e.compressible)&&void 0!==t&&t?{"Content-Encoding":"deflate"}:{})}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=pe.decoder.decode(e.body),s=e.headers["content-type"];let n;if(!s||-1===s.indexOf("javascript")&&-1===s.indexOf("json"))throw new d("Service response error, check status for details",g(t,e.status));try{n=JSON.parse(t)}catch(s){throw console.error("Error parsing JSON response:",s),new d("Service response error, check status for details",g(t,e.status))}if("status"in n&&"number"==typeof n.status&&n.status>=400)throw G.create(e);return n}}pe.decoder=new TextDecoder;var ge;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files",e[e.DataSync=5]="DataSync"}(ge||(ge={}));const be=new Set([ge.Presence,ge.Message,ge.Signal,ge.AppContext,ge.MessageAction,ge.Files,ge.DataSync]),ye={user:"user",channel:"channel",membership:"membership"};class me extends pe{constructor(e){var t,s,n,i,r,a;super({cancellable:!0}),this.parameters=e,null!==(t=(i=this.parameters).withPresence)&&void 0!==t||(i.withPresence=false),null!==(s=(r=this.parameters).channelGroups)&&void 0!==s||(r.channelGroups=[]),null!==(n=(a=this.parameters).channels)&&void 0!==n||(a.channels=[])}operation(){return K.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return r(this,void 0,void 0,(function*(){let t,s;try{s=pe.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",g(s,e.status));const n=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;if(e.c.endsWith("-pnpres")?t=ge.Presence:null!=t||(t=ge.Message),!be.has(t))return;const s=R(e.d);if(t!=ge.Presence&&t!=ge.Signal&&"string"==typeof e.d)return t==ge.Message?{type:ge.Message,data:this.messageFromEnvelope(e),pn_mfp:s}:{type:ge.Files,data:this.fileFromEnvelope(e),pn_mfp:s};if(t==ge.Message)return{type:ge.Message,data:this.messageFromEnvelope(e),pn_mfp:s};if(t===ge.Presence)return{type:ge.Presence,data:this.presenceEventFromEnvelope(e),pn_mfp:s};if(t==ge.Signal)return{type:ge.Signal,data:this.signalFromEnvelope(e),pn_mfp:s};if(t===ge.AppContext)return{type:ge.AppContext,data:this.appContextFromEnvelope(e),pn_mfp:s};if(t===ge.MessageAction)return{type:ge.MessageAction,data:this.messageActionFromEnvelope(e),pn_mfp:s};if(t===ge.DataSync){const t=this.dataSyncFromEnvelope(e);return t?{type:ge.DataSync,data:t,pn_mfp:s}:{type:ge.Message,data:this.messageFromEnvelope(e),pn_mfp:s}}return{type:ge.Files,data:this.fileFromEnvelope(e),pn_mfp:s}})).filter((e=>void 0!==e));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:n}}))}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{accept:"text/javascript"})}presenceEventFromEnvelope(e){var t;const{d:s}=e,[n,i]=this.subscriptionChannelFromEnvelope(e),r=n.replace("-pnpres",""),a=null!==i?r:null,o=null!==i?i:r;let c;if("string"==typeof s)try{const e=JSON.parse(s);null===e||"object"!=typeof e||Array.isArray(e)||(c=e)}catch(e){}else c=s;return c&&("data"in c?(c.state=c.data,delete c.data):"action"in c&&"interval"===c.action&&(c.hereNowRefresh=null!==(t=c.here_now_refresh)&&void 0!==t&&t,delete c.here_now_refresh)),Object.assign({channel:r,subscription:i,actualChannel:a,subscribedChannel:o,timetoken:e.p.t},null!=c?c:{})}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,i]=this.decryptedData(e.d),r={channel:t,subscription:s,actualChannel:null!==s?t:null,subscribedChannel:null!==s?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(r.userMetadata=e.u),e.cmt&&(r.customMessageType=e.cmt),i&&(r.error=i),r}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),e.cmt&&(n.customMessageType=e.cmt),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}dataSyncFromEnvelope(e){var t;const[s,n]=this.subscriptionChannelFromEnvelope(e),i=e.d,r=null==i?void 0:i.metadata;if(!r||"data-sync"!==r.source||!r.event||!r.type)return;const a=r.className?r.className.split(":"):[],o=a.filter((e=>e.length>0)),c=o.length>0?o[o.length-1]:void 0,u=r.classLevel,l=void 0===u?a[0]:"Global"===u?c:void 0,h=("entity"===r.type||"relationship"===r.type)&&l&&ye[l.toLowerCase()]||r.type,d=void 0!==r.classVersion?Number.parseInt(`${r.classVersion}`,10):NaN,p=Number.isNaN(d)?void 0:d,g=null!==(t=i.data)&&void 0!==t?t:{},b={version:i.version,source:r.source,type:r.type,className:c,classLevel:u,classVersion:p};let y;if("delete"===r.event&&"membership"===h){const e={id:g.id,deletedAt:g.deletedAt};"string"==typeof g.channelId&&(e.channelId=g.channelId),"string"==typeof g.userId&&(e.userId=g.userId),y=Object.assign(Object.assign({},b),{event:r.event,objectType:h,data:e})}else if("delete"===r.event&&"relationship"===h){const e={id:g.id,deletedAt:g.deletedAt};"string"==typeof g.entityAId&&(e.entityAId=g.entityAId),"string"==typeof g.entityBId&&(e.entityBId=g.entityBId),y=Object.assign(Object.assign({},b),{event:r.event,objectType:h,data:e})}else y="delete"===r.event?Object.assign(Object.assign({},b),{event:r.event,objectType:h,data:{id:g.id,deletedAt:g.deletedAt}}):Object.assign(Object.assign({},b),{event:r.event,objectType:h,data:Object.assign({},g)});return{channel:s,subscription:n,timetoken:e.p.t,message:y}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,i]=this.decryptedData(e.d);let r=i;const a={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(a.userMetadata=e.u),n?"string"==typeof n?null!=r||(r="Unexpected file information payload data type."):(a.message=n.message,n.file&&(a.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):null!=r||(r="File information payload is missing."),e.cmt&&(a.customMessageType=e.cmt),r&&(a.error=r),a}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,s;try{const s=this.parameters.crypto.decrypt(e);t=s instanceof ArrayBuffer?JSON.parse(fe.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class fe extends me{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${P(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:i,region:r,onDemand:a}=this.parameters,o={};return a&&(o["on-demand"]=1),e&&e.length>0&&(o["channel-group"]=e.sort().join(",")),t&&t.length>0&&(o["filter-expr"]=t),s&&(o.heartbeat=s),n&&Object.keys(n).length>0&&(o.state=JSON.stringify(n)),void 0!==i&&"string"==typeof i?i.length>0&&"0"!==i&&(o.tt=i):void 0!==i&&i>0&&(o.tt=i),r&&(o.tr=r),o}}class ve{constructor(){this.hasListeners=!1,this.listeners=[{count:-1,listener:{}}]}set onStatus(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"status"})}set onMessage(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"message"})}set onPresence(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"presence"})}set onSignal(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"signal"})}set onObjects(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"objects"})}set onMessageAction(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"messageAction"})}set onFile(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"file"})}set onDataSync(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"dataSync"})}handleEvent(e){if(this.hasListeners)if(e.type===ge.Message)this.announce("message",e.data);else if(e.type===ge.Signal)this.announce("signal",e.data);else if(e.type===ge.Presence)this.announce("presence",e.data);else if(e.type===ge.AppContext){const{data:t}=e,{message:s}=t;if(this.announce("objects",t),"uuid"===s.type){const{message:e,channel:n}=t,r=i(t,["message","channel"]),{event:a,type:o}=s,c=i(s,["event","type"]),u=Object.assign(Object.assign({},r),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"user"})});this.announce("user",u)}else if("channel"===s.type){const{message:e,channel:n}=t,r=i(t,["message","channel"]),{event:a,type:o}=s,c=i(s,["event","type"]),u=Object.assign(Object.assign({},r),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"space"})});this.announce("space",u)}else if("membership"===s.type){const{message:e,channel:n}=t,r=i(t,["message","channel"]),{event:a,data:o}=s,c=i(s,["event","data"]),{uuid:u,channel:l}=o,h=i(o,["uuid","channel"]),d=Object.assign(Object.assign({},r),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.announce("membership",d)}}else e.type===ge.MessageAction?this.announce("messageAction",e.data):e.type===ge.Files?this.announce("file",e.data):e.type===ge.DataSync&&this.announce("dataSync",e.data)}handleStatus(e){this.hasListeners&&this.announce("status",e)}addListener(e){this.updateTypeOrObjectListener({add:!0,listener:e})}removeListener(e){this.updateTypeOrObjectListener({add:!1,listener:e})}removeAllListeners(){this.listeners=[{count:-1,listener:{}}],this.hasListeners=!1}updateTypeOrObjectListener(e){if(e.type)"function"==typeof e.listener?this.listeners[0].listener[e.type]=e.listener:delete this.listeners[0].listener[e.type];else if(e.listener&&"function"!=typeof e.listener){let t,s=!1;for(t of this.listeners)if(t.listener===e.listener){e.add?(t.count++,s=!0):(t.count--,0===t.count&&this.listeners.splice(this.listeners.indexOf(t),1));break}e.add&&!s&&this.listeners.push({count:1,listener:e.listener})}this.hasListeners=this.listeners.length>1||Object.keys(this.listeners[0]).length>0}announce(e,t){this.listeners.forEach((({listener:s})=>{const n=s[e];n&&n(t)}))}}class Oe{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class Se{constructor(e){this.config=e,e.logger().debug("DedupingManager",(()=>({messageType:"object",message:{maximumCacheSize:e.maximumCacheSize},details:"Create with configuration:"}))),this.maximumCacheSize=e.maximumCacheSize,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify(null!==(t=e.message)&&void 0!==t?t:"")).toString()}`}isDuplicate(e){return this.hashHistory.includes(this.getKey(e))}addEntry(e){this.hashHistory.length>=this.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}hashCode(e){let t=0;if(0===e.length)return t;for(let s=0;s{this.pendingChannelSubscriptions.add(e),this.channels[e]={},i&&(this.presenceChannels[e]={}),(r||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==s||s.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},i&&(this.presenceChannelGroups[e]={}),(r||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t=!1){let{channels:s,channelGroups:n}=e;const r=new Set,a=new Set;if(null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],a.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],a.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],r.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],r.add(e))})),0===a.size&&0===r.size)return;const o=this.lastTimetoken,c=this.currentTimetoken;0===Object.keys(this.channels).length&&0===Object.keys(this.presenceChannels).length&&0===Object.keys(this.channelGroups).length&&0===Object.keys(this.presenceChannelGroups).length&&(this.lastTimetoken="0",this.currentTimetoken="0",this.referenceTimetoken=null,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect(!0),!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(r),s=Array.from(a),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,r=i(e,["error"]);let a;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?a=e.errorData.message:"message"in e&&"string"==typeof e.message&&(a=e.message)),this.emitStatus(Object.assign(Object.assign({},r),{error:null!=a&&a,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:c,lastTimetoken:o}))})))}unsubscribeAll(e=!1){this.disconnectedWhileHandledEvent=!0,this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(e=!1){this.disconnectedWhileHandledEvent=!1,this.stopSubscribeLoop();const t=[...Object.keys(this.channelGroups)],s=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((e=>t.push(`${e}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>s.push(`${e}-pnpres`))),0===s.length&&0===t.length||(this.subscribeCall(Object.assign(Object.assign(Object.assign({channels:s,channelGroups:t,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken},null!==this.region?{region:this.region}:{}),this.configuration.filterExpression?{filterExpression:this.configuration.filterExpression}:{}),{onDemand:!this.subscriptionStatusAnnounced||e}),((e,t)=>{this.processSubscribeResponse(e,t)})),!e&&this.configuration.useSmartHeartbeat&&this.startHeartbeatTimer())}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;return void(e.category===h.PNTimeoutCategory?this.startSubscribeLoop():e.category===h.PNNetworkIssuesCategory||e.category===h.PNMalformedResponseCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.emitStatus({category:h.PNNetworkDownCategory})),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.emitStatus({category:h.PNNetworkUpCategory})),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.emitStatus(t)})),this.reconnectionManager.startPolling(),this.emitStatus(Object.assign(Object.assign({},e),{category:h.PNNetworkIssuesCategory}))):e.category===h.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.emitStatus(e)):this.emitStatus(e))}if(this.referenceTimetoken=I(t.cursor.timetoken,this.storedTimetoken),this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.emitStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:i}=this.configuration;n&&s.length>=n&&this.emitStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{const e={timetoken:this.currentTimetoken,region:this.region?this.region:void 0};this.configuration.logger().debug("SubscriptionManager",(()=>({messageType:"object",message:s.map((e=>({type:e.type,data:Object.assign(Object.assign({},e.data),{pn_mfp:e.pn_mfp})}))),details:"Received events:"}))),s.forEach((t=>{if(i&&"message"in t.data&&"timetoken"in t.data){if(this.dedupingManager.isDuplicate(t.data))return void this.configuration.logger().warn("SubscriptionManager",(()=>({messageType:"object",message:t.data,details:"Duplicate message detected (skipped):"})));this.dedupingManager.addEntry(t.data)}this.emitEvent(e,t)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.emitStatus(t)}this.region=t.cursor.region,this.disconnectedWhileHandledEvent?this.disconnectedWhileHandledEvent=!1:this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;null==s||s.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==n||n.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(null==s||s.forEach((e=>this.heartbeatChannels[e]={})),null==n||n.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==s||s.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==n||n.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:s,channelGroups:n},(e=>this.emitStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.configuration.useSmartHeartbeat||this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.emitStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.emitStatus({category:h.PNNetworkDownCategory}),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.emitStatus(e)}))}}class we{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class ke extends we{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,i={topic:t,environment:s};return n.length&&(i.excluded_devices=n),i}}class Ce extends we{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get androidNotification(){var e;return null===(e=this.payload.android)||void 0===e?void 0:e.notification}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this.androidNotification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this.androidNotification.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.androidNotification.notification_count=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.androidNotification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.androidNotification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.androidNotification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={},this.payload.android={notification:{}}}toObject(){var e,t;const s={},n=Object.assign({},this.payload.notification),r=Object.assign({},this.payload.android),a=i(Object.assign({},null!==(e=r.notification)&&void 0!==e?e:{}),["title","body"]);if(this._isSilent){const e={};this._title&&(e.title=this._title),this._body&&(e.body=this._body);for(const[t,s]of Object.entries(a))null!=s&&(e[t]=String(s));this.payload.data&&Object.assign(e,this.payload.data),Object.keys(e).length&&(s.data=e),delete r.notification,Object.keys(r).length&&(s.android=r)}else if(Object.keys(n).length&&(s.notification=n),this.payload.data&&Object.keys(this.payload.data).length&&(s.data=Object.assign({},this.payload.data)),Object.keys(a).length){const e=i(r,["notification"]);s.android=Object.assign(Object.assign({},e),{notification:a})}else{const e=i(r,["notification"]);Object.keys(e).length&&(s.android=e)}const o=i(this.payload,["notification","android","data","pn_exceptions"]);return Object.assign(s,o),(null===(t=this.payload.pn_exceptions)||void 0===t?void 0:t.length)&&(s.pn_exceptions=this.payload.pn_exceptions),Object.keys(s).length?s:null}}class Pe{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new ke(this._payload.apns,e,t),this.fcm=new Ce(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_fcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class Ne{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class Ee{transition(e,t){var s;if(this.transitionMap.has(t.type))return null===(s=this.transitionMap.get(t.type))||void 0===s?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class Te extends Ne{constructor(e){super(!0),this.logger=e,this._pendingEvents=[],this._inTransition=!1}get currentState(){return this._currentState}get currentContext(){return this._currentContext}describe(e){return new Ee(e)}start(e,t){this._currentState=e,this._currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this._currentState)throw this.logger.error("Engine","Finite state machine is not started"),new Error("Start the engine first");if(this._inTransition)return this.logger.trace("Engine",(()=>({messageType:"object",message:e,details:"Event engine in transition. Enqueue received event:"}))),void this._pendingEvents.push(e);this._inTransition=!0,this.logger.trace("Engine",(()=>({messageType:"object",message:e,details:"Event engine received event:"}))),this.notify({type:"eventReceived",event:e});const t=this._currentState.transition(this._currentContext,e);if(t){const[s,n,i]=t;this.logger.trace("Engine",`Exiting state: ${this._currentState.label}`);for(const e of this._currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this._currentContext)});this.logger.trace("Engine",(()=>({messageType:"object",details:`Entering '${s.label}' state with context:`,message:n})));const r=this._currentState;this._currentState=s;const a=this._currentContext;this._currentContext=n,this.notify({type:"transitionDone",fromState:r,fromContext:a,toState:s,toContext:n,event:e});for(const e of i)this.notify({type:"invocationDispatched",invocation:e});for(const e of this._currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this._currentContext)})}else this.logger.warn("Engine",`No transition from '${this._currentState.label}' found for event: ${e.type}`);if(this._inTransition=!1,this._pendingEvents.length>0){const e=this._pendingEvents.shift();e&&(this.logger.trace("Engine",(()=>({messageType:"object",message:e,details:"De-queueing pending event:"}))),this.transition(e))}}}class _e{constructor(e,t){this.dependencies=e,this.logger=t,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if(this.logger.trace("Dispatcher",`Process invocation: ${e.type}`),"CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw this.logger.error("Dispatcher",`Unhandled invocation '${e.type}'`),new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);this.logger.trace("Dispatcher",(()=>({messageType:"object",details:"Call invocation handler with parameters:",message:e.payload,ignoredKeys:["abortSignal"]}))),e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function Ie(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function Me(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function Re(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!0});return s.type=e,s.cancel={type:"CANCEL",payload:e,managed:!1},s}class De extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class Ue extends Ne{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new De}abort(){this._aborted=!0,this.notify(new De)}}class Ae{constructor(e,t){this.payload=e,this.dependencies=t}}class $e extends Ae{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new Ue}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const Fe=e=>(t,s)=>new $e(t,s,e),xe=Re("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),qe=Me("LEAVE",((e,t)=>({channels:e,groups:t}))),Ge=Me("EMIT_STATUS",(e=>e)),Le=Re("WAIT",(()=>({}))),Ke=Ie("RECONNECT",(()=>({}))),He=Ie("DISCONNECT",((e=!1)=>({isOffline:e}))),Be=Ie("JOINED",((e,t)=>({channels:e,groups:t}))),We=Ie("LEFT",((e,t)=>({channels:e,groups:t}))),Ve=Ie("LEFT_ALL",((e=!1)=>({isOffline:e}))),ze=Ie("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Je=Ie("HEARTBEAT_FAILURE",(e=>e)),Xe=Ie("TIMES_UP",(()=>({})));class Qe extends _e{constructor(e,t){super(t,t.config.logger()),this.on(xe.type,Fe(((t,s,n)=>r(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:i,config:r}){s.throwIfAborted();try{yield n(Object.assign(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups},r.maintainPresenceState&&{state:i}),{heartbeat:r.presenceTimeout}));e.transition(ze(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;e.transition(Je(t))}}}))))),this.on(qe.type,Fe(((e,t,s)=>r(this,[e,t,s],void 0,(function*(e,t,{leave:s,config:n}){if(!n.suppressLeaveEvents)try{s({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Le.type,Fe(((t,s,n)=>r(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){const{cancelDelay:i,promise:r}=n();s.throwIfAborted();const a=s.subscribe((()=>i()));return yield r,a(),s.throwIfAborted(),e.transition(Xe())}))))),this.on(Ge.type,Fe(((e,t,s)=>r(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s,config:n}){n.announceFailedHeartbeats&&!0===(null==e?void 0:e.error)?s(Object.assign(Object.assign({},e),{operation:K.PNHeartbeatOperation})):n.announceSuccessfulHeartbeats&&200===e.statusCode&&s(Object.assign(Object.assign({},e),{error:!1,operation:K.PNHeartbeatOperation,category:h.PNAcknowledgmentCategory}))})))))}}const Ye=new Ee("HEARTBEAT_INACTIVE"),Ze=new Ee("HEARTBEATING"),et=new Ee("HEARTBEAT_COOLDOWN"),tt=new Ee("HEARTBEAT_STOPPED"),st=new Ee("HEARTBEAT_FAILED");Ye.on(Be.type,((e,t)=>Ze.with({channels:t.payload.channels,groups:t.payload.groups}))),Ze.onEnter((e=>xe(e.channels,e.groups))),Ze.onExit((()=>xe.cancel)),Ze.on(ze.type,((e,t)=>et.with({channels:e.channels,groups:e.groups},[Ge(Object.assign({},t.payload))]))),Ze.on(Be.type,((e,t)=>Ze.with({channels:[...e.channels,...t.payload.channels.filter((t=>!e.channels.includes(t)))],groups:[...e.groups,...t.payload.groups.filter((t=>!e.groups.includes(t)))]}))),Ze.on(We.type,((e,t)=>Ze.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[qe(t.payload.channels,t.payload.groups)]))),Ze.on(Je.type,((e,t)=>st.with(Object.assign({},e),[...t.payload.status?[Ge(Object.assign({},t.payload.status))]:[]]))),Ze.on(He.type,((e,t)=>tt.with({channels:e.channels,groups:e.groups},[...t.payload.isOffline?[]:[qe(e.channels,e.groups)]]))),Ze.on(Ve.type,((e,t)=>Ye.with(void 0,[...t.payload.isOffline?[]:[qe(e.channels,e.groups)]]))),et.onEnter((()=>Le())),et.onExit((()=>Le.cancel)),et.on(Xe.type,((e,t)=>Ze.with({channels:e.channels,groups:e.groups}))),et.on(Be.type,((e,t)=>Ze.with({channels:[...e.channels,...t.payload.channels.filter((t=>!e.channels.includes(t)))],groups:[...e.groups,...t.payload.groups.filter((t=>!e.groups.includes(t)))]}))),et.on(We.type,((e,t)=>Ze.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[qe(t.payload.channels,t.payload.groups)]))),et.on(He.type,((e,t)=>tt.with({channels:e.channels,groups:e.groups},[...t.payload.isOffline?[]:[qe(e.channels,e.groups)]]))),et.on(Ve.type,((e,t)=>Ye.with(void 0,[...t.payload.isOffline?[]:[qe(e.channels,e.groups)]]))),tt.on(Be.type,((e,t)=>tt.with({channels:[...e.channels,...t.payload.channels.filter((t=>!e.channels.includes(t)))],groups:[...e.groups,...t.payload.groups.filter((t=>!e.groups.includes(t)))]}))),tt.on(We.type,((e,t)=>tt.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),tt.on(Ke.type,((e,t)=>Ze.with({channels:e.channels,groups:e.groups}))),tt.on(Ve.type,((e,t)=>Ye.with(void 0))),st.on(Be.type,((e,t)=>Ze.with({channels:[...e.channels,...t.payload.channels.filter((t=>!e.channels.includes(t)))],groups:[...e.groups,...t.payload.groups.filter((t=>!e.groups.includes(t)))]}))),st.on(We.type,((e,t)=>Ze.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[qe(t.payload.channels,t.payload.groups)]))),st.on(Ke.type,((e,t)=>Ze.with({channels:e.channels,groups:e.groups}))),st.on(He.type,((e,t)=>tt.with({channels:e.channels,groups:e.groups},[...t.payload.isOffline?[]:[qe(e.channels,e.groups)]]))),st.on(Ve.type,((e,t)=>Ye.with(void 0,[...t.payload.isOffline?[]:[qe(e.channels,e.groups)]])));class nt{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.channels=[],this.groups=[],this.engine=new Te(e.config.logger()),this.dispatcher=new Qe(this.engine,e),e.config.logger().debug("PresenceEventEngine","Create presence event engine."),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(Ye,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...(null!=e?e:[]).filter((e=>!this.channels.includes(e)))],this.groups=[...this.groups,...(null!=t?t:[]).filter((e=>!this.groups.includes(e)))],0===this.channels.length&&0===this.groups.length||this.engine.transition(Be(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){e&&(this.channels=this.channels.filter((t=>!e.includes(t)))),t&&(this.groups=this.groups.filter((e=>!t.includes(e)))),this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(We(null!=e?e:[],null!=t?t:[]))}leaveAll(e=!1){this.dependencies.presenceState&&(this.channels.forEach((e=>delete this.dependencies.presenceState[e])),this.groups.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=[],this.groups=[],this.engine.transition(Ve(e))}reconnect(){this.engine.transition(Ke())}disconnect(e=!1){this.engine.transition(He(e))}dispose(){this.disconnect(!0),this._unsubscribeEngine(),this.dispatcher.dispose()}}const it=Ie("SUBSCRIPTION_CHANGED",((e,t,s=!1)=>({channels:e,groups:t,isOffline:s}))),rt=Ie("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),at=Ie("HANDSHAKE_SUCCESS",(e=>e)),ot=Ie("HANDSHAKE_FAILURE",(e=>e)),ct=Ie("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),ut=Ie("RECEIVE_FAILURE",(e=>e)),lt=Ie("DISCONNECT",((e=!1)=>({isOffline:e}))),ht=Ie("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),dt=Ie("UNSUBSCRIBE_ALL",(()=>({}))),pt=new Ee("UNSUBSCRIBED"),gt=new Ee("HANDSHAKING"),bt=new Ee("HANDSHAKE_STOPPED"),yt=new Ee("HANDSHAKE_FAILED"),mt=new Ee("RECEIVING"),ft=new Ee("RECEIVE_STOPPED"),vt=new Ee("RECEIVE_FAILED");pt.on(it.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?pt.with(void 0):gt.with({channels:t.channels,groups:t.groups,onDemand:!0}))),pt.on(rt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?pt.with(void 0):gt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region},onDemand:!0})));const Ot=Re("HANDSHAKE",((e,t,s)=>({channels:e,groups:t,onDemand:s}))),St=Re("RECEIVE_MESSAGES",((e,t,s,n)=>({channels:e,groups:t,cursor:s,onDemand:n}))),jt=Me("EMIT_MESSAGES",((e,t)=>({cursor:e,events:t}))),wt=Me("EMIT_STATUS",(e=>e));gt.onEnter((e=>{var t;return Ot(e.channels,e.groups,null!==(t=e.onDemand)&&void 0!==t&&t)})),gt.onExit((()=>Ot.cancel)),gt.on(it.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?pt.with(void 0):gt.with({channels:t.channels,groups:t.groups,cursor:e.cursor,onDemand:!0}))),gt.on(at.type,((e,{payload:t})=>{var s,n,i,r,a;return mt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(s=e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=e.cursor)||void 0===n?void 0:n.timetoken:t.timetoken,region:t.region},referenceTimetoken:I(t.timetoken,null===(i=e.cursor)||void 0===i?void 0:i.timetoken)},[wt({category:h.PNConnectedCategory,affectedChannels:e.channels.slice(0),affectedChannelGroups:e.groups.slice(0),operation:K.PNSubscribeOperation,currentTimetoken:(null===(r=e.cursor)||void 0===r?void 0:r.timetoken)?null===(a=e.cursor)||void 0===a?void 0:a.timetoken:t.timetoken})])})),gt.on(ot.type,((e,t)=>{var s;return yt.with(Object.assign(Object.assign({},e),{reason:t.payload}),[wt({category:h.PNConnectionErrorCategory,error:null===(s=t.payload.status)||void 0===s?void 0:s.category})])})),gt.on(lt.type,((e,t)=>{var s;if(t.payload.isOffline){const t=G.create(new Error("Network connection error")).toPubNubError(K.PNSubscribeOperation);return yt.with(Object.assign(Object.assign({},e),{reason:t}),[wt({category:h.PNConnectionErrorCategory,error:null===(s=t.status)||void 0===s?void 0:s.category})])}return bt.with(Object.assign({},e))})),gt.on(rt.type,((e,{payload:t})=>{var s;return 0===t.channels.length&&0===t.groups.length?pt.with(void 0):gt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0},onDemand:!0})})),gt.on(dt.type,(e=>pt.with())),bt.on(it.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?pt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),bt.on(ht.type,((e,{payload:t})=>gt.with(Object.assign(Object.assign({},e),{cursor:t.cursor||e.cursor,onDemand:!0})))),bt.on(rt.type,((e,{payload:t})=>{var s;return 0===t.channels.length&&0===t.groups.length?pt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||(null===(s=e.cursor)||void 0===s?void 0:s.region)||0}})})),bt.on(dt.type,(e=>pt.with())),yt.on(it.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?pt.with(void 0):gt.with({channels:t.channels,groups:t.groups,cursor:e.cursor,onDemand:!0}))),yt.on(ht.type,((e,{payload:t})=>gt.with(Object.assign(Object.assign({},e),{cursor:t.cursor||e.cursor,onDemand:!0})))),yt.on(rt.type,((e,{payload:t})=>{var s,n;return 0===t.channels.length&&0===t.groups.length?pt.with(void 0):gt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region?t.cursor.region:null!==(n=null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)&&void 0!==n?n:0},onDemand:!0})})),yt.on(dt.type,(e=>pt.with())),mt.onEnter((e=>{var t;return St(e.channels,e.groups,e.cursor,null!==(t=e.onDemand)&&void 0!==t&&t)})),mt.onExit((()=>St.cancel)),mt.on(ct.type,((e,{payload:t})=>mt.with({channels:e.channels,groups:e.groups,cursor:t.cursor,referenceTimetoken:I(t.cursor.timetoken)},[jt(e.cursor,t.events)]))),mt.on(it.type,((e,{payload:t})=>{var s;if(0===t.channels.length&&0===t.groups.length){let e;return t.isOffline&&(e=null===(s=G.create(new Error("Network connection error")).toPubNubError(K.PNSubscribeOperation).status)||void 0===s?void 0:s.category),pt.with(void 0,[wt(Object.assign({category:t.isOffline?h.PNDisconnectedUnexpectedlyCategory:h.PNDisconnectedCategory,operation:K.PNUnsubscribeOperation},e?{error:e}:{}))])}return mt.with({channels:t.channels,groups:t.groups,cursor:e.cursor,referenceTimetoken:e.referenceTimetoken,onDemand:!0},[wt({category:h.PNSubscriptionChangedCategory,affectedChannels:t.channels.slice(0),affectedChannelGroups:t.groups.slice(0),currentTimetoken:e.cursor.timetoken})])})),mt.on(rt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?pt.with(void 0,[wt({category:h.PNDisconnectedCategory})]):mt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||e.cursor.region},referenceTimetoken:I(e.cursor.timetoken,`${t.cursor.timetoken}`,e.referenceTimetoken),onDemand:!0},[wt({category:h.PNSubscriptionChangedCategory,affectedChannels:t.channels.slice(0),affectedChannelGroups:t.groups.slice(0),currentTimetoken:t.cursor.timetoken})]))),mt.on(ut.type,((e,{payload:t})=>{var s;return vt.with(Object.assign(Object.assign({},e),{reason:t}),[wt({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.status)||void 0===s?void 0:s.category})])})),mt.on(lt.type,((e,t)=>{var s;if(t.payload.isOffline){const t=G.create(new Error("Network connection error")).toPubNubError(K.PNSubscribeOperation);return vt.with(Object.assign(Object.assign({},e),{reason:t}),[wt({category:h.PNDisconnectedUnexpectedlyCategory,operation:K.PNSubscribeOperation,error:null===(s=t.status)||void 0===s?void 0:s.category})])}return ft.with(Object.assign({},e),[wt({category:h.PNDisconnectedCategory,operation:K.PNSubscribeOperation})])})),mt.on(dt.type,(e=>pt.with(void 0,[wt({category:h.PNDisconnectedCategory,operation:K.PNUnsubscribeOperation})]))),ft.on(it.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?pt.with(void 0):ft.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),ft.on(rt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?pt.with(void 0):ft.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||e.cursor.region}}))),ft.on(ht.type,((e,{payload:t})=>{var s;return gt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.cursor.timetoken?null===(s=t.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.cursor.region||e.cursor.region},onDemand:!0})})),ft.on(dt.type,(()=>pt.with(void 0))),vt.on(ht.type,((e,{payload:t})=>{var s;return gt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.cursor.timetoken?null===(s=t.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.cursor.region||e.cursor.region},onDemand:!0})})),vt.on(it.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?pt.with(void 0):gt.with({channels:t.channels,groups:t.groups,cursor:e.cursor,onDemand:!0}))),vt.on(rt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?pt.with(void 0):gt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||e.cursor.region},onDemand:!0}))),vt.on(dt.type,(e=>pt.with(void 0)));class kt extends _e{constructor(e,t){super(t,t.config.logger()),this.on(Ot.type,Fe(((t,s,n)=>r(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:i,config:r}){s.throwIfAborted();try{const a=yield n(Object.assign(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:r.filterExpression},r.maintainPresenceState&&{state:i}),{onDemand:t.onDemand}));return e.transition(at(a))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(ot(t))}}}))))),this.on(St.type,Fe(((t,s,n)=>r(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,config:i}){s.throwIfAborted();try{const r=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:i.filterExpression,onDemand:t.onDemand});e.transition(ct(r.cursor,r.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!s.aborted)return e.transition(ut(t))}}}))))),this.on(jt.type,Fe(((e,t,s)=>r(this,[e,t,s],void 0,(function*({cursor:e,events:t},s,{emitMessages:n}){t.length>0&&n(e,t)}))))),this.on(wt.type,Fe(((e,t,s)=>r(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){return s(e)})))))}}class Ct{get _engine(){return this.engine}constructor(e){this.channels=[],this.groups=[],this.dependencies=e,this.engine=new Te(e.config.logger()),this.dispatcher=new kt(this.engine,e),e.config.logger().debug("EventEngine","Create subscribe event engine."),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(pt,void 0)}get subscriptionTimetoken(){const e=this.engine.currentState;if(!e)return;let t,s="0";if(e.label===mt.label){const e=this.engine.currentContext;s=e.cursor.timetoken,t=e.referenceTimetoken}return _(s,null!=t?t:"0")}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){var i;const r=null==e?void 0:e.some((e=>!this.channels.includes(e))),a=null==t?void 0:t.some((e=>!this.groups.includes(e))),o=r||a;if(this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],n&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),s)this.engine.transition(rt(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s));else if(o)this.engine.transition(it(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]]))));else{this.dependencies.config.logger().debug("EventEngine","Skipping state transition - all channels/groups already subscribed. Emitting SubscriptionChanged event.");const e=this.engine.currentState,t=this.engine.currentContext;let s="0";if((null==e?void 0:e.label)===mt.label&&t){s=null===(i=t.cursor)||void 0===i?void 0:i.timetoken}this.dependencies.emitStatus({category:h.PNSubscriptionChangedCategory,affectedChannels:Array.from(new Set(this.channels)),affectedChannelGroups:Array.from(new Set(this.groups)),currentTimetoken:s})}this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=N(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=N(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const i=E(this.channels,e),r=E(this.groups,t);this.dependencies.presenceState&&(null==i||i.forEach((e=>delete this.dependencies.presenceState[e])),null==r||r.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=s,this.groups=n,this.engine.transition(it(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:i.slice(0),groups:r.slice(0)})}}unsubscribeAll(e=!1){const t=this.getSubscribedChannelGroups(),s=this.getSubscribedChannels();this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(it(this.channels.slice(0),this.groups.slice(0),e)),this.dependencies.leaveAll&&this.dependencies.leaveAll({channels:s,groups:t,isOffline:e})}reconnect({timetoken:e,region:t}){const s=this.getSubscribedChannels(),n=this.getSubscribedChannels();this.engine.transition(ht(e,t)),this.dependencies.presenceReconnect&&this.dependencies.presenceReconnect({channels:n,groups:s})}disconnect(e=!1){const t=this.getSubscribedChannels(),s=this.getSubscribedChannels();this.engine.transition(lt(e)),this.dependencies.presenceDisconnect&&this.dependencies.presenceDisconnect({channels:s,groups:t,isOffline:e})}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(!0),this._unsubscribeEngine(),this.dispatcher.dispose()}}class Pt extends pe{constructor(e){var t;const s=null!==(t=e.sendByPost)&&void 0!==t&&t;super({method:s?ue.POST:ue.GET,compressible:s}),this.parameters=e,this.parameters.sendByPost=s}operation(){return K.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return r(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${C(t)}/0${this.parameters.sendByPost?"":`/${C(n)}`}`}get queryParameters(){const{customMessageType:e,meta:t,replicate:s,storeInHistory:n,ttl:i}=this.parameters,r={};return e&&(r.custom_message_type=e),void 0!==n&&(r.store=n?"1":"0"),void 0!==i&&(r.ttl=i),void 0===s||s||(r.norep="true"),t&&"object"==typeof t&&(r.meta=JSON.stringify(t)),r}get headers(){var e;return this.parameters.sendByPost?Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"}):super.headers}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Nt extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return r(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,i=JSON.stringify(n);return`/signal/${e}/${t}/0/${C(s)}/0/${C(i)}`}get queryParameters(){const{customMessageType:e}=this.parameters,t={};return e&&(t.custom_message_type=e),t}}class Et extends me{operation(){return K.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${P(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n,heartbeat:i,onDemand:r}=this.parameters,a={ee:""};return r&&(a["on-demand"]=1),e&&e.length>0&&(a["channel-group"]=e.sort().join(",")),t&&t.length>0&&(a["filter-expr"]=t),"string"==typeof s?s&&"0"!==s&&s.length>0&&(a.tt=s):s&&s>0&&(a.tt=s),n&&(a.tr=n),i&&(a.heartbeat=i),a}}class Tt extends me{operation(){return K.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${P(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,heartbeat:t,filterExpression:s,state:n,onDemand:i}=this.parameters,r={ee:""};return i&&(r["on-demand"]=1),e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),s&&s.length>0&&(r["filter-expr"]=s),n&&Object.keys(n).length>0&&(r.state=JSON.stringify(n)),t&&(r.heartbeat=t),r}}var _t;!function(e){e[e.Channel=0]="Channel",e[e.ChannelGroup=1]="ChannelGroup"}(_t||(_t={}));class It{constructor({channels:e,channelGroups:t}){this.isEmpty=!0,this._channelGroups=new Set((null!=t?t:[]).filter((e=>e.length>0))),this._channels=new Set((null!=e?e:[]).filter((e=>e.length>0))),this.isEmpty=0===this._channels.size&&0===this._channelGroups.size}get length(){return this.isEmpty?0:this._channels.size+this._channelGroups.size}get channels(){return this.isEmpty?[]:Array.from(this._channels)}get channelGroups(){return this.isEmpty?[]:Array.from(this._channelGroups)}contains(e){return!this.isEmpty&&(this._channels.has(e)||this._channelGroups.has(e))}with(e){return new It({channels:[...this._channels,...e._channels],channelGroups:[...this._channelGroups,...e._channelGroups]})}without(e){return new It({channels:[...this._channels].filter((t=>!e._channels.has(t))),channelGroups:[...this._channelGroups].filter((t=>!e._channelGroups.has(t)))})}add(e){return e._channelGroups.size>0&&(this._channelGroups=new Set([...this._channelGroups,...e._channelGroups])),e._channels.size>0&&(this._channels=new Set([...this._channels,...e._channels])),this.isEmpty=0===this._channels.size&&0===this._channelGroups.size,this}remove(e){return e._channelGroups.size>0&&(this._channelGroups=new Set([...this._channelGroups].filter((t=>!e._channelGroups.has(t))))),e._channels.size>0&&(this._channels=new Set([...this._channels].filter((t=>!e._channels.has(t))))),this}removeAll(){return this._channels.clear(),this._channelGroups.clear(),this.isEmpty=!0,this}toString(){return`SubscriptionInput { channels: [${this.channels.join(", ")}], channelGroups: [${this.channelGroups.join(", ")}], is empty: ${this.isEmpty?"true":"false"}} }`}}class Mt{constructor(e,t,s,n){this._isSubscribed=!1,this.clones={},this.parents=[],this._id=ie.createUUID(),this.referenceTimetoken=n,this.subscriptionInput=t,this.options=s,this.client=e}get id(){return this._id}get isLastClone(){return 1===Object.keys(this.clones).length}get isSubscribed(){return!!this._isSubscribed||this.parents.length>0&&this.parents.some((e=>e.isSubscribed))}set isSubscribed(e){this.isSubscribed!==e&&(this._isSubscribed=e)}addParentState(e){this.parents.includes(e)||this.parents.push(e)}removeParentState(e){const t=this.parents.indexOf(e);-1!==t&&this.parents.splice(t,1)}storeClone(e,t){this.clones[e]||(this.clones[e]=t)}}class Rt{constructor(e,t="Subscription"){this.subscriptionType=t,this.id=ie.createUUID(),this.eventDispatcher=new ve,this._state=e}get state(){return this._state}get channels(){return this.state.subscriptionInput.channels.slice(0)}get channelGroups(){return this.state.subscriptionInput.channelGroups.slice(0)}set onMessage(e){this.eventDispatcher.onMessage=e}set onPresence(e){this.eventDispatcher.onPresence=e}set onSignal(e){this.eventDispatcher.onSignal=e}set onObjects(e){this.eventDispatcher.onObjects=e}set onMessageAction(e){this.eventDispatcher.onMessageAction=e}set onFile(e){this.eventDispatcher.onFile=e}set onDataSync(e){this.eventDispatcher.onDataSync=e}addListener(e){this.eventDispatcher.addListener(e)}removeListener(e){this.eventDispatcher.removeListener(e)}removeAllListeners(){this.eventDispatcher.removeAllListeners()}handleEvent(e,t){var s;if((!this.state.cursor||e>this.state.cursor)&&(this.state.cursor=e),this.state.referenceTimetoken&&t.data.timetoken({messageType:"text",message:`Event timetoken (${t.data.timetoken}) is older than reference timetoken (${this.state.referenceTimetoken}) for ${this.id} subscription object. Ignoring event.`})));if((null===(s=this.state.options)||void 0===s?void 0:s.filter)&&!this.state.options.filter(t))return void this.state.client.logger.trace(this.subscriptionType,`Event filtered out by filter function for ${this.id} subscription object. Ignoring event.`);const n=Object.values(this.state.clones);n.length>0&&this.state.client.logger.trace(this.subscriptionType,`Notify ${this.id} subscription object clones (count: ${n.length}) about received event.`),n.forEach((e=>e.eventDispatcher.handleEvent(t)))}dispose(){const e=Object.keys(this.state.clones);e.length>1?(this.state.client.logger.debug(this.subscriptionType,`Remove subscription object clone on dispose: ${this.id}`),delete this.state.clones[this.id]):1===e.length&&this.state.clones[this.id]&&(this.state.client.logger.debug(this.subscriptionType,`Unsubscribe subscription object on dispose: ${this.id}`),this.unsubscribe())}invalidate(e=!1){this.state._isSubscribed=!1,e&&(delete this.state.clones[this.id],0===Object.keys(this.state.clones).length&&(this.state.client.logger.trace(this.subscriptionType,"Last clone removed. Reset shared subscription state."),this.state.subscriptionInput.removeAll(),this.state.parents=[]))}subscribe(e){this.state.isSubscribed?this.state.client.logger.trace(this.subscriptionType,"Already subscribed. Ignoring subscribe request."):(this.state.client.logger.debug(this.subscriptionType,(()=>e?{messageType:"object",message:e,details:"Subscribe with parameters:"}:{messageType:"text",message:"Subscribe"})),this.state.isSubscribed=!0,this.updateSubscription({subscribing:!0,timetoken:null==e?void 0:e.timetoken}))}unsubscribe(){if(!this.state._isSubscribed||this.state.isSubscribed){if(!this.state._isSubscribed&&this.state.parents.length>0&&this.state.isSubscribed)return void this.state.client.logger.warn(this.subscriptionType,(()=>({messageType:"object",details:"Subscription is subscribed as part of a subscription set. Remove from active sets to unsubscribe:",message:this.state.parents.filter((e=>e.isSubscribed))})));if(!this.state._isSubscribed)return void this.state.client.logger.trace(this.subscriptionType,"Not subscribed. Ignoring unsubscribe request.")}this.state.client.logger.debug(this.subscriptionType,"Unsubscribe"),this.state.isSubscribed=!1,delete this.state.cursor,this.updateSubscription({subscribing:!1})}updateSubscription(e){var t,s;(null==e?void 0:e.timetoken)&&((null===(t=this.state.cursor)||void 0===t?void 0:t.timetoken)&&"0"!==(null===(s=this.state.cursor)||void 0===s?void 0:s.timetoken)?"0"!==e.timetoken&&e.timetoken>this.state.cursor.timetoken&&(this.state.cursor.timetoken=e.timetoken):this.state.cursor={timetoken:e.timetoken});const n=e.subscriptions&&e.subscriptions.length>0?e.subscriptions:void 0;e.subscribing?this.register(Object.assign(Object.assign({},e.timetoken?{cursor:this.state.cursor}:{}),n?{subscriptions:n}:{})):this.unregister(n)}}class Dt extends Mt{constructor(e){const t=new It({});e.subscriptions.forEach((e=>t.add(e.state.subscriptionInput))),super(e.client,t,e.options,e.client.subscriptionTimetoken),this.subscriptions=e.subscriptions}addSubscription(e){this.subscriptions.includes(e)||(e.state.addParentState(this),this.subscriptions.push(e),this.subscriptionInput.add(e.state.subscriptionInput))}removeSubscription(e,t){const s=this.subscriptions.indexOf(e);-1!==s&&(this.subscriptions.splice(s,1),t||e.state.removeParentState(this),this.subscriptionInput.remove(e.state.subscriptionInput))}removeAllSubscriptions(){this.subscriptions.forEach((e=>e.state.removeParentState(this))),this.subscriptions.splice(0,this.subscriptions.length),this.subscriptionInput.removeAll()}}class Ut extends Rt{constructor(e){let t;if("client"in e){let s=[];!e.subscriptions&&e.entities?e.entities.forEach((t=>s.push(t.subscription(e.options)))):e.subscriptions&&(s=e.subscriptions),t=new Dt({client:e.client,subscriptions:s,options:e.options}),s.forEach((e=>e.state.addParentState(t))),t.client.logger.debug("SubscriptionSet",(()=>({messageType:"object",details:"Create subscription set with parameters:",message:Object.assign({subscriptions:t.subscriptions},e.options?e.options:{})})))}else t=e.state,t.client.logger.debug("SubscriptionSet","Create subscription set clone");super(t,"SubscriptionSet"),this.state.storeClone(this.id,this),t.subscriptions.forEach((e=>e.addParentSet(this)))}get state(){return super.state}get subscriptions(){return this.state.subscriptions.slice(0)}handleEvent(e,t){var s;this.state.subscriptionInput.contains(null!==(s=t.data.subscription)&&void 0!==s?s:t.data.channel)&&(this.state._isSubscribed?(super.handleEvent(e,t),this.state.subscriptions.length>0&&this.state.client.logger.trace(this.subscriptionType,`Notify ${this.id} subscription set subscriptions (count: ${this.state.subscriptions.length}) about received event.`),this.state.subscriptions.forEach((s=>s.handleEvent(e,t)))):this.state.client.logger.trace(this.subscriptionType,`Subscription set ${this.id} is not subscribed. Ignoring event.`))}subscriptionInput(e=!1){let t=this.state.subscriptionInput;return this.state.subscriptions.forEach((s=>{e&&s.state.entity.subscriptionsCount>0&&(t=t.without(s.state.subscriptionInput))})),t}cloneEmpty(){return new Ut({state:this.state})}dispose(){const e=this.state.isLastClone;this.state.subscriptions.forEach((t=>{t.removeParentSet(this),e&&t.state.removeParentState(this.state)})),super.dispose()}invalidate(e=!1){(e?this.state.subscriptions.slice(0):this.state.subscriptions).forEach((t=>{e&&(t.state.entity.decreaseSubscriptionCount(this.state.id),t.removeParentSet(this)),t.invalidate(e)})),e&&this.state.removeAllSubscriptions(),super.invalidate()}addSubscription(e){this.addSubscriptions([e])}addSubscriptions(e){const t=[],s=[];this.state.client.logger.debug(this.subscriptionType,(()=>{const t=[],s=[];return e.forEach((e=>{this.state.subscriptions.includes(e)?t.push(e):s.push(e)})),{messageType:"object",details:`Add subscriptions to ${this.id} (subscriptions count: ${this.state.subscriptions.length+s.length}):`,message:{addedSubscriptions:s,ignoredSubscriptions:t}}})),e.filter((e=>!this.state.subscriptions.includes(e))).forEach((e=>{e.state.isSubscribed?s.push(e):t.push(e),e.addParentSet(this),this.state.addSubscription(e)})),0===s.length&&0===t.length||!this.state.isSubscribed||(s.forEach((({state:e})=>e.entity.increaseSubscriptionCount(this.state.id))),t.length>0&&this.updateSubscription({subscribing:!0,subscriptions:t}))}removeSubscription(e){this.removeSubscriptions([e])}removeSubscriptions(e){const t=[];this.state.client.logger.debug(this.subscriptionType,(()=>{const t=[],s=[];return e.forEach((e=>{this.state.subscriptions.includes(e)?s.push(e):t.push(e)})),{messageType:"object",details:`Remove subscriptions from ${this.id} (subscriptions count: ${this.state.subscriptions.length}):`,message:{removedSubscriptions:s,ignoredSubscriptions:t}}})),e.filter((e=>this.state.subscriptions.includes(e))).forEach((e=>{e.state.isSubscribed&&t.push(e),e.removeParentSet(this),this.state.removeSubscription(e,e.parentSetsCount>1)})),0!==t.length&&this.state.isSubscribed&&this.updateSubscription({subscribing:!1,subscriptions:t})}addSubscriptionSet(e){this.addSubscriptions(e.subscriptions)}removeSubscriptionSet(e){this.removeSubscriptions(e.subscriptions)}register(e){var t;const s=null!==(t=e.subscriptions)&&void 0!==t?t:this.state.subscriptions;s.forEach((({state:e})=>e.entity.increaseSubscriptionCount(this.state.id))),this.state.client.logger.trace(this.subscriptionType,(()=>({messageType:"text",message:`Register subscription for real-time events: ${this}`}))),this.state.client.registerEventHandleCapable(this,e.cursor,s)}unregister(e){const t=null!=e?e:this.state.subscriptions;t.forEach((({state:e})=>e.entity.decreaseSubscriptionCount(this.state.id))),this.state.client.logger.trace(this.subscriptionType,(()=>e?{messageType:"object",message:{subscription:this,subscriptions:e},details:"Unregister subscriptions of subscription set from real-time events:"}:{messageType:"text",message:`Unregister subscription from real-time events: ${this}`})),this.state.client.unregisterEventHandleCapable(this,t)}toString(){const e=this.state;return`${this.subscriptionType} { id: ${this.id}, stateId: ${e.id}, clonesCount: ${Object.keys(this.state.clones).length}, isSubscribed: ${e.isSubscribed}, subscriptions: [${e.subscriptions.map((e=>e.toString())).join(", ")}] }`}}class At extends Mt{constructor(e){var t,s;const n=e.entity.subscriptionNames(null!==(s=null===(t=e.options)||void 0===t?void 0:t.receivePresenceEvents)&&void 0!==s&&s),i=new It({[e.entity.subscriptionType==_t.Channel?"channels":"channelGroups"]:n});super(e.client,i,e.options,e.client.subscriptionTimetoken),this.entity=e.entity}}class $t extends Rt{constructor(e){"client"in e?e.client.logger.debug("Subscription",(()=>({messageType:"object",details:"Create subscription with parameters:",message:Object.assign({entity:e.entity},e.options?e.options:{})}))):e.state.client.logger.debug("Subscription","Create subscription clone"),super("state"in e?e.state:new At(e)),this.parents=[],this.handledUpdates=[],this.state.storeClone(this.id,this)}get state(){return super.state}get parentSetsCount(){return this.parents.length}handleEvent(e,t){var s,n;if(this.state.isSubscribed&&this.state.subscriptionInput.contains(null!==(s=t.data.subscription)&&void 0!==s?s:t.data.channel)){if(this.parentSetsCount>0){const e=R(t.data);if(this.handledUpdates.includes(e))return void this.state.client.logger.trace(this.subscriptionType,`Event (${e}) already handled by ${this.id}. Ignoring.`);this.handledUpdates.push(e),this.handledUpdates.length>10&&this.handledUpdates.shift()}this.state.subscriptionInput.contains(null!==(n=t.data.subscription)&&void 0!==n?n:t.data.channel)&&super.handleEvent(e,t)}}subscriptionInput(e=!1){return e&&this.state.entity.subscriptionsCount>0?new It({}):this.state.subscriptionInput}cloneEmpty(){return new $t({state:this.state})}dispose(){this.parentSetsCount>0?this.state.client.logger.debug(this.subscriptionType,(()=>({messageType:"text",message:`'${this.state.entity.subscriptionNames()}' subscription still in use. Ignore dispose request.`}))):(this.handledUpdates.splice(0,this.handledUpdates.length),super.dispose())}invalidate(e=!1){e&&this.state.entity.decreaseSubscriptionCount(this.state.id),this.handledUpdates.splice(0,this.handledUpdates.length),super.invalidate(e)}addParentSet(e){this.parents.includes(e)||(this.parents.push(e),this.state.client.logger.trace(this.subscriptionType,`Add parent subscription set for ${this.id}: ${e.id}. Parent subscription set count: ${this.parentSetsCount}`))}removeParentSet(e){const t=this.parents.indexOf(e);-1!==t&&(this.parents.splice(t,1),this.state.client.logger.trace(this.subscriptionType,`Remove parent subscription set from ${this.id}: ${e.id}. Parent subscription set count: ${this.parentSetsCount}`)),0===this.parentSetsCount&&this.handledUpdates.splice(0,this.handledUpdates.length)}addSubscription(e){this.state.client.logger.debug(this.subscriptionType,(()=>({messageType:"text",message:`Create set with subscription: ${e}`})));const t=new Ut({client:this.state.client,subscriptions:[this,e],options:this.state.options});return this.state.isSubscribed||e.state.isSubscribed?(this.state.client.logger.trace(this.subscriptionType,"Subscribe resulting set because the receiver is already subscribed."),t.subscribe(),t):t}register(e){this.state.entity.increaseSubscriptionCount(this.state.id),this.state.client.logger.trace(this.subscriptionType,(()=>({messageType:"text",message:`Register subscription for real-time events: ${this}`}))),this.state.client.registerEventHandleCapable(this,e.cursor)}unregister(e){this.state.entity.decreaseSubscriptionCount(this.state.id),this.state.client.logger.trace(this.subscriptionType,(()=>({messageType:"text",message:`Unregister subscription from real-time events: ${this}`}))),this.handledUpdates.splice(0,this.handledUpdates.length),this.state.client.unregisterEventHandleCapable(this)}toString(){const e=this.state;return`${this.subscriptionType} { id: ${this.id}, stateId: ${e.id}, entity: ${e.entity.subscriptionNames(!1).pop()}, clonesCount: ${Object.keys(e.clones).length}, isSubscribed: ${e.isSubscribed}, parentSetsCount: ${this.parentSetsCount}, cursor: ${e.cursor?e.cursor.timetoken:"not set"}, referenceTimetoken: ${e.referenceTimetoken?e.referenceTimetoken:"not set"} }`}}class Ft extends pe{constructor(e){var t,s,n,i;super(),this.parameters=e,null!==(t=(n=this.parameters).channels)&&void 0!==t||(n.channels=[]),null!==(s=(i=this.parameters).channelGroups)&&void 0!==s||(i.channelGroups=[])}operation(){return K.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),{channels:s=[],channelGroups:n=[]}=this.parameters,i={channels:{}};return 1===s.length&&0===n.length?i.channels[s[0]]=t.payload:i.channels=t.payload,i}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${P(null!=s?s:[],",")}/uuid/${C(null!=t?t:"")}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class xt extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?void 0===t?"Missing State":0===(null==s?void 0:s.length)&&0===(null==n?void 0:n.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){return r(this,void 0,void 0,(function*(){return{state:this.deserializeResponse(e).payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${P(null!=s?s:[],",")}/uuid/${C(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),s}}class qt extends pe{constructor(e){super({cancellable:!0}),this.parameters=e}operation(){return K.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return r(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${P(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),void 0!==t&&(n.state=JSON.stringify(t)),n}}class Gt extends pe{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return K.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return r(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${P(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class Lt extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${C(t)}`}}class Kt extends pe{constructor(e){var t,s,n,i,r,a,o,c;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(s=(a=this.parameters).includeUUIDs)&&void 0!==s||(a.includeUUIDs=true),null!==(n=(o=this.parameters).includeState)&&void 0!==n||(o.includeState=false),null!==(i=(c=this.parameters).limit)&&void 0!==i||(c.limit=1e3)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?K.PNGlobalHereNowOperation:K.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return r(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e),i="occupancy"in n?1:n.payload.total_channels,r="occupancy"in n?n.occupancy:n.payload.total_occupancy,a={};let o={};const c=this.parameters.limit;let u=!1;if("occupancy"in n){const e=this.parameters.channels[0];o[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:r}}else o=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(o).forEach((e=>{const t=o[e];a[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy},u||t.occupancy!==c||(u=!0)})),{totalChannels:i,totalOccupancy:r,channels:a}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${P(null!=t?t:[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,limit:n,offset:i,queryParameters:r}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.operation()===K.PNHereNowOperation?{limit:n}:{}),this.operation()===K.PNHereNowOperation&&null!=i&&i?{offset:i}:{}),t?{}:{disable_uuids:"1"}),null!=s&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),r)}}class Ht extends pe{constructor(e){super({method:ue.DELETE}),this.parameters=e}operation(){return K.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return r(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${C(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class Bt extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return r(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${P(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class Wt extends pe{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(s=e.includeMeta)&&void 0!==s||(e.includeMeta=false),null!==(n=e.logVerbosity)&&void 0!==n||(e.logVerbosity=false)}operation(){return K.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),s=t[0],n=t[1],i=t[2];return Array.isArray(s)?{messages:s.map((e=>{const t=this.processPayload(e.message),s={entry:t.payload,timetoken:e.timetoken};return t.error&&(s.error=t.error),e.meta&&(s.meta=e.meta),s})),startTimeToken:n,endTimeToken:i}:{messages:[],startTimeToken:n,endTimeToken:i}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${C(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:i,includeMeta:r}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),i?{string_message_token:"true"}:{}),null!=s?{reverse:s.toString()}:{}),r?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let n,i;try{const s=t.decrypt(e);n=s instanceof ArrayBuffer?JSON.parse(Wt.decoder.decode(s)):s}catch(t){s&&console.log("decryption error",t.message),n=e,i=`Error while decrypting message content: ${t.message}`}return{payload:n,error:i}}}var Vt;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Vt||(Vt={}));class zt extends pe{constructor(e){var t,s,n,i,r;super(),this.parameters=e;const a=null!==(t=e.includeMessageActions)&&void 0!==t&&t,o=e.channels.length>1||a?25:100;e.count?e.count=Math.min(e.count,o):e.count=o,e.includeUuid?e.includeUUID=e.includeUuid:null!==(s=e.includeUUID)&&void 0!==s||(e.includeUUID=true),null!==(n=e.stringifiedTimeToken)&&void 0!==n||(e.stringifiedTimeToken=false),null!==(i=e.includeMessageType)&&void 0!==i||(e.includeMessageType=true),null!==(r=e.logVerbosity)&&void 0!==r||(e.logVerbosity=false)}operation(){return K.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?void 0!==s&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return r(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e),n=null!==(t=s.channels)&&void 0!==t?t:{},i={};return Object.keys(n).forEach((e=>{i[e]=n[e].map((t=>{null===t.message_type&&(t.message_type=Vt.Message);const s=this.processPayload(e,t),n=Object.assign(Object.assign({channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.message_type},t.custom_message_type?{customMessageType:t.custom_message_type}:{}),{uuid:t.uuid});if(t.actions){const e=n;e.actions=t.actions,e.data=t.actions}return t.meta&&(n.meta=t.meta),s.error&&(n.error=s.error),n}))})),s.more?{channels:i,more:s.more}:{channels:i}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${P(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeCustomMessageType:n,includeMessageType:i,includeMeta:r,includeUUID:a,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==r&&r?{include_meta:"true"}:{}),a?{include_uuid:"true"}:{}),null!=n?{include_custom_message_type:n?"true":"false"}:{}),i?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||"string"!=typeof t.message)return{payload:t.message};let i,r;try{const e=s.decrypt(t.message);i=e instanceof ArrayBuffer?JSON.parse(zt.decoder.decode(e)):e}catch(e){n&&console.log("decryption error",e.message),i=t.message,r=`Error while decrypting message content: ${e.message}`}if(!r&&i&&t.message_type==Vt.Files&&"object"==typeof i&&this.isFileMessage(i)){const t=i;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:r}}return{payload:i,error:r}}isFileMessage(e){return void 0!==e.file}}class Jt extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${C(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class Xt extends pe{constructor(e){super({method:ue.POST}),this.parameters=e}operation(){return K.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return r(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${C(t)}/message/${s}`}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){return JSON.stringify(this.parameters.action)}}class Qt extends pe{constructor(e){super({method:ue.DELETE}),this.parameters=e}operation(){return K.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return r(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${C(t)}/message/${n}/action/${s}`}}class Yt extends pe{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return K.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return r(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:i,fileName:r}=this.parameters,a=Object.assign({file:{name:r,id:i}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${C(t)}/0/${C(this.prepareMessagePayload(a))}`}get queryParameters(){const{customMessageType:e,storeInHistory:t,ttl:s,meta:n}=this.parameters;return Object.assign(Object.assign(Object.assign({store:t?"1":"0"},e?{custom_message_type:e}:{}),s?{ttl:s}:{}),n&&"object"==typeof n?{meta:JSON.stringify(n)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Zt extends pe{constructor(e){super({method:ue.LOCAL}),this.parameters=e}operation(){return K.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return r(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${C(e)}/files/${C(t)}/${C(s)}`}}class es extends pe{constructor(e){super({method:ue.DELETE}),this.parameters=e}operation(){return K.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${C(s)}/files/${C(t)}/${C(n)}`}}class ts extends pe{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return K.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${C(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class ss extends pe{constructor(e){super({method:ue.POST}),this.parameters=e}operation(){return K.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${C(t)}/generate-upload-url`}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){return JSON.stringify({name:this.parameters.name})}}class ns extends pe{constructor(e){super({method:ue.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return K.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return r(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?ns.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class is{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return r(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:K.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof G?e:G.create(e);throw new d("File upload error.",t.toStatus(K.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return r(this,void 0,void 0,(function*(){const e=new ss(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return r(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:i}=this.parameters,{id:r,name:a,url:o,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&i&&(this.file=yield i.encryptFile(t,this.file,s))),this.parameters.sendRequest(new ns({fileId:r,fileName:a,file:this.file,uploadUrl:o,formFields:c}))}))}publishFileMessage(e,t){return r(this,void 0,void 0,(function*(){var s,n,i,r;let a,o={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{o=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(a=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:o.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=a.status)||void 0===s?void 0:s.category)&&void 0!==n?n:h.PNUnknownCategory,statusCode:null!==(r=null===(i=a.status)||void 0===i?void 0:i.statusCode)&&void 0!==r?r:0,channel:this.parameters.channel,id:e,name:t})}))}}class rs{constructor(e,t){this.subscriptionStateIds=[],this.client=t,this._nameOrId=e}get entityType(){return"Channel"}get subscriptionType(){return _t.Channel}subscriptionNames(e){return[this._nameOrId,...e&&!this._nameOrId.endsWith("-pnpres")?[`${this._nameOrId}-pnpres`]:[]]}subscription(e){return new $t({client:this.client,entity:this,options:e})}get subscriptionsCount(){return this.subscriptionStateIds.length}increaseSubscriptionCount(e){this.subscriptionStateIds.includes(e)||this.subscriptionStateIds.push(e)}decreaseSubscriptionCount(e){{const t=this.subscriptionStateIds.indexOf(e);t>=0&&this.subscriptionStateIds.splice(t,1)}}toString(){return`${this.entityType} { nameOrId: ${this._nameOrId}, subscriptionsCount: ${this.subscriptionsCount} }`}}const as=["default","__default__"],os=e=>{if(!e)return;const t=e.trim();return 0===t.length||as.includes(t.toLowerCase())?void 0:t};class cs extends rs{constructor(e,t,s){super(e,t),this._projection=os(s)}get id(){return this._nameOrId}get projection(){return this._projection}get subscriptionChannel(){return this._projection?`__${this._projection}__${this._nameOrId}`:this._nameOrId}subscriptionNames(e){return[this.subscriptionChannel]}subscription(e){{const t=this.entityForProjection(os(null==e?void 0:e.projection));return t!==this?t.subscription(e):super.subscription(e)}}entityForProjection(e){var t,s,n,i;if(e===this._projection)return this;const r=null!==(t=this.variants)&&void 0!==t?t:this.variants={};null!==(n=r[i=null!==(s=this._projection)&&void 0!==s?s:""])&&void 0!==n||(r[i]=this);const a=null!=e?e:"";let o=r[a];return o||(o=r[a]=this.withProjection(e),o.variants=r),o}toString(){var e;return`${this.entityType} { id: ${this._nameOrId}, projection: ${null!==(e=this._projection)&&void 0!==e?e:"none"}, channel: ${this.subscriptionChannel}, subscriptionsCount: ${this.subscriptionsCount} }`}}class us extends cs{get entityType(){return"DataSyncRelationship"}withProjection(e){return new us(this._nameOrId,this.client,e)}}class ls extends cs{get entityType(){return"DataSyncMembership"}withProjection(e){return new ls(this._nameOrId,this.client,e)}}class hs extends cs{get entityType(){return"DataSyncChannel"}withProjection(e){return new hs(this._nameOrId,this.client,e)}}class ds extends cs{get entityType(){return"DataSyncEntity"}withProjection(e){return new ds(this._nameOrId,this.client,e)}}class ps extends rs{get entityType(){return"ChannelMetadata"}get id(){return this._nameOrId}subscriptionNames(e){return[this.id]}}class gs extends cs{get entityType(){return"DataSyncUser"}withProjection(e){return new gs(this._nameOrId,this.client,e)}}class bs extends rs{get entityType(){return"ChannelGroups"}get name(){return this._nameOrId}get subscriptionType(){return _t.ChannelGroup}}class ys extends rs{get entityType(){return"UserMetadata"}get id(){return this._nameOrId}subscriptionNames(e){return[this.id]}}class ms extends rs{get entityType(){return"Channel"}get name(){return this._nameOrId}}class fs extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return r(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${C(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class vs extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return r(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${C(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class Os extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return r(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${C(t)}`}}class Ss extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return r(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${C(t)}/remove`}}class js extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return r(this,void 0,void 0,(function*(){return{groups:this.deserializeResponse(e).payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class ws{constructor(e,t,s){this.sendRequest=s,this.logger=e,this.keySet=t}listChannels(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List channel group channels with parameters:"})));const s=new Os(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`List channel group channels success. Received ${e.channels.length} channels.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}listGroups(e){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub","List all channel groups.");const t=new js({keySet:this.keySet}),s=e=>{e&&this.logger.debug("PubNub",`List all channel groups success. Received ${e.groups.length} groups.`)};return e?this.sendRequest(t,((t,n)=>{s(n),e(t,n)})):this.sendRequest(t).then((e=>(s(e),e)))}))}addChannels(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add channels to the channel group with parameters:"})));const s=new vs(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Add channels to the channel group success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}removeChannels(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove channels from the channel group with parameters:"})));const s=new fs(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Remove channels from the channel group success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}deleteGroup(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove a channel group with parameters:"})));const s=new Ss(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub",`Remove a channel group success. Removed '${e.channelGroup}' channel group.'`)};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}}class ks extends pe{constructor(e){var t,s;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(s=this.parameters).environment)&&void 0!==t||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?n?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: fcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let i="apns2"===n?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return"remove-device"===t&&(i=`${i}/remove`),i}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;s=Object.assign(Object.assign({},s),{environment:e,topic:t})}return s}}class Cs extends ks{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return K.PNRemovePushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return r(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class Ps extends ks{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return K.PNPushNotificationEnabledChannelsOperation}parse(e){return r(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e)}}))}}class Ns extends ks{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return K.PNAddPushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return r(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class Es extends ks{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return K.PNRemoveAllPushNotificationsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return r(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class Ts{constructor(e,t,s){this.sendRequest=s,this.logger=e,this.keySet=t}listChannels(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List push-enabled channels with parameters:"})));const s=new Ps(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`List push-enabled channels success. Received ${e.channels.length} channels.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}addChannels(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add push-enabled channels with parameters:"})));const s=new Ns(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Add push-enabled channels success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}removeChannels(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove push-enabled channels with parameters:"})));const s=new Cs(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Remove push-enabled channels success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}deleteDevice(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove push notifications for device with parameters:"})));const s=new Es(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Remove push notifications for device success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}}class _s extends pe{constructor(e){var t,s,n,i,r,a;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(r=e.include).customFields)&&void 0!==s||(r.customFields=false),null!==(n=(a=e.include).totalCount)&&void 0!==n||(a.totalCount=false),null!==(i=e.limit)&&void 0!==i||(e.limit=100)}operation(){return K.PNGetAllChannelMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:i}=this.parameters;let r="";return r="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),i?{limit:i}:{}),r.length?{sort:r}:{})}}class Is extends pe{constructor(e){super({method:ue.DELETE}),this.parameters=e}operation(){return K.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${C(t)}`}}class Ms extends pe{constructor(e){var t,s,n,i,r,a,o,c,u,l,h,d,p,g,b,y,m,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(i=(p=e.include).statusField)&&void 0!==i||(p.statusField=false),null!==(r=(g=e.include).typeField)&&void 0!==r||(g.typeField=false),null!==(a=(b=e.include).channelFields)&&void 0!==a||(b.channelFields=false),null!==(o=(y=e.include).customChannelFields)&&void 0!==o||(y.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(f=e.include).channelTypeField)&&void 0!==u||(f.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return K.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${C(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:i}=this.parameters;let r="";r="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),i?{limit:i}:{}),r.length?{sort:r}:{})}}class Rs extends pe{constructor(e){var t,s,n,i,r,a,o,c,u,l,h,d,p,g,b,y,m,f;super({method:ue.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(i=(p=e.include).statusField)&&void 0!==i||(p.statusField=false),null!==(r=(g=e.include).typeField)&&void 0!==r||(g.typeField=false),null!==(a=(b=e.include).channelFields)&&void 0!==a||(b.channelFields=false),null!==(o=(y=e.include).customChannelFields)&&void 0!==o||(y.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(f=e.include).channelTypeField)&&void 0!==u||(f.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return K.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${C(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:i}=this.parameters;let r="";r="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["channel.status","channel.type","status"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),i?{limit:i}:{}),r.length?{sort:r}:{})}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class Ds extends pe{constructor(e){var t,s,n,i;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(i=e.include).customFields)&&void 0!==s||(i.customFields=false),null!==(n=e.limit)&&void 0!==n||(e.limit=100)}operation(){return K.PNGetAllUUIDMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:i}=this.parameters;let r="";return r="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),i?{limit:i}:{}),r.length?{sort:r}:{})}}class Us extends pe{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return K.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${C(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class As extends pe{constructor(e){var t,s,n;super({method:ue.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return K.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json"})}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${C(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class $s extends pe{constructor(e){super({method:ue.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return K.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${C(t)}`}}class Fs extends pe{constructor(e){var t,s,n,i,r,a,o,c,u,l,h,d,p,g,b,y,m,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(i=(p=e.include).statusField)&&void 0!==i||(p.statusField=false),null!==(r=(g=e.include).typeField)&&void 0!==r||(g.typeField=false),null!==(a=(b=e.include).UUIDFields)&&void 0!==a||(b.UUIDFields=false),null!==(o=(y=e.include).customUUIDFields)&&void 0!==o||(y.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(f=e.include).UUIDTypeField)&&void 0!==u||(f.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return K.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${C(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:i}=this.parameters;let r="";r="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),i?{limit:i}:{}),r.length?{sort:r}:{})}}class xs extends pe{constructor(e){var t,s,n,i,r,a,o,c,u,l,h,d,p,g,b,y,m,f;super({method:ue.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(i=(p=e.include).statusField)&&void 0!==i||(p.statusField=false),null!==(r=(g=e.include).typeField)&&void 0!==r||(g.typeField=false),null!==(a=(b=e.include).UUIDFields)&&void 0!==a||(b.UUIDFields=false),null!==(o=(y=e.include).customUUIDFields)&&void 0!==o||(y.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(f=e.include).UUIDTypeField)&&void 0!==u||(f.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return K.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${C(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:i}=this.parameters;let r="";r="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["uuid.status","uuid.type","type"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),i?{limit:i}:{}),r.length?{sort:r}:{})}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class qs extends pe{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return K.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${C(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Gs extends pe{constructor(e){var t,s,n;super({method:ue.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return K.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json"})}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${C(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Ls{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}get logger(){return this.configuration.logger()}getAllUUIDMetadata(e,t){return r(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Get all UUID metadata objects with parameters:"}))),this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return r(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new Ds(Object.assign(Object.assign({},s),{keySet:this.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Get all UUID metadata success. Received ${e.totalCount} UUID metadata objects.`)};return t?this.sendRequest(n,((e,s)=>{i(s),t(e,s)})):this.sendRequest(n).then((e=>(i(e),e)))}))}getUUIDMetadata(e,t){return r(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.configuration.userId},details:`Get ${e&&"function"!=typeof e?"":" current"} UUID metadata object with parameters:`}))),this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return r(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const i=new qs(Object.assign(Object.assign({},n),{keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Get UUID metadata object success. Received '${n.uuid}' UUID metadata object.`)};return t?this.sendRequest(i,((e,s)=>{r(s),t(e,s)})):this.sendRequest(i).then((e=>(r(e),e)))}))}setUUIDMetadata(e,t){return r(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set UUID metadata object with parameters:"}))),this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return r(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new Gs(Object.assign(Object.assign({},e),{keySet:this.keySet})),i=t=>{t&&this.logger.debug("PubNub",`Set UUID metadata object success. Updated '${e.uuid}' UUID metadata object.`)};return t?this.sendRequest(n,((e,s)=>{i(s),t(e,s)})):this.sendRequest(n).then((e=>(i(e),e)))}))}removeUUIDMetadata(e,t){return r(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.configuration.userId},details:`Remove${e&&"function"!=typeof e?"":" current"} UUID metadata object with parameters:`}))),this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return r(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const i=new $s(Object.assign(Object.assign({},n),{keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Remove UUID metadata object success. Removed '${n.uuid}' UUID metadata object.`)};return t?this.sendRequest(i,((e,s)=>{r(s),t(e,s)})):this.sendRequest(i).then((e=>(r(e),e)))}))}getAllChannelMetadata(e,t){return r(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Get all Channel metadata objects with parameters:"}))),this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return r(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new _s(Object.assign(Object.assign({},s),{keySet:this.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Get all Channel metadata objects success. Received ${e.totalCount} Channel metadata objects.`)};return t?this.sendRequest(n,((e,s)=>{i(s),t(e,s)})):this.sendRequest(n).then((e=>(i(e),e)))}))}getChannelMetadata(e,t){return r(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Channel metadata object with parameters:"}))),this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return r(this,void 0,void 0,(function*(){const s=new Us(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Get Channel metadata object success. Received '${e.channel}' Channel metadata object.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}setChannelMetadata(e,t){return r(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Channel metadata object with parameters:"}))),this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return r(this,void 0,void 0,(function*(){const s=new As(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Set Channel metadata object success. Updated '${e.channel}' Channel metadata object.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}removeChannelMetadata(e,t){return r(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Channel metadata object with parameters:"}))),this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return r(this,void 0,void 0,(function*(){const s=new Is(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Remove Channel metadata object success. Removed '${e.channel}' Channel metadata object.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}getChannelMembers(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get channel members with parameters:"})));const s=new Fs(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Get channel members success. Received ${e.totalCount} channel members.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}setChannelMembers(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set channel members with parameters:"})));const s=new xs(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Set channel members success. There are ${e.totalCount} channel members now.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}removeChannelMembers(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove channel members with parameters:"})));const s=new xs(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Remove channel members success. There are ${e.totalCount} channel members now.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}getMemberships(e,t){return r(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},n),details:"Get memberships with parameters:"})));const i=new Ms(Object.assign(Object.assign({},n),{keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Get memberships success. Received ${e.totalCount} memberships.`)};return t?this.sendRequest(i,((e,s)=>{r(s),t(e,s)})):this.sendRequest(i).then((e=>(r(e),e)))}))}setMemberships(e,t){return r(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set memberships with parameters:"})));const n=new Rs(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Set memberships success. There are ${e.totalCount} memberships now.`)};return t?this.sendRequest(n,((e,s)=>{i(s),t(e,s)})):this.sendRequest(n).then((e=>(i(e),e)))}))}removeMemberships(e,t){return r(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove memberships with parameters:"})));const n=new Rs(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Remove memberships success. There are ${e.totalCount} memberships now.`)};return t?this.sendRequest(n,((e,s)=>{i(s),t(e,s)})):this.sendRequest(n).then((e=>(i(e),e)))}))}fetchMemberships(e,t){return r(this,void 0,void 0,(function*(){var s,n;if(this.logger.warn("PubNub","'fetchMemberships' is deprecated. Use 'pubnub.objects.getChannelMembers' or 'pubnub.objects.getMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch memberships with parameters:"}))),"spaceId"in e){const n=e,i={channel:null!==(s=n.spaceId)&&void 0!==s?s:n.channel,filter:n.filter,limit:n.limit,page:n.page,include:Object.assign({},n.include),sort:n.sort?Object.fromEntries(Object.entries(n.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},r=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(i,((e,s)=>{t(e,s?r(s):s)})):this.getChannelMembers(i).then(r)}const i=e,r={uuid:null!==(n=i.userId)&&void 0!==n?n:i.uuid,filter:i.filter,limit:i.limit,page:i.page,include:Object.assign({},i.include),sort:i.sort?Object.fromEntries(Object.entries(i.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},a=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(r,((e,s)=>{t(e,s?a(s):s)})):this.getMemberships(r).then(a)}))}addMemberships(e,t){return r(this,void 0,void 0,(function*(){var s,n,i,r,a,o;if(this.logger.warn("PubNub","'addMemberships' is deprecated. Use 'pubnub.objects.setChannelMembers' or 'pubnub.objects.setMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add memberships with parameters:"}))),"spaceId"in e){const r=e,a={channel:null!==(s=r.spaceId)&&void 0!==s?s:r.channel,uuids:null!==(i=null===(n=r.users)||void 0===n?void 0:n.map((e=>"string"==typeof e?e:{id:e.userId,custom:e.custom})))&&void 0!==i?i:r.uuids,limit:0};return t?this.setChannelMembers(a,t):this.setChannelMembers(a)}const c=e,u={uuid:null!==(r=c.userId)&&void 0!==r?r:c.uuid,channels:null!==(o=null===(a=c.spaces)||void 0===a?void 0:a.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==o?o:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class Ks extends pe{constructor(e){super({method:ue.POST}),this.parameters=e}operation(){return K.PNCreateDataSyncUserOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.data?void 0===this.parameters.data.classVersion||null===this.parameters.data.classVersion?"Entity class version cannot be empty":void 0:"User data cannot be empty"}get headers(){var e;const t=null!==(e=super.headers)&&void 0!==e?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.user+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/users`}get body(){const{id:e,class:t,classLevel:s,data:n}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e?{id:e}:{}),void 0!==t?{entityClass:t}:{}),{entityClassVersion:n.classVersion}),void 0!==s?{entityClassLevel:s}:{}),void 0!==n.status?{status:n.status}:{}),void 0!==n.payload?{payload:n.payload}:{})})}}function Hs(e){return"string"==typeof e?e:Object.entries(null!=e?e:{}).map((([e,t])=>null!==t?`${e}:${t}`:e))}function Bs(e){const{add:t,replace:s,remove:n,move:i,copy:r,test:a}=e,o=[];if(t)for(const[e,s]of Object.entries(t))o.push({op:"add",path:e,value:s});if(s)for(const[e,t]of Object.entries(s))o.push({op:"replace",path:e,value:t});if(n)for(const e of n)o.push({op:"remove",path:e});if(i)for(const{from:e,path:t}of i)o.push({op:"move",from:e,path:t});if(r)for(const{from:e,path:t}of r)o.push({op:"copy",from:e,path:t});if(a)for(const[e,t]of Object.entries(a))o.push({op:"test",path:e,value:t});return o}class Ws extends pe{constructor(e){var t;super(),this.parameters=e,null!==(t=e.limit)&&void 0!==t||(e.limit=20)}operation(){return K.PNGetDataSyncUsersOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/users`}get queryParameters(){const{class:e,classVersion:t,classLevel:s,cursor:n,limit:i,filter:r,filterFast:a,sort:o}=this.parameters,c=Hs(o);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e?{entity_class:e}:{}),void 0!==t?{entity_class_version:`${t}`}:{}),s?{entity_class_level:s}:{}),n?{cursor:n}:{}),i?{limit:`${i}`}:{}),r?{filter:r}:{}),a?{filter_fast:a}:{}),c.length?{sort:c}:{})}}class Vs extends pe{constructor(e){super({method:ue.PUT}),this.parameters=e}operation(){return K.PNSetDataSyncUserOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.data?void 0===this.parameters.data.classVersion||null===this.parameters.data.classVersion?"Entity class version cannot be empty":void 0:"User data cannot be empty":"User id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.user+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/users/${C(t)}`}get body(){const{data:e}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({entityClassVersion:e.classVersion},void 0!==e.status?{status:e.status}:{}),void 0!==e.payload?{payload:e.payload}:{})})}}class zs extends pe{constructor(e){super({method:ue.DELETE}),this.parameters=e}operation(){return K.PNRemoveDataSyncUserOperation}validate(){if(!this.parameters.id)return"User id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return r(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/users/${C(t)}`}}class Js extends pe{constructor(e){super({method:ue.PATCH}),this.parameters=e}operation(){return K.PNUpdateDataSyncUserOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"User id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:i,test:r}=this.parameters,a=e&&Object.keys(e).length>0,o=t&&Object.keys(t).length>0,c=s&&s.length>0,u=n&&n.length>0,l=i&&i.length>0,h=r&&Object.keys(r).length>0;return a||o||c||u||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/users/${C(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:i,test:r}=this.parameters,a=Bs({add:e,replace:t,remove:s,move:n,copy:i,test:r});return JSON.stringify(a)}}class Xs extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNGetDataSyncUserOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"User id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/users/${C(t)}`}}class Qs extends pe{constructor(e){super({method:ue.POST}),this.parameters=e}operation(){return K.PNCreateDataSyncChannelOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.data?void 0===this.parameters.data.classVersion||null===this.parameters.data.classVersion?"Entity class version cannot be empty":void 0:"Channel data cannot be empty"}get headers(){var e;const t=null!==(e=super.headers)&&void 0!==e?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.channel+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/channels`}get body(){const{id:e,class:t,classLevel:s,data:n}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e?{id:e}:{}),void 0!==t?{entityClass:t}:{}),{entityClassVersion:n.classVersion}),void 0!==s?{entityClassLevel:s}:{}),void 0!==n.status?{status:n.status}:{}),void 0!==n.payload?{payload:n.payload}:{})})}}class Ys extends pe{constructor(e){var t;super(),this.parameters=e,null!==(t=e.limit)&&void 0!==t||(e.limit=20)}operation(){return K.PNGetDataSyncChannelsOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{class:e,classVersion:t,classLevel:s,cursor:n,limit:i,filter:r,filterFast:a,sort:o}=this.parameters,c=Hs(o);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e?{entity_class:e}:{}),void 0!==t?{entity_class_version:`${t}`}:{}),s?{entity_class_level:s}:{}),n?{cursor:n}:{}),i?{limit:`${i}`}:{}),r?{filter:r}:{}),a?{filter_fast:a}:{}),c.length?{sort:c}:{})}}class Zs extends pe{constructor(e){super({method:ue.PUT}),this.parameters=e}operation(){return K.PNSetDataSyncChannelOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.data?void 0===this.parameters.data.classVersion||null===this.parameters.data.classVersion?"Entity class version cannot be empty":void 0:"Channel data cannot be empty":"Channel id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.channel+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/channels/${C(t)}`}get body(){const{data:e}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({entityClassVersion:e.classVersion},void 0!==e.status?{status:e.status}:{}),void 0!==e.payload?{payload:e.payload}:{})})}}class en extends pe{constructor(e){super({method:ue.DELETE}),this.parameters=e}operation(){return K.PNRemoveDataSyncChannelOperation}validate(){if(!this.parameters.id)return"Channel id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return r(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/channels/${C(t)}`}}class tn extends pe{constructor(e){super({method:ue.PATCH}),this.parameters=e}operation(){return K.PNUpdateDataSyncChannelOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Channel id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:i,test:r}=this.parameters,a=e&&Object.keys(e).length>0,o=t&&Object.keys(t).length>0,c=s&&s.length>0,u=n&&n.length>0,l=i&&i.length>0,h=r&&Object.keys(r).length>0;return a||o||c||u||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/channels/${C(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:i,test:r}=this.parameters,a=Bs({add:e,replace:t,remove:s,move:n,copy:i,test:r});return JSON.stringify(a)}}class sn extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNGetDataSyncChannelOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Channel id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/channels/${C(t)}`}}class nn extends pe{constructor(e){super({method:ue.POST}),this.parameters=e}operation(){return K.PNCreateDataSyncMembershipOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.userId?this.parameters.channelId?this.parameters.data?this.parameters.data.classVersion?void 0:"Membership class version cannot be empty":"Membership data cannot be empty":"Channel id cannot be empty":"User id cannot be empty"}get headers(){var e;const t=null!==(e=super.headers)&&void 0!==e?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.membership+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships`}get body(){const{id:e,userId:t,channelId:s,data:n}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e?{id:e}:{}),{userId:t,channelId:s,relationshipClassVersion:n.classVersion}),void 0!==n.status?{status:n.status}:{}),void 0!==n.payload?{payload:n.payload}:{})})}}class rn extends pe{constructor(e){var t;super(),this.parameters=e,null!==(t=e.limit)&&void 0!==t||(e.limit=20)}operation(){return K.PNGetDataSyncMembershipsOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/memberships`}get queryParameters(){const{userId:e,channelId:t,classVersion:s,cursor:n,limit:i,filter:r,filterFast:a,sort:o}=this.parameters,c=Hs(o);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e?{user_id:e}:{}),t?{channel_id:t}:{}),void 0!==s?{relationship_class_version:`${s}`}:{}),n?{cursor:n}:{}),i?{limit:`${i}`}:{}),r?{filter:r}:{}),a?{filter_fast:a}:{}),c.length?{sort:c}:{})}}class an extends pe{constructor(e){super({method:ue.PUT}),this.parameters=e}operation(){return K.PNSetDataSyncMembershipOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.userId?this.parameters.channelId?this.parameters.data?this.parameters.data.classVersion?void 0:"Membership class version cannot be empty":"Membership data cannot be empty":"Channel id cannot be empty":"User id cannot be empty":"Membership id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.membership+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships/${C(t)}`}get body(){const{userId:e,channelId:t,data:s}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({userId:e,channelId:t,relationshipClassVersion:s.classVersion},void 0!==s.status?{status:s.status}:{}),void 0!==s.payload?{payload:s.payload}:{})})}}class on extends pe{constructor(e){super({method:ue.DELETE}),this.parameters=e}operation(){return K.PNRemoveDataSyncMembershipOperation}validate(){if(!this.parameters.id)return"Membership id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return r(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships/${C(t)}`}}class cn extends pe{constructor(e){super({method:ue.PATCH}),this.parameters=e}operation(){return K.PNUpdateDataSyncMembershipOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Membership id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:i,test:r}=this.parameters,a=e&&Object.keys(e).length>0,o=t&&Object.keys(t).length>0,c=s&&s.length>0,u=n&&n.length>0,l=i&&i.length>0,h=r&&Object.keys(r).length>0;return a||o||c||u||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships/${C(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:i,test:r}=this.parameters,a=Bs({add:e,replace:t,remove:s,move:n,copy:i,test:r});return JSON.stringify(a)}}class un extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNGetDataSyncMembershipOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Membership id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships/${C(t)}`}}class ln extends pe{constructor(e){super({method:ue.POST}),this.parameters=e}operation(){return K.PNCreateDataSyncRelationshipOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.entityAId?this.parameters.entityBId?this.parameters.class?this.parameters.data?this.parameters.data.classVersion?void 0:"Relationship class version cannot be empty":"Relationship data cannot be empty":"Relationship class cannot be empty":"Entity B id cannot be empty":"Entity A id cannot be empty"}get headers(){var e;const t=null!==(e=super.headers)&&void 0!==e?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.relationship+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships`}get body(){const{id:e,class:t,entityAId:s,entityBId:n,data:i}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e?{id:e}:{}),{entityAId:s,entityBId:n,relationshipClass:t,relationshipClassVersion:i.classVersion}),void 0!==i.status?{status:i.status}:{}),void 0!==i.payload?{payload:i.payload}:{})})}}class hn extends pe{constructor(e){var t;super(),this.parameters=e,null!==(t=e.limit)&&void 0!==t||(e.limit=20)}operation(){return K.PNGetDataSyncRelationshipsOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.class)return"Relationship class cannot be empty"}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/relationships`}get queryParameters(){const{class:e,classVersion:t,entityAId:s,entityBId:n,cursor:i,limit:r,filter:a,filterFast:o,sort:c}=this.parameters,u=Hs(c);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({relationship_class:e},void 0!==t?{relationship_class_version:`${t}`}:{}),s?{entity_a_id:s}:{}),n?{entity_b_id:n}:{}),i?{cursor:i}:{}),r?{limit:`${r}`}:{}),a?{filter:a}:{}),o?{filter_fast:o}:{}),u.length?{sort:u}:{})}}class dn extends pe{constructor(e){super({method:ue.PUT}),this.parameters=e}operation(){return K.PNSetDataSyncRelationshipOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.entityAId?this.parameters.entityBId?this.parameters.data?this.parameters.data.classVersion?void 0:"Relationship class version cannot be empty":"Relationship data cannot be empty":"Entity B id cannot be empty":"Entity A id cannot be empty":"Relationship id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.relationship+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships/${C(t)}`}get body(){const{entityAId:e,entityBId:t,data:s}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({entityAId:e,entityBId:t,relationshipClassVersion:s.classVersion},void 0!==s.status?{status:s.status}:{}),void 0!==s.payload?{payload:s.payload}:{})})}}class pn extends pe{constructor(e){super({method:ue.DELETE}),this.parameters=e}operation(){return K.PNRemoveDataSyncRelationshipOperation}validate(){if(!this.parameters.id)return"Relationship id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return r(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships/${C(t)}`}}class gn extends pe{constructor(e){super({method:ue.PATCH}),this.parameters=e}operation(){return K.PNUpdateDataSyncRelationshipOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Relationship id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:i,test:r}=this.parameters,a=e&&Object.keys(e).length>0,o=t&&Object.keys(t).length>0,c=s&&s.length>0,u=n&&n.length>0,l=i&&i.length>0,h=r&&Object.keys(r).length>0;return a||o||c||u||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships/${C(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:i,test:r}=this.parameters,a=Bs({add:e,replace:t,remove:s,move:n,copy:i,test:r});return JSON.stringify(a)}}class bn extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNGetDataSyncRelationshipOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Relationship id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships/${C(t)}`}}class yn extends pe{constructor(e){super({method:ue.POST}),this.parameters=e}operation(){return K.PNCreateDataSyncEntityOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.class?this.parameters.data?void 0===this.parameters.data.classVersion||null===this.parameters.data.classVersion?"Entity class version cannot be empty":void 0:"Entity data cannot be empty":"Entity class cannot be empty"}get headers(){var e;const t=null!==(e=super.headers)&&void 0!==e?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.entity+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/entities`}get body(){const{id:e,class:t,classLevel:s,data:n}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e?{id:e}:{}),{entityClass:t,entityClassVersion:n.classVersion}),void 0!==s?{entityClassLevel:s}:{}),void 0!==n.status?{status:n.status}:{}),void 0!==n.payload?{payload:n.payload}:{})})}}class mn extends pe{constructor(e){var t;super(),this.parameters=e,null!==(t=e.limit)&&void 0!==t||(e.limit=20)}operation(){return K.PNGetDataSyncEntitiesOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.class)return"Entity class cannot be empty"}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/entities`}get queryParameters(){const{class:e,classVersion:t,classLevel:s,cursor:n,limit:i,filter:r,filterFast:a,sort:o}=this.parameters,c=Hs(o);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({entity_class:e},void 0!==t?{entity_class_version:`${t}`}:{}),s?{entity_class_level:s}:{}),n?{cursor:n}:{}),i?{limit:`${i}`}:{}),r?{filter:r}:{}),a?{filter_fast:a}:{}),c.length?{sort:c}:{})}}class fn extends pe{constructor(e){super({method:ue.PUT}),this.parameters=e}operation(){return K.PNSetDataSyncEntityOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.data?void 0===this.parameters.data.classVersion||null===this.parameters.data.classVersion?"Entity class version cannot be empty":void 0:"Entity data cannot be empty":"Entity id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.entity+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/entities/${C(t)}`}get body(){const{data:e}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({entityClassVersion:e.classVersion},void 0!==e.status?{status:e.status}:{}),void 0!==e.payload?{payload:e.payload}:{})})}}class vn extends pe{constructor(e){super({method:ue.DELETE}),this.parameters=e}operation(){return K.PNRemoveDataSyncEntityOperation}validate(){if(!this.parameters.id)return"Entity id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return r(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/entities/${C(t)}`}}class On extends pe{constructor(e){super({method:ue.PATCH}),this.parameters=e}operation(){return K.PNUpdateDataSyncEntityOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Entity id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:i,test:r}=this.parameters,a=e&&Object.keys(e).length>0,o=t&&Object.keys(t).length>0,c=s&&s.length>0,u=n&&n.length>0,l=i&&i.length>0,h=r&&Object.keys(r).length>0;return a||o||c||u||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/entities/${C(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:i,test:r}=this.parameters,a=Bs({add:e,replace:t,remove:s,move:n,copy:i,test:r});return JSON.stringify(a)}}class Sn extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNGetDataSyncEntityOperation}parse(e){return r(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Entity id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/entities/${C(t)}`}}class jn{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}get logger(){return this.configuration.logger()}createEntity(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Entity with parameters:"})));const s=new yn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getEntity(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Entity with parameters:"})));const s=new Sn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getEntities(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Entities with parameters:"})));const s=new mn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setEntity(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Entity with parameters:"})));const s=new fn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateEntity(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Entity with parameters:"})));const s=new On(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeEntity(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Entity with parameters:"})));const s=new vn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}createRelationship(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Relationship with parameters:"})));const s=new ln(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getRelationship(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Relationship with parameters:"})));const s=new bn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getRelationships(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Relationships with parameters:"})));const s=new hn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setRelationship(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Relationship with parameters:"})));const s=new dn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateRelationship(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Relationship with parameters:"})));const s=new gn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeRelationship(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Relationship with parameters:"})));const s=new pn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}createUser(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create User with parameters:"})));const s=new Ks(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getUser(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get User with parameters:"})));const s=new Xs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getUsers(e,t){return r(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},s),details:"Get Users with parameters:"})));const n=new Ws(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setUser(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set User with parameters:"})));const s=new Vs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateUser(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update User with parameters:"})));const s=new Js(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeUser(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove User with parameters:"})));const s=new zs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}createChannel(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Channel with parameters:"})));const s=new Qs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannel(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Channel with parameters:"})));const s=new sn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannels(e,t){return r(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},s),details:"Get Channels with parameters:"})));const n=new Ys(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setChannel(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Channel with parameters:"})));const s=new Zs(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateChannel(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Channel with parameters:"})));const s=new tn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannel(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Channel with parameters:"})));const s=new en(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}createMembership(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Membership with parameters:"})));const s=new nn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMembership(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Membership with parameters:"})));const s=new un(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMemberships(e,t){return r(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},s),details:"Get Memberships with parameters:"})));const n=new rn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setMembership(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Membership with parameters:"})));const s=new an(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateMembership(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Membership with parameters:"})));const s=new cn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeMembership(e,t){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Membership with parameters:"})));const s=new on(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class wn extends pe{constructor(){super()}operation(){return K.PNTimeOperation}parse(e){return r(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[0]}}))}get path(){return"/time/0"}}class kn extends pe{constructor(e){super(),this.parameters=e}operation(){return K.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return r(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:i,PubNubFile:r}=this.parameters,a=e.headers["content-type"];let o,c=e.body;return r.supportsEncryptFile&&(t||s)&&(t&&n?c=yield n.decrypt(t,c):!t&&s&&(o=yield s.decryptFile(r.create({data:c,name:i,mimeType:a}),r))),o||r.create({data:c,name:i,mimeType:a})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${C(t)}/files/${C(s)}/${C(n)}`}}class Cn{static notificationPayload(e,t){return new Pe(e,t)}static generateUUID(){return ie.createUUID()}constructor(e){if(this.eventHandleCapable={},this.entities={},this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this.logger.debug("PubNub",(()=>({messageType:"object",message:e.configuration,details:"Create with configuration:",ignoredKeys:(e,t)=>"function"==typeof t[e]||e.startsWith("_")||"keySet"===e||k(e)}))),this._objects=new Ls(this._configuration,this.sendRequest.bind(this)),this._dataSync=new jn(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new ws(this._configuration.logger(),this._configuration.keySet,this.sendRequest.bind(this)),this._push=new Ts(this._configuration.logger(),this._configuration.keySet,this.sendRequest.bind(this)),this.eventDispatcher=new ve,this._configuration.enableEventEngine){this.logger.debug("PubNub","Using new subscription loop management.");let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new nt({heartbeat:(e,t)=>(this.logger.trace("PresenceEventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Heartbeat with parameters:"}))),this.heartbeat(e,t)),leave:e=>{this.logger.trace("PresenceEventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),this.makeUnsubscribe(e,(()=>{}))},heartbeatDelay:()=>{let t=()=>{};const s=new Promise(((s,n)=>{if(e=this._configuration.getHeartbeatInterval(),e){const i=setTimeout((()=>{s()}),1e3*e);t=()=>{clearTimeout(i),n(new d("Heartbeat interval has been cancelled."))}}else n(new d("Heartbeat interval has been reset."))}));return{cancelDelay:t,promise:s}},emitStatus:e=>this.emitStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new Ct({handshake:e=>(this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Handshake with parameters:",ignoredKeys:["abortSignal","crypto","timeout","keySet","getFileUrl"]}))),this.subscribeHandshake(e)),receiveMessages:e=>(this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Receive messages with parameters:",ignoredKeys:["abortSignal","crypto","timeout","keySet","getFileUrl"]}))),this.subscribeReceiveMessages(e)),join:e=>{var t,s;this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Join with parameters:"}))),e&&0===(null!==(t=e.channels)&&void 0!==t?t:[]).length&&0===(null!==(s=e.groups)&&void 0!==s?s:[]).length?this.logger.trace("EventEngine","Ignoring 'join' announcement request."):this.join(e)},leave:e=>{var t,s;this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),e&&0===(null!==(t=e.channels)&&void 0!==t?t:[]).length&&0===(null!==(s=e.groups)&&void 0!==s?s:[]).length?this.logger.trace("EventEngine","Ignoring 'leave' announcement request."):this.leave(e)},leaveAll:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave all with parameters:"}))),this.leaveAll(e)},presenceReconnect:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Reconnect with parameters:"}))),this.presenceReconnect(e)},presenceDisconnect:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Disconnect with parameters:"}))),this.presenceDisconnect(e)},presenceState:this.presenceState,config:this._configuration,emitMessages:(e,t)=>{try{this.logger.debug("EventEngine",(()=>({messageType:"object",message:t.map((e=>{const t=e.type===ge.Message||e.type===ge.Signal?R(e.data.message):void 0;return t?{type:e.type,data:Object.assign(Object.assign({},e.data),{pn_mfp:t})}:e})),details:"Received events:"}))),t.forEach((t=>this.emitEvent(e,t)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.emitStatus(t)}},emitStatus:e=>this.emitStatus(e)})}else this.logger.debug("PubNub","Using legacy subscription loop management."),this.subscriptionManager=new je(this._configuration,((e,t)=>{try{this.emitEvent(e,t)}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.emitStatus(t)}}),this.emitStatus.bind(this),((e,t)=>{this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},e),details:"Subscribe with parameters:",ignoredKeys:["crypto","timeout","keySet","getFileUrl"]}))),this.makeSubscribe(e,t)}),((e,t)=>(this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},e),details:"Heartbeat with parameters:",ignoredKeys:["crypto","timeout","keySet","getFileUrl"]}))),this.heartbeat(e,t))),((e,t)=>{this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),this.makeUnsubscribe(e,t)}),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this.logger.debug("PubNub","Auth key updated."),this._configuration.setAuthKey(e),this.onAuthenticationChange&&this.onAuthenticationChange(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length){const e=new Error("Missing or invalid userId parameter. Provide a valid string userId");throw this.logger.error("PubNub",(()=>({messageType:"error",message:e}))),e}this.logger.debug("PubNub",`Set user ID: ${e}`),this._configuration.userId=e,this.onUserIdChange&&this.onUserIdChange(this._configuration.userId)}getUserId(){return this._configuration.userId}setUserId(e){this.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this.logger.debug("PubNub",`Set filter expression: ${e}`),this._configuration.setFilterExpression(e)}setFilterExpression(e){this.logger.debug("PubNub",`Set filter expression: ${e}`),this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.logger.debug("PubNub","Cipher key updated."),this.cipherKey=e}set heartbeatInterval(e){var t;this.logger.debug("PubNub",`Set heartbeat interval: ${e}`),this._configuration.setHeartbeatInterval(e),this.onHeartbeatIntervalChange&&this.onHeartbeatIntervalChange(null!==(t=this._configuration.getHeartbeatInterval())&&void 0!==t?t:0)}setHeartbeatInterval(e){this.heartbeatInterval=e}get logger(){return this._configuration.logger()}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this.logger.debug("PubNub",`Add '${e}' 'pnsdk' suffix: ${t}`),this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.logger.warn("PubNub","'setUserId` is deprecated, please use 'setUserId' or 'userId' setter instead."),this.logger.debug("PubNub",`Set UUID: ${e}`),this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){let t=this.entities[`${e}_ch`];return t||(t=this.entities[`${e}_ch`]=new ms(e,this)),t}channelGroup(e){let t=this.entities[`${e}_chg`];return t||(t=this.entities[`${e}_chg`]=new bs(e,this)),t}channelMetadata(e){let t=this.entities[`${e}_chm`];return t||(t=this.entities[`${e}_chm`]=new ps(e,this)),t}userMetadata(e){let t=this.entities[`${e}_um`];return t||(t=this.entities[`${e}_um`]=new ys(e,this)),t}dataSyncUser(e){let t=this.entities[`${e}_dsu`];return t||(t=this.entities[`${e}_dsu`]=new gs(e,this)),t}dataSyncChannel(e){let t=this.entities[`${e}_dsc`];return t||(t=this.entities[`${e}_dsc`]=new hs(e,this)),t}dataSyncMembership(e){let t=this.entities[`${e}_dsm`];return t||(t=this.entities[`${e}_dsm`]=new ls(e,this)),t}dataSyncEntity(e){let t=this.entities[`${e}_dse`];return t||(t=this.entities[`${e}_dse`]=new ds(e,this)),t}dataSyncRelationship(e){let t=this.entities[`${e}_dsr`];return t||(t=this.entities[`${e}_dsr`]=new us(e,this)),t}subscriptionSet(e){var t,s;{const n=[];return null===(t=e.channels)||void 0===t||t.forEach((e=>n.push(this.channel(e)))),null===(s=e.channelGroups)||void 0===s||s.forEach((e=>n.push(this.channelGroup(e)))),new Ut({client:this,entities:n,options:e.subscriptionOptions})}}sendRequest(e,t){return r(this,void 0,void 0,(function*(){const s=e.validate();if(s){const e=(n=s,p(Object.assign({message:n},{}),h.PNValidationErrorCategory));if(this.logger.error("PubNub",(()=>({messageType:"error",message:e}))),t)return t(e,null);throw new d("Validation failed, check status for details",e)}var n;const i=e.request(),r=e.operation();i.formData&&i.formData.length>0||r===K.PNDownloadFileOperation?i.timeout=this._configuration.getFileTimeout():r===K.PNSubscribeOperation||r===K.PNReceiveMessagesOperation?i.timeout=this._configuration.getSubscribeTimeout():i.timeout=this._configuration.getTransactionTimeout();const a={error:!1,operation:r,category:h.PNAcknowledgmentCategory,statusCode:0},[o,c]=this.transport.makeSendable(i);return e.cancellationController=c||null,o.then((t=>{if(a.statusCode=t.status,200!==t.status&&204!==t.status){const e=Cn.decoder.decode(t.body),s=t.headers["content-type"];if(s||-1!==s.indexOf("javascript")||-1!==s.indexOf("json")){const t=JSON.parse(e);"object"==typeof t&&"error"in t&&t.error&&"object"==typeof t.error&&(a.errorData=t.error)}else a.responseText=e}return e.parse(t)})).then((e=>t?t(a,e):e)).catch((e=>{const s=e instanceof G?e:G.create(e);if(t)return s.category!==h.PNCancelledCategory&&this.logger.error("PubNub",(()=>({messageType:"error",message:s.toPubNubError(r,"REST API request processing error, check status for details")}))),t(s.toStatus(r),null);const n=s.toPubNubError(r,"REST API request processing error, check status for details");throw s.category!==h.PNCancelledCategory&&this.logger.error("PubNub",(()=>({messageType:"error",message:n}))),n}))}))}destroy(e=!1){this.logger.info("PubNub","Destroying PubNub client."),this._globalSubscriptionSet&&(this._globalSubscriptionSet.invalidate(!0),this._globalSubscriptionSet=void 0),Object.values(this.eventHandleCapable).forEach((e=>e.invalidate(!0))),this.eventHandleCapable={},this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.unsubscribeAll(e),this.presenceEventEngine&&this.presenceEventEngine.leaveAll(e)}stop(){this.logger.warn("PubNub","'stop' is deprecated, please use 'destroy' instead."),this.destroy()}publish(e,t){return r(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Publish with parameters:"})));const s=!1===e.replicate&&!1===e.storeInHistory,n=new Pt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),i=e=>{e&&this.logger.debug("PubNub",`${s?"Fire":"Publish"} success with timetoken: ${e.timetoken}`)};return t?this.sendRequest(n,((e,s)=>{i(s),t(e,s)})):this.sendRequest(n).then((e=>(i(e),e)))}}))}signal(e,t){return r(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Signal with parameters:"})));const s=new Nt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Publish success with timetoken: ${e.timetoken}`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}fire(e,t){return r(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fire with parameters:"}))),null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}get globalSubscriptionSet(){return this._globalSubscriptionSet||(this._globalSubscriptionSet=this.subscriptionSet({})),this._globalSubscriptionSet}get subscriptionTimetoken(){return this.subscriptionManager?this.subscriptionManager.subscriptionTimetoken:this.eventEngine?this.eventEngine.subscriptionTimetoken:void 0}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}registerEventHandleCapable(e,t,s){{let n;this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign(Object.assign({subscription:e},t?{cursor:t}:[]),s?{subscriptions:s}:{}),details:"Register event handle capable:"}))),this.eventHandleCapable[e.state.id]||(this.eventHandleCapable[e.state.id]=e),s&&0!==s.length?(n=new It({}),s.forEach((e=>n.add(e.subscriptionInput(!1))))):n=e.subscriptionInput(!1);const i={};i.channels=n.channels,i.channelGroups=n.channelGroups,t&&(i.timetoken=t.timetoken),this.subscriptionManager?this.subscriptionManager.subscribe(i):this.eventEngine&&this.eventEngine.subscribe(i)}}unregisterEventHandleCapable(e,t){{if(!this.eventHandleCapable[e.state.id])return;const s=[];this.logger.trace("PubNub",(()=>({messageType:"object",message:{subscription:e,subscriptions:t},details:"Unregister event handle capable:"})));let n,i=!t||0===t.length;if(!i&&e instanceof Ut&&e.subscriptions.length===(null==t?void 0:t.length)&&(i=e.subscriptions.every((e=>t.includes(e)))),i&&delete this.eventHandleCapable[e.state.id],t&&0!==t.length?(n=new It({}),t.forEach((e=>{const t=e.subscriptionInput(!0);t.isEmpty?s.push(e):n.add(t)}))):(n=e.subscriptionInput(!0),n.isEmpty&&s.push(e)),s.length>0&&this.logger.trace("PubNub",(()=>{const e=[];return s[0]instanceof Ut?s[0].subscriptions.forEach((t=>e.push(t.state.entity))):s.forEach((t=>e.push(t.state.entity))),{messageType:"object",message:{entities:e},details:"Can't unregister event handle capable because entities still in use:"}})),n.isEmpty)return;{const e=[],t=[];if(Object.values(this.eventHandleCapable).forEach((s=>{const i=s.subscriptionInput(!1),r=i.channelGroups,a=i.channels;e.push(...n.channelGroups.filter((e=>r.includes(e)))),t.push(...n.channels.filter((e=>a.includes(e))))})),(t.length>0||e.length>0)&&(this.logger.trace("PubNub",(()=>{const s=[],i=n=>{const i=n.subscriptionNames(!0),r=n.subscriptionType===_t.Channel?t:e;i.some((e=>r.includes(e)))&&s.push(n)};Object.values(this.eventHandleCapable).forEach((e=>{e instanceof Ut?e.subscriptions.forEach((e=>{i(e.state.entity)})):e instanceof $t&&i(e.state.entity)}));let r="Some entities still in use:";return t.length+e.length===n.length&&(r="Can't unregister event handle capable because entities still in use:"),{messageType:"object",message:{entities:s},details:r}})),n.remove(new It({channels:t,channelGroups:e})),n.isEmpty))return}const r={};r.channels=n.channels,r.channelGroups=n.channelGroups,this.subscriptionManager?this.subscriptionManager.unsubscribe(r):this.eventEngine&&this.eventEngine.unsubscribe(r)}}subscribe(e){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Subscribe with parameters:"})));const t=this.subscriptionSet(Object.assign(Object.assign({},e),{subscriptionOptions:{receivePresenceEvents:e.withPresence}}));this.globalSubscriptionSet.addSubscriptionSet(t),t.dispose();const s="number"==typeof e.timetoken?`${e.timetoken}`:e.timetoken;this.globalSubscriptionSet.subscribe({timetoken:s})}}makeSubscribe(e,t){{this._configuration.isSharedWorkerEnabled()||(e.onDemand=!1);const s=new fe(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((e,n)=>{var i;this.subscriptionManager&&(null===(i=this.subscriptionManager.abort)||void 0===i?void 0:i.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,n)})),this.subscriptionManager){const e=()=>s.abort("Cancel long-poll subscribe request");e.identifier=s.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){{if(this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Unsubscribe with parameters:"}))),!this._globalSubscriptionSet)return void this.logger.debug("PubNub","There are no active subscriptions. Ignore.");const t=this.globalSubscriptionSet.subscriptions.filter((t=>{var s,n;const i=t.subscriptionInput(!1);if(i.isEmpty)return!1;for(const t of null!==(s=e.channels)&&void 0!==s?s:[])if(i.contains(t))return!0;for(const t of null!==(n=e.channelGroups)&&void 0!==n?n:[])if(i.contains(t))return!0}));t.length>0&&this.globalSubscriptionSet.removeSubscriptions(t)}}makeUnsubscribe(e,t){{let{channels:s,channelGroups:n}=e;if(this._configuration.getKeepPresenceChannelsInPresenceRequests()||(n&&(n=n.filter((e=>!e.endsWith("-pnpres")))),s&&(s=s.filter((e=>!e.endsWith("-pnpres"))))),0===(null!=n?n:[]).length&&0===(null!=s?s:[]).length)return t({error:!1,operation:K.PNUnsubscribeOperation,category:h.PNAcknowledgmentCategory,statusCode:200});this.sendRequest(new Gt({channels:s,channelGroups:n,keySet:this._configuration.keySet}),t)}}unsubscribeAll(){this.logger.debug("PubNub","Unsubscribe all channels and groups"),this._globalSubscriptionSet&&this._globalSubscriptionSet.invalidate(!1),Object.values(this.eventHandleCapable).forEach((e=>e.invalidate(!1))),this.eventHandleCapable={},this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(e=!1){this.logger.debug("PubNub",`Disconnect (while offline? ${e?"yes":"no"})`),this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect(e)}reconnect(e){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Reconnect with parameters:"}))),this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return r(this,void 0,void 0,(function*(){{this._configuration.isSharedWorkerEnabled()||(e.onDemand=!1),e.heartbeat||(e.heartbeat=this._configuration.getPresenceTimeout());const t=new Tt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort("Cancel subscribe handshake request")}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}}))}subscribeReceiveMessages(e){return r(this,void 0,void 0,(function*(){{this._configuration.isSharedWorkerEnabled()||(e.onDemand=!1),e.heartbeat||(e.heartbeat=this._configuration.getPresenceTimeout());const t=new Et(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort("Cancel long-poll subscribe request")}));return this.sendRequest(t).then((e=>(s(),e)))}}))}getMessageActions(e,t){return r(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get message actions with parameters:"})));const s=new Jt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Get message actions success. Received ${e.data.length} message actions.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}addMessageAction(e,t){return r(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add message action with parameters:"})));const s=new Xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Message action add success. Message action added with timetoken: ${e.data.actionTimetoken}`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}removeMessageAction(e,t){return r(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove message action with parameters:"})));const s=new Qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Message action remove success. Removed message action with ${e.actionTimetoken} timetoken.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}fetchMessages(e,t){return r(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch messages with parameters:"})));const s=new zt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e=>{if(!e)return;const t=Object.values(e.channels).reduce(((e,t)=>e+t.length),0);this.logger.debug("PubNub",`Fetch messages success. Received ${t} messages.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}deleteMessages(e,t){return r(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Delete messages with parameters:"})));const s=new Ht(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub","Delete messages success.")};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}messageCounts(e,t){return r(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get messages count with parameters:"})));const s=new Bt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=t=>{if(!t)return;const s=Object.values(t.channels).reduce(((e,t)=>e+t),0);this.logger.debug("PubNub",`Get messages count success. There are ${s} messages since provided reference timetoken${e.channelTimetokens?e.channelTimetokens.join(","):""}.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}history(e,t){return r(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch history with parameters:"})));const s=new Wt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),n=e=>{e&&this.logger.debug("PubNub",`Fetch history success. Received ${e.messages.length} messages.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}hereNow(e,t){return r(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Here now with parameters:"})));const s=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Here now success. There are ${e.totalOccupancy} participants in ${e.totalChannels} channels.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}whereNow(e,t){return r(this,void 0,void 0,(function*(){var s;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Where now with parameters:"})));const n=new Lt({uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet}),i=e=>{e&&this.logger.debug("PubNub",`Where now success. Currently present in ${e.channels.length} channels.`)};return t?this.sendRequest(n,((e,s)=>{i(s),t(e,s)})):this.sendRequest(n).then((e=>(i(e),e)))}}))}getState(e,t){return r(this,void 0,void 0,(function*(){var s;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get presence state with parameters:"})));const n=new Ft(Object.assign(Object.assign({},e),{uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Get presence state success. Received presence state for ${Object.keys(e.channels).length} channels.`)};return t?this.sendRequest(n,((e,s)=>{i(s),t(e,s)})):this.sendRequest(n).then((e=>(i(e),e)))}}))}setState(e,t){return r(this,void 0,void 0,(function*(){var s,n;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set presence state with parameters:"})));const{keySet:i,userId:r}=this._configuration,a=this._configuration.getPresenceTimeout();let o;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(s=e.channels)||void 0===s||s.forEach((s=>t[s]=e.state)),"channelGroups"in e&&(null===(n=e.channelGroups)||void 0===n||n.forEach((s=>t[s]=e.state))),this.onPresenceStateChange&&this.onPresenceStateChange(this.presenceState)}o="withHeartbeat"in e&&e.withHeartbeat?new qt(Object.assign(Object.assign({},e),{keySet:i,heartbeat:a})):new xt(Object.assign(Object.assign({},e),{keySet:i,uuid:r}));const c=e=>{e&&this.logger.debug("PubNub","Set presence state success."+(o instanceof qt?" Presence state has been set using heartbeat endpoint.":""))};return this.subscriptionManager&&(this.subscriptionManager.setState(e),this.onPresenceStateChange&&this.onPresenceStateChange(this.subscriptionManager.presenceState)),t?this.sendRequest(o,((e,s)=>{c(s),t(e,s)})):this.sendRequest(o).then((e=>(c(e),e)))}}))}presence(e){var t;this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Change presence with parameters:"}))),null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return r(this,void 0,void 0,(function*(){var s;{this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Heartbeat with parameters:"})));let{channels:n,channelGroups:i}=e;if(i&&(i=i.filter((e=>!e.endsWith("-pnpres")))),n&&(n=n.filter((e=>!e.endsWith("-pnpres")))),0===(null!=i?i:[]).length&&0===(null!=n?n:[]).length){const e={error:!1,operation:K.PNHeartbeatOperation,category:h.PNAcknowledgmentCategory,statusCode:200};return this.logger.trace("PubNub","There are no active subscriptions. Ignore."),t?t(e,{}):Promise.resolve(e)}const r=new qt(Object.assign(Object.assign({},e),{channels:[...new Set(n)],channelGroups:[...new Set(i)],keySet:this._configuration.keySet})),a=e=>{e&&this.logger.trace("PubNub","Heartbeat success.")},o=null===(s=e.abortSignal)||void 0===s?void 0:s.subscribe((e=>{r.abort("Cancel long-poll subscribe request")}));return t?this.sendRequest(r,((e,s)=>{a(s),o&&o(),t(e,s)})):this.sendRequest(r).then((e=>(a(e),o&&o(),e)))}}))}join(e){var t,s;this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Join with parameters:"}))),e&&0===(null!==(t=e.channels)&&void 0!==t?t:[]).length&&0===(null!==(s=e.groups)&&void 0!==s?s:[]).length?this.logger.trace("PubNub","Ignoring 'join' announcement request."):this.presenceEventEngine?this.presenceEventEngine.join(e):this.heartbeat(Object.assign(Object.assign({channels:e.channels,channelGroups:e.groups},this._configuration.maintainPresenceState&&this.presenceState&&Object.keys(this.presenceState).length>0&&{state:this.presenceState}),{heartbeat:this._configuration.getPresenceTimeout()}),(()=>{}))}presenceReconnect(e){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Presence reconnect with parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.reconnect():this.heartbeat(Object.assign(Object.assign({channels:e.channels,channelGroups:e.groups},this._configuration.maintainPresenceState&&{state:this.presenceState}),{heartbeat:this._configuration.getPresenceTimeout()}),(()=>{}))}leave(e){var t,s,n;this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),e&&0===(null!==(t=e.channels)&&void 0!==t?t:[]).length&&0===(null!==(s=e.groups)&&void 0!==s?s:[]).length?this.logger.trace("PubNub","Ignoring 'leave' announcement request."):this.presenceEventEngine?null===(n=this.presenceEventEngine)||void 0===n||n.leave(e):this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}leaveAll(e={}){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave all with parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.leaveAll(!!e.isOffline):e.isOffline||this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}presenceDisconnect(e){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Presence disconnect parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.disconnect(!!e.isOffline):e.isOffline||this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}grantToken(e,t){return r(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return r(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e),this.onAuthenticationChange&&this.onAuthenticationChange(e)}setToken(e){this.logger.debug("PubNub","Access token updated."),this.token=e}parseToken(e){return this.logger.debug("PubNub","Parse access token."),this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return r(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return r(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}get dataSync(){return this._dataSync}fetchUsers(e,t){return r(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchUsers' is deprecated. Use 'pubnub.objects.getAllUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Fetch all User objects with parameters:"}))),this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return r(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchUser' is deprecated. Use 'pubnub.objects.getUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.userId},details:`Fetch${e&&"function"!=typeof e?"":" current"} User object with parameters:`}))),this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return r(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'createUser' is deprecated. Use 'pubnub.objects.setUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create User object with parameters:"}))),this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return r(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'updateUser' is deprecated. Use 'pubnub.objects.setUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update User object with parameters:"}))),this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return r(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'removeUser' is deprecated. Use 'pubnub.objects.removeUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.userId},details:`Remove${e&&"function"!=typeof e?"":" current"} User object with parameters:`}))),this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return r(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchSpaces' is deprecated. Use 'pubnub.objects.getAllChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Fetch all Space objects with parameters:"}))),this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return r(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchSpace' is deprecated. Use 'pubnub.objects.getChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch Space object with parameters:"}))),this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return r(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'createSpace' is deprecated. Use 'pubnub.objects.setChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Space object with parameters:"}))),this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return r(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'updateSpace' is deprecated. Use 'pubnub.objects.setChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Space object with parameters:"}))),this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return r(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'removeSpace' is deprecated. Use 'pubnub.objects.removeChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Space object with parameters:"}))),this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return r(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return r(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return r(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'addMemberships' is deprecated. Use 'pubnub.objects.setChannelMembers' or 'pubnub.objects.setMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update memberships with parameters:"}))),this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return r(this,void 0,void 0,(function*(){var s,n,i;{if(this.logger.warn("PubNub","'removeMemberships' is deprecated. Use 'pubnub.objects.removeMemberships' or 'pubnub.objects.removeChannelMembers' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove memberships with parameters:"}))),"spaceId"in e){const i=e,r={channel:null!==(s=i.spaceId)&&void 0!==s?s:i.channel,uuids:null!==(n=i.userIds)&&void 0!==n?n:i.uuids,limit:0};return t?this.objects.removeChannelMembers(r,t):this.objects.removeChannelMembers(r)}const r=e,a={uuid:r.userId,channels:null!==(i=r.spaceIds)&&void 0!==i?i:r.channels,limit:0};return t?this.objects.removeMemberships(a,t):this.objects.removeMemberships(a)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return r(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Send file with parameters:"})));const s=new is(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:K.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0},i=e=>{e&&this.logger.debug("PubNub",`Send file success. File shared with ${e.id} ID.`)};return s.process().then((e=>(n.statusCode=e.status,i(e),t?t(n,e):e))).catch((e=>{let s;throw e instanceof d?s=e.status:e instanceof G&&(s=e.toStatus(n.operation)),this.logger.error("PubNub",(()=>({messageType:"error",message:new d("File sending error. Check status for details",s)}))),t&&s&&t(s,null),new d("REST API request processing error. Check status for details",s)}))}}))}publishFile(e,t){return r(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Publish file message with parameters:"})));const s=new Yt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),n=e=>{e&&this.logger.debug("PubNub",`Publish file message success. File message published with timetoken: ${e.timetoken}`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}listFiles(e,t){return r(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List files with parameters:"})));const s=new ts(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`List files success. There are ${e.count} uploaded files.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}getFileUrl(e){var t;{const s=this.transport.request(new Zt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=null!==(t=s.queryParameters)&&void 0!==t?t:{},i=Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${C(t)}`)).join("&"):`${e}=${C(t)}`})).join("&");return`${s.origin}${s.path}?${i}`}}downloadFile(e,t){return r(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Download file with parameters:"})));const s=new kn(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()})),n=e=>{e&&this.logger.debug("PubNub","Download file success.")};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):yield this.sendRequest(s).then((e=>(n(e),e)))}}))}deleteFile(e,t){return r(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Delete file with parameters:"})));const s=new es(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Delete file success. Deleted file with ${e.id} ID.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}time(e){return r(this,void 0,void 0,(function*(){this.logger.debug("PubNub","Get service time.");const t=new wn,s=e=>{e&&this.logger.debug("PubNub",`Get service time success. Current timetoken: ${e.timetoken}`)};return e?this.sendRequest(t,((t,n)=>{s(n),e(t,n)})):this.sendRequest(t).then((e=>(s(e),e)))}))}emitStatus(e){var t;null===(t=this.eventDispatcher)||void 0===t||t.handleStatus(e)}emitEvent(e,t){var s;this._globalSubscriptionSet&&this._globalSubscriptionSet.handleEvent(e,t),null===(s=this.eventDispatcher)||void 0===s||s.handleEvent(t),Object.values(this.eventHandleCapable).forEach((s=>{s!==this._globalSubscriptionSet&&s.handleEvent(e,t)}))}set onStatus(e){this.eventDispatcher&&(this.eventDispatcher.onStatus=e)}set onMessage(e){this.eventDispatcher&&(this.eventDispatcher.onMessage=e)}set onPresence(e){this.eventDispatcher&&(this.eventDispatcher.onPresence=e)}set onSignal(e){this.eventDispatcher&&(this.eventDispatcher.onSignal=e)}set onObjects(e){this.eventDispatcher&&(this.eventDispatcher.onObjects=e)}set onMessageAction(e){this.eventDispatcher&&(this.eventDispatcher.onMessageAction=e)}set onFile(e){this.eventDispatcher&&(this.eventDispatcher.onFile=e)}set onDataSync(e){this.eventDispatcher&&(this.eventDispatcher.onDataSync=e)}addListener(e){this.eventDispatcher&&this.eventDispatcher.addListener(e)}removeListener(e){this.eventDispatcher&&this.eventDispatcher.removeListener(e)}removeAllListeners(){this.eventDispatcher&&this.eventDispatcher.removeAllListeners()}encrypt(e,t){this.logger.warn("PubNub","'encrypt' is deprecated. Use cryptoModule instead.");const s=this._configuration.getCryptoModule();if(!t&&s&&"string"==typeof e){const t=s.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){this.logger.warn("PubNub","'decrypt' is deprecated. Use cryptoModule instead.");const s=this._configuration.getCryptoModule();if(!t&&s){const t=s.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return r(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return r(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}Cn.decoder=new TextDecoder,Cn.OPERATIONS=K,Cn.CATEGORIES=h,Cn.Endpoint=X,Cn.ExponentialRetryPolicy=Q.ExponentialRetryPolicy,Cn.LinearRetryPolicy=Q.LinearRetryPolicy,Cn.NoneRetryPolicy=Q.None,Cn.LogLevel=V;class Pn{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return"object"==typeof n?n:void 0}}class Nn extends Cn{constructor(e){var t;const s=void 0!==e.subscriptionWorkerUrl,i=W(e),r=Object.assign(Object.assign({},i),{sdkFamily:"Web"});r.PubNubFile=o;const a=re(r,(e=>{if(e.cipherKey){return new F({default:new $(Object.assign(Object.assign({},e),e.logger?{}:{logger:a.logger()})),cryptors:[new j({cipherKey:e.cipherKey})]})}}));let u,l;e.subscriptionWorkerLogVerbosity?e.subscriptionWorkerLogLevel=V.Debug:void 0===e.subscriptionWorkerLogLevel&&(e.subscriptionWorkerLogLevel=V.None),void 0!==e.subscriptionWorkerLogVerbosity&&a.logger().warn("Configuration","'subscriptionWorkerLogVerbosity' is deprecated. Use 'subscriptionWorkerLogLevel' instead."),a.getCryptoModule()&&(a.getCryptoModule().logger=a.logger()),u=new ce(new Pn((e=>B(n.decode(e))),c)),(a.getCipherKey()||a.secretKey)&&(l=new U({secretKey:a.secretKey,cipherKey:a.getCipherKey(),useRandomIVs:a.getUseRandomIVs(),customEncrypt:a.getCustomEncrypt(),customDecrypt:a.getCustomDecrypt(),logger:a.logger()}));let h,d=()=>{},p=()=>{},g=()=>{},b=()=>{};h=new A;let y=new de(a.logger(),r.transport);if(i.subscriptionWorkerUrl)try{const e=new H({clientIdentifier:a._instanceId,subscriptionKey:a.subscribeKey,userId:a.getUserId(),workerUrl:i.subscriptionWorkerUrl,sdkVersion:a.getVersion(),heartbeatInterval:a.getHeartbeatInterval(),announceSuccessfulHeartbeats:a.announceSuccessfulHeartbeats,announceFailedHeartbeats:a.announceFailedHeartbeats,workerOfflineClientsCheckInterval:r.subscriptionWorkerOfflineClientsCheckInterval,workerUnsubscribeOfflineClients:r.subscriptionWorkerUnsubscribeOfflineClients,workerLogLevel:r.subscriptionWorkerLogLevel,tokenManager:u,transport:y,logger:a.logger()});p=t=>e.onPresenceStateChange(t),d=t=>e.onHeartbeatIntervalChange(t),g=t=>e.onTokenChange(t),b=t=>e.onUserIdChange(t),y=e,i.subscriptionWorkerUnsubscribeOfflineClients&&"undefined"!=typeof window&&window.addEventListener&&window.addEventListener("pagehide",(t=>{t.persisted||e.terminate()}),{once:!0})}catch(e){a.logger().error("PubNub",(()=>({messageType:"error",message:e})))}else s&&a.logger().warn("PubNub","SharedWorker not supported in this browser. Fallback to the original transport.");const m=new he({clientConfiguration:a,tokenManager:u,transport:y});if(super({configuration:a,transport:m,cryptography:h,tokenManager:u,crypto:l}),this.File=o,this.onHeartbeatIntervalChange=d,this.onAuthenticationChange=g,this.onPresenceStateChange=p,this.onUserIdChange=b,y instanceof H){y.emitStatus=this.emitStatus.bind(this);const e=this.disconnect.bind(this);this.disconnect=t=>{y.disconnect(),e()}}(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.logger.debug("PubNub","Network down detected"),this.emitStatus({category:Nn.CATEGORIES.PNNetworkDownCategory}),this._configuration.restore?this.disconnect(!0):this.destroy(!0)}networkUpDetected(){this.logger.debug("PubNub","Network up detected"),this.emitStatus({category:Nn.CATEGORIES.PNNetworkUpCategory}),this.reconnect()}}return Nn.CryptoModule=F,Nn})); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s={exports:{}};!function(t){!function(e,s){var n=Math.pow(2,-24),r=Math.pow(2,32),i=Math.pow(2,53);var a={encode:function(e){var t,n=new ArrayBuffer(256),a=new DataView(n),o=0;function c(e){for(var s=n.byteLength,r=o+e;s>2,u=0;u>6),r.push(128|63&a)):a<55296?(r.push(224|a>>12),r.push(128|a>>6&63),r.push(128|63&a)):(a=(1023&a)<<10,a|=1023&t.charCodeAt(++n),a+=65536,r.push(240|a>>18),r.push(128|a>>12&63),r.push(128|a>>6&63),r.push(128|63&a))}return d(3,r.length),h(r);default:var p;if(Array.isArray(t))for(d(4,p=t.length),n=0;n>5!==e)throw"Invalid indefinite length element";return s}function y(e,t){for(var s=0;s>10),e.push(56320|1023&n))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return s});var m=function e(){var r,d,m=l(),f=m>>5,v=31&m;if(7===f)switch(v){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),s=h(),r=32768&s,i=31744&s,a=1023&s;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==a)return a*n;return t.setUint32(0,r<<16|i<<13|a<<13),t.getFloat32(0)}();case 26:return c(a.getFloat32(o),4);case 27:return c(a.getFloat64(o),8)}if((d=g(v))<0&&(f<2||6=0;)S+=d,O.push(u(d));var j=new Uint8Array(S),w=0;for(r=0;r=0;)y(k,d);else y(k,d);return String.fromCharCode.apply(null,k);case 4:var P;if(d<0)for(P=[];!p();)P.push(e());else for(P=new Array(d),r=0;re.toString())).join(", ")}]}`}}a.encoder=new TextEncoder,a.decoder=new TextDecoder;class o{static create(e){return new o(e)}constructor(e){let t,s,n,r;if(e instanceof File)r=e,n=e.name,s=e.type,t=e.size;else if("data"in e){const i=e.data;s=e.mimeType,n=e.name,r=new File([i],n,{type:s}),t=r.size}if(void 0===r)throw new Error("Couldn't construct a file out of supplied options.");if(void 0===n)throw new Error("Couldn't guess filename out of the options. Please provide one.");t&&(this.contentLength=t),this.mimeType=s,this.data=r,this.name=n}toBuffer(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toArrayBuffer(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if(s.result instanceof ArrayBuffer)return e(s.result)})),s.addEventListener("error",(()=>t(s.error))),s.readAsArrayBuffer(this.data)}))}))}toString(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if("string"==typeof s.result)return e(s.result)})),s.addEventListener("error",(()=>{t(s.error)})),s.readAsBinaryString(this.data)}))}))}toStream(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return i(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return i(this,void 0,void 0,(function*(){return this.data}))}}o.supportsBlob="undefined"!=typeof Blob,o.supportsFile="undefined"!=typeof File,o.supportsBuffer=!1,o.supportsStream=!1,o.supportsString=!0,o.supportsArrayBuffer=!0,o.supportsEncryptFile=!0,o.supportsFileUri=!1;function c(e){const t=e.replace(/==?$/,""),s=Math.floor(t.length/4*3),n=new ArrayBuffer(s),r=new Uint8Array(n);let i=0;function a(){const e=t.charAt(i++),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===s)throw new Error(`Illegal character at ${i}: ${t.charAt(i-1)}`);return s}for(let e=0;e>4,c=(15&s)<<4|n>>2,u=(3&n)<<6|i;r[e]=o,64!=n&&(r[e+1]=c),64!=i&&(r[e+2]=u)}return n}function u(e){let t="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(e),r=n.byteLength,i=r%3,a=r-i;let o,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=s[o]+s[c]+s[u]+s[l];return 1==i?(h=n[a],o=(252&h)>>2,c=(3&h)<<4,t+=s[o]+s[c]+"=="):2==i&&(h=n[a]<<8|n[a+1],o=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=s[o]+s[c]+s[u]+"="),t}var l;!function(e){e.PNNetworkIssuesCategory="PNNetworkIssuesCategory",e.PNTimeoutCategory="PNTimeoutCategory",e.PNCancelledCategory="PNCancelledCategory",e.PNBadRequestCategory="PNBadRequestCategory",e.PNAccessDeniedCategory="PNAccessDeniedCategory",e.PNValidationErrorCategory="PNValidationErrorCategory",e.PNAcknowledgmentCategory="PNAcknowledgmentCategory",e.PNMalformedResponseCategory="PNMalformedResponseCategory",e.PNServerErrorCategory="PNServerErrorCategory",e.PNUnknownCategory="PNUnknownCategory",e.PNNetworkUpCategory="PNNetworkUpCategory",e.PNNetworkDownCategory="PNNetworkDownCategory",e.PNReconnectedCategory="PNReconnectedCategory",e.PNConnectedCategory="PNConnectedCategory",e.PNSubscriptionChangedCategory="PNSubscriptionChangedCategory",e.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",e.PNDisconnectedCategory="PNDisconnectedCategory",e.PNConnectionErrorCategory="PNConnectionErrorCategory",e.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory",e.PNSharedWorkerUpdatedCategory="PNSharedWorkerUpdatedCategory"}(l||(l={}));var h=l;class d extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function p(e,t){var s;return null!==(s=e.statusCode)&&void 0!==s||(e.statusCode=0),Object.assign(Object.assign({},e),{statusCode:e.statusCode,category:t,error:!0})}function g(e,t){return p(Object.assign(Object.assign({message:"Unable to deserialize service response"},void 0!==e?{responseText:e}:{}),void 0!==t?{statusCode:t}:{}),h.PNMalformedResponseCategory)} +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function b(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name&&"BYTES_PER_ELEMENT"in e&&1===e.BYTES_PER_ELEMENT}const y=e=>e?`"${e}" `:"";function m(e,t=""){if("number"!=typeof e)throw new TypeError(y(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(y(t)+"expected integer >= 0, got "+e);return e}function f(e,t,s=""){if(b(e)&&(void 0===t||e.length===t))return e;void 0!==t&&m(t,"length");const n=b(e),r=void 0!==t?` of length ${t}`:"",i=n?`length=${e.length}`:"type="+typeof e,a=y(s)+"expected Uint8Array"+r+", got "+i;if(!n)throw new TypeError(a);throw new RangeError(a)}function v(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function O(...e){for(let t=0;t68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();const j=S?e=>e:function(e){for(let s=0;s>>8&65280|t>>>24&255;var t;return e};function w(e,t){if(n=t,(s=e).byteLength&&n.byteLength&&s.buffer===n.buffer&&s.byteOffset{function s(s,...n){if(f(s,void 0,"key"),void 0!==e.nonceLength){f(n[0],e.varSizeNonce?void 0:e.nonceLength,"nonce")}const r=e.tagLength,i=void 0!==e.nonceLength?1:0;if(!e.withAAD)for(let e=i;e{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");f(t,void 0,"output")}};let c=!1;return{encrypt(e,t){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,f(e,void 0,"data"),o(a.encrypt.length,t),a.encrypt(e,t)},decrypt(e,t){if(f(e,void 0,"data"),r&&e.length= tagLength='+r);return o(a.decrypt.length,t),a.decrypt(e,t)}}}return Object.assign(s,e),s};function P(e,t,s=!0){if(void 0===t)return new Uint8Array(e);if(f(t,e,"output"),s&&!C(t))throw new Error("invalid output, must be aligned");return t}function C(e){return e.byteOffset%4==0}function E(e){return Uint8Array.from(f(e))}const N=16;function T(e){return e<<1^283&-(e>>7)}function I(e,t){let s=0;for(;t>0;t>>=1)s^=e&-(1&t),e=T(e);return s}const R=(()=>{const e=new Uint8Array(256);for(let t=0,s=1;t<256;t++,s^=T(s))e[t]=s;const t=new Uint8Array(256);t[0]=99;for(let s=0;s<255;s++){let n=e[255-s];n|=n<<8,t[e[s]]=255&(n^n>>4^n>>5^n>>6^n>>7^99)}return O(e),t})(),M=R.map(((e,t)=>R.indexOf(t))),U=e=>e<<8|e>>>24;function _(e,t){if(256!==e.length)throw new Error("wrong sbox length");const s=new Uint32Array(256).map(((s,n)=>t(e[n]))),n=s.map(U),r=n.map(U),i=r.map(U),a=new Uint32Array(65536),o=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let u=0;u<256;u++){const l=256*t+u;a[l]=s[t]^n[u],o[l]=r[t]^i[u],c[l]=e[t]<<8|e[u]}return{sbox:e,sbox2:c,T0:s,T1:n,T2:r,T3:i,T01:a,T23:o}}const D=_(R,(e=>I(e,3)<<24|e<<16|e<<8|I(e,2))),A=_(M,(e=>I(e,11)<<24|I(e,13)<<16|I(e,9)<<8|I(e,14))),$=(()=>{const e=new Uint8Array(16);for(let t=0,s=1;t<16;t++,s=T(s))e[t]=s;return e})();function F(e){f(e);const t=e.length;!function(e){if(![16,24,32].includes(e.length))throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length='+e.length)}(e);const{sbox2:s}=D,n=[];S&&C(e)||n.push(e=E(e));const r=j(v(e)),i=r.length,a=e=>q(s,e,e,e,e),o=new Uint32Array(t+28);o.set(r);for(let e=i;e>>8)^$[e/i-1]:i>6&&e%i==4&&(t=a(t)),o[e]=o[e-i]^t}var c;return O(...n),o}function x(e,t,s,n,r,i){return e[s<<8&65280|n>>>8&255]^t[r>>>8&65280|i>>>24&255]}function q(e,t,s,n,r){return e[255&t|65280&s]|e[n>>>16&255|r>>>16&65280]<<16}function L(e,t,s,n,r){const{sbox2:i,T01:a,T23:o}=D;let c=0;t^=e[c++],s^=e[c++],n^=e[c++],r^=e[c++];const u=e.length/4-2;for(let i=0;i>>8&255]^o[n>>>16&255]^c[n>>>24]}return s}(e);void 0===r&&(r=new Uint8Array(s.length));let a=t;const o=[i];S&&C(a)||o.push(a=E(a));const c=v(a);j(c),S&&C(s)||o.push(s=E(s));const u=v(s),l=v(r);j(u);let h=c[0],d=c[1],p=c[2],g=c[3];for(let e=0;e+4<=u.length;){const t=h,s=d,n=p,r=g;h=u[e+0],d=u[e+1],p=u[e+2],g=u[e+3];const{s0:a,s1:o,s2:c,s3:b}=G(i,h,d,p,g);l[e++]=a^t,l[e++]=o^s,l[e++]=c^n,l[e++]=b^r}return j(l),O(...o),function(e,t){if(!t)return e;const s=e.length;if(0===s)throw new Error("pkcs7: empty ciphertext not allowed");const n=e[s-1];let r=1;r&=n-1>>>31^1,r&=16-n>>>31^1;for(let t=0;t<16;t++){const i=t-n>>>31;r&=(e[s-1-t]^n?0:1)|1^i}if(!r)throw new Error("aes: bad decrypt");return e.subarray(0,s-n)}(r,n)}}}));function H(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name&&"BYTES_PER_ELEMENT"in e&&1===e.BYTES_PER_ELEMENT}function V(e,t,s=""){if(H(e)&&void 0===t)return e;const n=H(e),r=n?`length=${e.length}`:"type="+typeof e,i=(e=>e?`"${e}" `:"")(s)+"expected Uint8Array, got "+r;if(!n)throw new TypeError(i);throw new RangeError(i)}const W=(e,t)=>{((e,t)=>{if(null===e||"object"!=typeof e||Array.isArray(e))throw new TypeError(("object"===t?"":`"${t}" `)+"expected object, got type="+typeof e)})(e,t);const s=Object.getPrototypeOf(e);if(s!==Object.prototype&&null!==s)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function B(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function z(...e){for(let t=0;t>>t}function X(e,t={}){if("function"!=typeof e)throw new TypeError('"hashCons" expected function, got type='+typeof e);t=function(e,t,s="opts"){return W(e,"defaults"),void 0!==t&&W(t,s),Object.assign(Object.create(null),e,t)}({},t,"info");const s=(t,s)=>e(s).update(t).digest(),n=e(void 0);return s.outputLen=n.outputLen,s.blockLen=n.blockLen,s.canXOF=n.canXOF,s.create=t=>e(t),Object.assign(s,t),Object.freeze(s)}const Q=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Z(e,t,s){return e&t^e&s^t&s}class ee{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,s,n){this.blockLen=e,this.outputLen=t,this.padOffset=s,this.isLE=n,this.buffer=new Uint8Array(e),this.view=J(this.buffer)}update(e){B(this),V(e);const{view:t,buffer:s,blockLen:n}=this,r=e.length;let i=!1;for(let a=0;a=s))throw new RangeError('"output" expected length >= '+s)}(e,this),this.finished=!0;const{buffer:t,view:s,blockLen:n,isLE:r}=this;let{pos:i}=this;t[i++]=128,t.fill(0,i),this.padOffset>n-i&&(this.process(s,0),t.fill(0)),function(e,t,s,n){const r=(e=>e/2**32|0)(s),i=(e=>e>>>0)(s);e.setUint32(t,n?i:r,n),e.setUint32(t+4,n?r:i,n)}(s,n-8,8*this.length,r),this.process(s,0),this.roundClean();const a=e===t?s:J(e),o=this.outputLen,c=o/4,u=this.get();if(o%4||c>u.length)throw new Error("invalid outputLen");for(let e=0;e>>3,r=Y(s,17)^Y(s,19)^s>>>10;ne[e]=r+ne[e-7]+n+ne[e-16]|0}let{A:s,B:n,C:r,D:i,E:a,F:o,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(Y(a,6)^Y(a,11)^Y(a,25))+((l=a)&o^~l&c)+se[e]+ne[e]|0,h=(Y(s,2)^Y(s,13)^Y(s,22))+Z(s,n,r)|0;u=c,c=o,o=a,a=i+t|0,i=r,r=n,n=s,s=t+h|0}var l;s=s+this.A|0,n=n+this.B|0,r=r+this.C|0,i=i+this.D|0,a=a+this.E|0,o=o+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(s,n,r,i,a,o,c,u)}roundClean(){z(ne)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),z(this.buffer)}}class ie extends re{constructor(){super(32,te)}}const ae=X((()=>new ie),Q(1)),oe=e=>{for(let t=0;t=55296&&s<=56319){const s=t+157343)throw new URIError("URI malformed");t++}else if(s>=56320&&s<=57343)throw new URIError("URI malformed")}return(new TextEncoder).encode(e)},ce=e=>{const t=e.length;let s=0;for(;s=194&&n<=223)r=1;else if(n>=224&&n<=239)r=2,224===n?i=160:237===n&&(a=159);else{if(!(n>=240&&n<=244))return!1;r=3,240===n?i=144:244===n&&(a=143)}if(s+r>=t)return!1;if(e[s+1]a)return!1;for(let t=2;t<=r;t++)if(e[s+t]<128||e[s+t]>191)return!1;s+=r+1}return!0},ue=e=>{if(!ce(e))throw new Error("Malformed UTF-8 data");const t=(new TextDecoder).decode(e);return e.length>=3&&239===e[0]&&187===e[1]&&191===e[2]&&65279!==t.charCodeAt(0)?`\ufeff${t}`:t},le=e=>{const t=e.length?e[e.length-1]:0;return t>e.length?new Uint8Array(0):e.subarray(0,e.length-t)},he=e=>Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join(""),de=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);class pe{constructor({cipherKey:e}){this.cipherKey=e,this.encryptedKey=ae(oe(e))}encrypt(e){if(0===("string"==typeof e?e:pe.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv(),s="string"==typeof e?oe(e):new Uint8Array(e);return{metadata:t,data:de(K(this.encryptedKey,t).encrypt(s))}}encryptFileData(e){return i(this,void 0,void 0,(function*(){const t=yield this.getKey(),s=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:s},t,e),metadata:s}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=new Uint8Array(e.metadata),s=new Uint8Array(e.data),n=le(K(this.encryptedKey,t,{disablePadding:!0}).decrypt(s));if(!ce(n))throw new Error("Malformed UTF-8 data");return de(n)}decryptFileData(e){return i(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(pe.BLOCK_SIZE))}getKey(){return i(this,void 0,void 0,(function*(){const e=pe.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}toString(){return"AesCbcCryptor {}"}}pe.BLOCK_SIZE=16,pe.encoder=new TextEncoder,pe.decoder=new TextDecoder;const ge=(e,t,s,n=!1)=>{if("ecb"===e)throw new Error("AES-ECB is not supported");return K(t,s,n?{disablePadding:!0}:void 0)},be={sha256:e=>ae(e),hmacSha256:()=>{throw new Error("HMAC-SHA256 is not supported on this platform")},aesEncrypt:(e,t,s,n)=>ge(e,t,s).encrypt(n),aesDecrypt:(e,t,s,n)=>le(ge(e,t,s,!0).decrypt(n)),randomBytes:e=>function(e=32){m(e,"bytesLength");const t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}(e)},ye=new Set(["authKey","authKeys","secretKey","cipherKey","token","auth"]),me=e=>ye.has(e),fe=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),ve=(e,t)=>{const s=e.map((e=>fe(e)));return s.length?s.join(","):null!=t?t:""},Oe=(e,t)=>{const s=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!s[e])||(s[e]=!0,!1)))},Se=(e,t)=>[...e].filter((s=>t.includes(s)&&e.indexOf(s)===e.lastIndexOf(s)&&t.indexOf(s)===t.lastIndexOf(s))),je=e=>Object.keys(e).map((t=>{const s=e[t];return Array.isArray(s)?s.map((e=>`${t}=${fe(e)}`)).join("&"):`${t}=${fe(s)}`})).join("&"),we=(e,t)=>{if("0"===t||"0"===e)return;const s=Pe(`${Date.now()}0000`,t,!1);return Pe(e,s,!0)},ke=(e,t,s)=>{if(e&&0!==e.length){if(t&&t.length>0&&"0"!==t){const n=Pe(e,t,!1);return Pe(null!=s?s:`${Date.now()}0000`,n.replace("-",""),Number(n)<0)}return s&&s.length>0&&"0"!==s?s:`${Date.now()}0000`}},Pe=(e,t,s)=>{t.startsWith("-")&&(t=t.replace("-",""),s=!1),t=t.padStart(17,"0");const n=e.slice(0,10),r=e.slice(10,17),i=t.slice(0,10),a=t.slice(10,17);let o=Number(n),c=Number(r);return o+=Number(i)*(s?1:-1),c+=Number(a)*(s?1:-1),c>=1e7?(o+=Math.floor(c/1e7),c%=1e7):c<0?o>0?(o-=1,c+=1e7):o<0&&(c*=-1):o<0&&c>0&&(o+=1,c=1e7-c),0!==o?`${o}${`${c}`.padStart(7,"0")}`:`${c}`},Ce=e=>{const t="string"!=typeof e?JSON.stringify(e):e,s=new Uint32Array(1);let n=0,r=t.length;for(;r-- >0;)s[0]=(s[0]<<5)-s[0]+t.charCodeAt(n++);return s[0].toString(16).padStart(8,"0")};let Ee=!1;class Ne{constructor(e,t){this.configuration=e,this.primitives=t,this.iv="0123456789012345",this.allowedKeyEncodings=["hex","utf8","base64","binary"],this.allowedKeyLengths=[128,256],this.allowedModes=["ecb","cbc"],this.logger=e.logger,this.defaultOptions={encryptKey:!0,keyEncoding:"utf8",keyLength:256,mode:"cbc"}}set logger(e){this._logger=e,this.logger&&this.logger.debug("Crypto",(()=>({messageType:"object",message:this.configuration,details:"Create with configuration:",ignoredKeys:(e,t)=>"function"==typeof t[e]||"logger"===e||me(e)})))}get logger(){return this._logger}HMACSHA256(e){var t;const s=this.primitives.hmacSha256(oe(null!==(t=this.configuration.secretKey)&&void 0!==t?t:""),oe(e));return u(de(s))}SHA256(e){return he(this.primitives.sha256(oe(e)))}encrypt(e,t,s){return this.configuration.customEncrypt?(this.logger&&this.logger.warn("Crypto","'customEncrypt' is deprecated. Consult docs for better alternative."),this.configuration.customEncrypt(e)):this.pnEncrypt(e,t,s)}decrypt(e,t,s){return this.configuration.customDecrypt?(this.logger&&this.logger.warn("Crypto","'customDecrypt' is deprecated. Consult docs for better alternative."),this.configuration.customDecrypt(e)):this.pnDecrypt(e,t,s)}pnEncrypt(e,t,s){const n=null!=t?t:this.configuration.cipherKey;if(!n)return e;if(this.logger&&this.logger.debug("Crypto",(()=>({messageType:"object",message:Object.assign({data:e},null!=s?s:{}),details:"Encrypt with parameters:",ignoredKeys:me}))),"string"!=typeof e)throw new Error("Encryption error: data should be a string");s=this.parseOptions(s);const r=this.getMode(s),i=this.getPaddedKey(n,s),a=oe(e);if(this.configuration.useRandomIVs){const e=this.getRandomIV(),t=this.primitives.aesEncrypt(r,i,e,a);return u(de(((e,t)=>{const s=new Uint8Array(e.length+t.length);return s.set(e),s.set(t,e.length),s})(e,t)))}const o=this.primitives.aesEncrypt(r,i,this.getIV(s),a);return u(de(o))||e}pnDecrypt(e,t,s){const n=null!=t?t:this.configuration.cipherKey;if(!n)return e;this.logger&&this.logger.debug("Crypto",(()=>({messageType:"object",message:Object.assign({data:e},null!=s?s:{}),details:"Decrypt with parameters:",ignoredKeys:me}))),s=this.parseOptions(s);const r=this.getMode(s),i=this.getPaddedKey(n,s);if(this.configuration.useRandomIVs){const t=new Uint8Array(c(e)),s=t.slice(0,16),n=t.slice(16);try{const e=ue(this.primitives.aesDecrypt(r,i,s,n));return JSON.parse(e)}catch(e){return this.logger&&this.logger.error("Crypto",(()=>({messageType:"error",message:e}))),null}}else{const t=this.getIV(s);try{const s=new Uint8Array(c(e)),n=ue(this.primitives.aesDecrypt(r,i,t,s));return JSON.parse(n)}catch(e){return this.logger&&this.logger.error("Crypto",(()=>({messageType:"error",message:e}))),null}}}parseOptions(e){var t,s,n,r;if(!e)return this.defaultOptions;const i={encryptKey:null!==(t=e.encryptKey)&&void 0!==t?t:this.defaultOptions.encryptKey,keyEncoding:null!==(s=e.keyEncoding)&&void 0!==s?s:this.defaultOptions.keyEncoding,keyLength:null!==(n=e.keyLength)&&void 0!==n?n:this.defaultOptions.keyLength,mode:null!==(r=e.mode)&&void 0!==r?r:this.defaultOptions.mode};return-1===this.allowedKeyEncodings.indexOf(i.keyEncoding.toLowerCase())&&(i.keyEncoding=this.defaultOptions.keyEncoding),-1===this.allowedKeyLengths.indexOf(i.keyLength)&&(i.keyLength=this.defaultOptions.keyLength),-1===this.allowedModes.indexOf(i.mode.toLowerCase())&&(i.mode=this.defaultOptions.mode),i}decodeKey(e,t){return"base64"===t.keyEncoding?new Uint8Array(c(e)):"hex"===t.keyEncoding?(s=e,Uint8Array.from(null!==(n=s.match(/.{1,2}/g))&&void 0!==n?n:[],(e=>parseInt(e,16)))):oe(e);var s,n}getPaddedKey(e,t){const s=this.decodeKey(e,t);return t.encryptKey?oe(he(this.primitives.sha256(s)).slice(0,32)):s}getMode(e){return"ecb"===e.mode?"ecb":"cbc"}getIV(e){return"cbc"===e.mode?oe(this.iv):null}getRandomIV(){try{return this.primitives.randomBytes(16)}catch(e){return!Ee&&this.logger&&(Ee=!0,this.logger.warn("Crypto","'crypto.getRandomValues' is unavailable; falling back to insecure Math.random() IV. Install 'react-native-get-random-values'.")),Uint8Array.from({length:16},(()=>Math.floor(256*Math.random())))}}}class Te extends Ne{constructor(e){super(e,be)}}class Ie{encrypt(e,t){return i(this,void 0,void 0,(function*(){if(!(t instanceof ArrayBuffer)&&"string"!=typeof t)throw new Error("Cannot encrypt this file. In browsers file encryption supports only string or ArrayBuffer");const s=yield this.getKey(e);return t instanceof ArrayBuffer?this.encryptArrayBuffer(s,t):this.encryptString(s,t)}))}encryptArrayBuffer(e,t){return i(this,void 0,void 0,(function*(){const s=crypto.getRandomValues(new Uint8Array(16));return this.concatArrayBuffer(s.buffer,yield crypto.subtle.encrypt({name:"AES-CBC",iv:s},e,t))}))}encryptString(e,t){return i(this,void 0,void 0,(function*(){const s=crypto.getRandomValues(new Uint8Array(16)),n=Ie.encoder.encode(t).buffer,r=yield crypto.subtle.encrypt({name:"AES-CBC",iv:s},e,n),i=this.concatArrayBuffer(s.buffer,r);return Ie.decoder.decode(i)}))}encryptFile(e,t,s){return i(this,void 0,void 0,(function*(){var n,r;if((null!==(n=t.contentLength)&&void 0!==n?n:0)<=0)throw new Error("encryption error. empty content");const i=yield this.getKey(e),a=yield t.toArrayBuffer(),o=yield this.encryptArrayBuffer(i,a);return s.create({name:t.name,mimeType:null!==(r=t.mimeType)&&void 0!==r?r:"application/octet-stream",data:o})}))}decrypt(e,t){return i(this,void 0,void 0,(function*(){if(!(t instanceof ArrayBuffer)&&"string"!=typeof t)throw new Error("Cannot decrypt this file. In browsers file decryption supports only string or ArrayBuffer");const s=yield this.getKey(e);return t instanceof ArrayBuffer?this.decryptArrayBuffer(s,t):this.decryptString(s,t)}))}decryptArrayBuffer(e,t){return i(this,void 0,void 0,(function*(){const s=t.slice(0,16);if(t.slice(Ie.IV_LENGTH).byteLength<=0)throw new Error("decryption error: empty content");return yield crypto.subtle.decrypt({name:"AES-CBC",iv:s},e,t.slice(Ie.IV_LENGTH))}))}decryptString(e,t){return i(this,void 0,void 0,(function*(){const s=Ie.encoder.encode(t).buffer,n=s.slice(0,16),r=s.slice(16),i=yield crypto.subtle.decrypt({name:"AES-CBC",iv:n},e,r);return Ie.decoder.decode(i)}))}decryptFile(e,t,s){return i(this,void 0,void 0,(function*(){const n=yield this.getKey(e),r=yield t.toArrayBuffer(),i=yield this.decryptArrayBuffer(n,r);return s.create({name:t.name,mimeType:t.mimeType,data:i})}))}getKey(e){return i(this,void 0,void 0,(function*(){const t=yield crypto.subtle.digest("SHA-256",Ie.encoder.encode(e)),s=Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join(""),n=Ie.encoder.encode(s.slice(0,32)).buffer;return crypto.subtle.importKey("raw",n,"AES-CBC",!0,["encrypt","decrypt"])}))}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}}Ie.IV_LENGTH=16,Ie.encoder=new TextEncoder,Ie.decoder=new TextDecoder;class Re{constructor(e){this.config=e,this.cryptor=new Te(Object.assign({},e)),this.fileCryptor=new Ie}set logger(e){this.cryptor.logger=e,!1===this.config.useRandomIVs&&e.warn("LegacyCryptor","Setting 'useRandomIVs' to false is insecure and should only be used to support legacy clients.\n Do not disable random IVs in new applications.")}encrypt(e){const t="string"==typeof e?e:Re.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(s=this.config)||void 0===s?void 0:s.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:u(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return i(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}toString(){return`LegacyCryptor { ${Object.entries(this.config).reduce(((e,[t,s])=>("logger"===t||me(t)||e.push(`${t}: ${"function"==typeof s?"":s}`),e)),[]).join(", ")} }`}}Re.encoder=new TextEncoder,Re.decoder=new TextDecoder;class Me extends a{set logger(e){if(this.defaultCryptor.identifier===Me.LEGACY_IDENTIFIER)e.warn("CryptoModule","'legacyCryptoModule' is deprecated. Use 'aesCbcCryptoModule' instead for new applications."),this.defaultCryptor.logger=e;else{const t=this.cryptors.find((e=>e.identifier===Me.LEGACY_IDENTIFIER));t&&(t.logger=e)}}static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return e.logger&&(e.logger.warn("CryptoModule","'legacyCryptoModule' is deprecated. Use 'aesCbcCryptoModule' instead for new applications."),!1===e.useRandomIVs&&e.logger.warn("CryptoModule","Setting 'useRandomIVs' to false is insecure and should only be used to support legacy clients.\n Do not disable random IVs in new applications.")),new Me({default:new Re(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new pe({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new Me({default:new pe({cipherKey:e.cipherKey}),cryptors:[new Re(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===Me.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(Me.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const s=this.getHeaderData(t);return this.concatArrayBuffer(s,t.data)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===Ue.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const s=yield this.getFileData(e),n=yield this.defaultCryptor.encryptFileData(s);if("string"==typeof n.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(n),n.data)})}))}decrypt(e){const t="string"==typeof e?c(e):e,s=Ue.tryParse(t),n=this.getCryptor(s),r=s.length>0?t.slice(s.length-s.metadataLength,s.length):null;if(t.slice(s.length).byteLength<=0)throw new Error("Decryption error: empty content");return n.decrypt({data:t.slice(s.length),metadata:r})}decryptFile(e,t){return i(this,void 0,void 0,(function*(){const s=yield e.data.arrayBuffer(),n=Ue.tryParse(s),r=this.getCryptor(n);if((null==r?void 0:r.identifier)===Ue.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(s)).slice(n.length-n.metadataLength,n.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:s.slice(n.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof _e)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=Ue.from(this.defaultCryptor.identifier,e.metadata),s=new Uint8Array(t.length);let n=0;return s.set(t.data,n),n+=t.length-e.metadata.byteLength,s.set(new Uint8Array(e.metadata),n),s.buffer}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}getFileData(e){return i(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof o)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}Me.LEGACY_IDENTIFIER="";class Ue{static from(e,t){if(e!==Ue.LEGACY_IDENTIFIER)return new _e(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let s,n,r=null;if(t.byteLength>=4&&(s=t.slice(0,4),this.decoder.decode(s)!==Ue.SENTINEL))return Me.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>Ue.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+Ue.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");n=t.slice(5,i);let a=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return a=t[i],i+=1,255===a&&t.byteLength>=i+2&&(a=new Uint16Array(t.slice(i,i+2)).reduce(((e,t)=>(e<<8)+t),0)),new _e(this.decoder.decode(n),a)}}Ue.SENTINEL="PNED",Ue.LEGACY_IDENTIFIER="",Ue.IDENTIFIER_LENGTH=4,Ue.VERSION=1,Ue.MAX_VERSION=1,Ue.decoder=new TextDecoder;class _e{constructor(e,t){this._identifier=e,this._metadataLength=t}get identifier(){return this._identifier}set identifier(e){this._identifier=e}get metadataLength(){return this._metadataLength}set metadataLength(e){this._metadataLength=e}get version(){return Ue.VERSION}get length(){return Ue.SENTINEL.length+1+Ue.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),s=new TextEncoder;t.set(s.encode(Ue.SENTINEL)),e+=Ue.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(s.encode(this.identifier),e);const n=this.metadataLength;return e+=Ue.IDENTIFIER_LENGTH,n<255?t[e]=n:t.set([255,n>>8,255&n],e),t}}_e.IDENTIFIER_LENGTH=4,_e.SENTINEL="PNED";class De extends Error{static create(e,t){return De.isErrorObject(e)?De.createFromError(e):De.createFromServiceResponse(e,t)}static createFromError(e){let t=h.PNUnknownCategory,s="Unknown error",n="Error";if(!e)return new De(s,t,0);if(e instanceof De)return e;if(De.isErrorObject(e)&&(s=e.message,n=e.name),"AbortError"===n||-1!==s.indexOf("Aborted"))t=h.PNCancelledCategory,s="Request cancelled";else if(-1!==s.toLowerCase().indexOf("timeout"))t=h.PNTimeoutCategory,s="Request timeout";else if(-1!==s.toLowerCase().indexOf("network"))t=h.PNNetworkIssuesCategory,s="Network issues";else if("TypeError"===n)t=-1!==s.indexOf("Load failed")||-1!=s.indexOf("Failed to fetch")?h.PNNetworkIssuesCategory:h.PNBadRequestCategory;else if("FetchError"===n){const n=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(n)&&(t=h.PNNetworkIssuesCategory),"ECONNREFUSED"===n?s="Connection refused":"ENETUNREACH"===n?s="Network not reachable":"ENOTFOUND"===n?s="Server not found":"ECONNRESET"===n?s="Connection reset by peer":"EAI_AGAIN"===n?s="Name resolution error":"ETIMEDOUT"===n?(t=h.PNTimeoutCategory,s="Request timeout"):s=`Unknown system error: ${e}`}else"Request timeout"===s&&(t=h.PNTimeoutCategory);return new De(s,t,0,e)}static createFromServiceResponse(e,t){let s,n=h.PNUnknownCategory,r="Unknown error",{status:i}=e;if(null!=t||(t=e.body),402===i?r="Not available for used key set. Contact support@pubnub.com":404===i?r="Resource not found":400===i?(n=h.PNBadRequestCategory,r="Bad request"):403===i?(n=h.PNAccessDeniedCategory,r="Access denied"):i>=500&&(n=h.PNServerErrorCategory,r="Internal server error"),"object"==typeof e&&0===Object.keys(e).length&&(n=h.PNMalformedResponseCategory,r="Malformed response (network issues)",i=400),t&&t.byteLength>0){const n=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(n);"object"==typeof e&&(Array.isArray(e)?"number"==typeof e[0]&&0===e[0]&&e.length>1&&"string"==typeof e[1]&&(s=e[1]):("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(s=e,i=e.status):s=e,"error"in e&&e.error instanceof Error&&(s=e.error)))}catch(e){s=n}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(n);r=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else s=n}return new De(r,n,i,s)}constructor(e,t,s,n){super(e),this.category=t,this.statusCode=s,this.errorData=n,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData,toJSON:function(){let e;const t=this.errorData;if(t)try{if("object"==typeof t){const s=Object.assign(Object.assign(Object.assign(Object.assign({},"name"in t?{name:t.name}:{}),"message"in t?{message:t.message}:{}),"stack"in t?{stack:t.stack}:{}),t);e=JSON.parse(JSON.stringify(s,De.circularReplacer()))}else e=t}catch(t){e={error:"Could not serialize the error object"}}const s=r(this,["toJSON"]);return JSON.stringify(Object.assign(Object.assign({},s),{errorData:e}))}}}toPubNubError(e,t){return new d(null!=t?t:this.message,this.toStatus(e))}static circularReplacer(){const e=new WeakSet;return function(t,s){if("object"==typeof s&&null!==s){if(e.has(s))return"[Circular]";e.add(s)}return s}}static isErrorObject(e){return!(!e||"object"!=typeof e)&&(e instanceof Error||("name"in e&&"message"in e&&"string"==typeof e.name&&"string"==typeof e.message||"[object Error]"===Object.prototype.toString.call(e)))}}var Ae;!function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNCreateDataSyncEntityOperation="PNCreateDataSyncEntityOperation",e.PNGetDataSyncEntityOperation="PNGetDataSyncEntityOperation",e.PNGetDataSyncEntitiesOperation="PNGetDataSyncEntitiesOperation",e.PNSetDataSyncEntityOperation="PNSetDataSyncEntityOperation",e.PNUpdateDataSyncEntityOperation="PNUpdateDataSyncEntityOperation",e.PNRemoveDataSyncEntityOperation="PNRemoveDataSyncEntityOperation",e.PNCreateDataSyncRelationshipOperation="PNCreateDataSyncRelationshipOperation",e.PNGetDataSyncRelationshipOperation="PNGetDataSyncRelationshipOperation",e.PNGetDataSyncRelationshipsOperation="PNGetDataSyncRelationshipsOperation",e.PNSetDataSyncRelationshipOperation="PNSetDataSyncRelationshipOperation",e.PNUpdateDataSyncRelationshipOperation="PNUpdateDataSyncRelationshipOperation",e.PNRemoveDataSyncRelationshipOperation="PNRemoveDataSyncRelationshipOperation",e.PNCreateDataSyncUserOperation="PNCreateDataSyncUserOperation",e.PNGetDataSyncUserOperation="PNGetDataSyncUserOperation",e.PNGetDataSyncUsersOperation="PNGetDataSyncUsersOperation",e.PNSetDataSyncUserOperation="PNSetDataSyncUserOperation",e.PNUpdateDataSyncUserOperation="PNUpdateDataSyncUserOperation",e.PNRemoveDataSyncUserOperation="PNRemoveDataSyncUserOperation",e.PNCreateDataSyncChannelOperation="PNCreateDataSyncChannelOperation",e.PNGetDataSyncChannelOperation="PNGetDataSyncChannelOperation",e.PNGetDataSyncChannelsOperation="PNGetDataSyncChannelsOperation",e.PNSetDataSyncChannelOperation="PNSetDataSyncChannelOperation",e.PNUpdateDataSyncChannelOperation="PNUpdateDataSyncChannelOperation",e.PNRemoveDataSyncChannelOperation="PNRemoveDataSyncChannelOperation",e.PNCreateDataSyncMembershipOperation="PNCreateDataSyncMembershipOperation",e.PNGetDataSyncMembershipOperation="PNGetDataSyncMembershipOperation",e.PNGetDataSyncMembershipsOperation="PNGetDataSyncMembershipsOperation",e.PNSetDataSyncMembershipOperation="PNSetDataSyncMembershipOperation",e.PNUpdateDataSyncMembershipOperation="PNUpdateDataSyncMembershipOperation",e.PNRemoveDataSyncMembershipOperation="PNRemoveDataSyncMembershipOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(Ae||(Ae={}));var $e=Ae;class Fe{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.accessTokensMap={},this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}set emitStatus(e){this._emitStatus=e}onUserIdChange(e){this.configuration.userId=e,this.scheduleEventPost({type:"client-update",heartbeatInterval:this.configuration.heartbeatInterval,clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,workerLogLevel:this.configuration.workerLogLevel})}onPresenceStateChange(e){this.scheduleEventPost({type:"client-presence-state-update",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,workerLogLevel:this.configuration.workerLogLevel,state:e})}onHeartbeatIntervalChange(e){this.configuration.heartbeatInterval=e,this.scheduleEventPost({type:"client-update",heartbeatInterval:this.configuration.heartbeatInterval,clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,workerLogLevel:this.configuration.workerLogLevel})}onTokenChange(e){const t={type:"client-update",heartbeatInterval:this.configuration.heartbeatInterval,clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,workerLogLevel:this.configuration.workerLogLevel};this.parsedAccessToken(e).then((s=>{t.preProcessedToken=s,t.accessToken=e})).then((()=>this.scheduleEventPost(t)))}disconnect(){this.scheduleEventPost({type:"client-disconnect",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,workerLogLevel:this.configuration.workerLogLevel})}terminate(){this.scheduleEventPost({type:"client-unregister",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,workerLogLevel:this.configuration.workerLogLevel})}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/heartbeat")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;this.configuration.logger.debug("SubscriptionWorkerMiddleware","Process request with SharedWorker transport.");const s={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,request:e,workerLogLevel:this.configuration.workerLogLevel};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,identifier:e.identifier,workerLogLevel:this.configuration.workerLogLevel};this.scheduleEventPost(t)}}),[new Promise(((t,n)=>{this.callbacks.set(e.identifier,{resolve:t,reject:n}),this.parsedAccessTokenForRequest(e).then((e=>s.preProcessedToken=e)).then((()=>this.scheduleEventPost(s)))})),t]}request(e){return e}scheduleEventPost(e,t=!1){const s=this.sharedSubscriptionWorker;s?s.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||0===this.workerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.workerEventsQueue.forEach((t=>e.port.postMessage(t))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){if("undefined"!=typeof SharedWorker){try{this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`)}catch(e){throw this.configuration.logger.error("SubscriptionWorkerMiddleware",(()=>({messageType:"error",message:e}))),e}this.subscriptionWorker.port.start(),this.scheduleEventPost({type:"client-register",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,heartbeatInterval:this.configuration.heartbeatInterval,workerOfflineClientsCheckInterval:this.configuration.workerOfflineClientsCheckInterval,workerUnsubscribeOfflineClients:this.configuration.workerUnsubscribeOfflineClients,workerLogLevel:this.configuration.workerLogLevel},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e),this.shouldAnnounceNewerSharedWorkerVersionAvailability()&&localStorage.setItem("PNSubscriptionSharedWorkerVersion",this.configuration.sdkVersion),window.addEventListener("storage",(e=>{"PNSubscriptionSharedWorkerVersion"===e.key&&e.newValue&&this._emitStatus&&this.isNewerSharedWorkerVersion(e.newValue)&&this._emitStatus({error:!1,category:h.PNSharedWorkerUpdatedCategory})}))}}handleWorkerEvent(e){const{data:t}=e;if("shared-worker-ping"===t.type||"shared-worker-connected"===t.type||"shared-worker-console-log"===t.type||"shared-worker-console-dir"===t.type||t.clientIdentifier===this.configuration.clientIdentifier)if("shared-worker-connected"===t.type)this.configuration.logger.trace("SharedWorker","Ready for events processing."),this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if("shared-worker-console-log"===t.type)this.configuration.logger.debug("SharedWorker",(()=>"string"==typeof t.message||"number"==typeof t.message||"boolean"==typeof t.message?{messageType:"text",message:t.message}:t.message));else if("shared-worker-console-dir"===t.type)this.configuration.logger.debug("SharedWorker",(()=>({messageType:"object",message:t.data,details:t.message?t.message:void 0})));else if("shared-worker-ping"===t.type){const{subscriptionKey:e,clientIdentifier:t}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:e,clientIdentifier:t,workerLogLevel:this.configuration.workerLogLevel})}else if("request-process-success"===t.type||"request-process-error"===t.type)if(this.callbacks.has(t.identifier)){const{resolve:e,reject:s}=this.callbacks.get(t.identifier);this.callbacks.delete(t.identifier),"request-process-success"===t.type?e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body}):s(this.errorFromRequestSendingError(t))}else this._emitStatus&&t.url.indexOf("/v2/presence")>=0&&t.url.indexOf("/heartbeat")>=0&&("request-process-success"===t.type&&this.configuration.announceSuccessfulHeartbeats?this._emitStatus({statusCode:t.response.status,error:!1,operation:$e.PNHeartbeatOperation,category:h.PNAcknowledgmentCategory}):"request-process-error"===t.type&&this.configuration.announceFailedHeartbeats&&this._emitStatus(this.errorFromRequestSendingError(t).toStatus($e.PNHeartbeatOperation)))}parsedAccessTokenForRequest(e){return i(this,void 0,void 0,(function*(){var t;return this.parsedAccessToken(e.queryParameters?null!==(t=e.queryParameters.auth)&&void 0!==t?t:"":void 0)}))}parsedAccessToken(e){return i(this,void 0,void 0,(function*(){if(e)return this.accessTokensMap[e]?this.accessTokensMap[e]:this.stringifyAccessToken(e).then((([t,s])=>{if(t&&s)return(this.accessTokensMap={[e]:{token:s,expiration:t.timestamp+60*t.ttl}})[e]}))}))}stringifyAccessToken(e){return i(this,void 0,void 0,(function*(){if(!this.configuration.tokenManager)return[void 0,void 0];const t=this.configuration.tokenManager.parseToken(e);if(!t)return[void 0,void 0];const s=e=>e?Object.entries(e).sort((([e],[t])=>e.localeCompare(t))).map((([e,t])=>Object.entries(t||{}).sort((([e],[t])=>e.localeCompare(t))).map((([t,s])=>{return`${e}:${t}=${s?(n=s,Object.entries(n).filter((([e,t])=>t)).map((([e])=>e[0])).sort().join("")):""}`;var n})).join(","))).join(";"):"";let n=[s(t.resources),s(t.patterns),t.authorized_uuid].filter(Boolean).join("|");if("undefined"!=typeof crypto&&crypto.subtle){const e=yield crypto.subtle.digest("SHA-256",(new TextEncoder).encode(n));n=String.fromCharCode(...Array.from(new Uint8Array(e)))}return[t,"undefined"!=typeof btoa?btoa(n):n]}))}errorFromRequestSendingError(e){let t=h.PNUnknownCategory,s="Unknown error";if(e.error)"NETWORK_ISSUE"===e.error.type?t=h.PNNetworkIssuesCategory:"TIMEOUT"===e.error.type?t=h.PNTimeoutCategory:"ABORTED"===e.error.type&&(t=h.PNCancelledCategory),s=`${e.error.message} (${e.identifier})`;else if(e.response){const{url:t,response:s}=e;return De.create({url:t,headers:s.headers,body:s.body,status:s.status},s.body)}return new De(s,t,0,new Error(s))}shouldAnnounceNewerSharedWorkerVersionAvailability(){const e=localStorage.getItem("PNSubscriptionSharedWorkerVersion");return!e||!this.isNewerSharedWorkerVersion(e)}isNewerSharedWorkerVersion(e){const[t,s,n]=this.configuration.sdkVersion.split(".").map(Number),[r,i,a]=e.split(".").map(Number);return r>t||i>s||a>n}}function xe(e,t=0){const s=e=>"object"==typeof e&&null!==e&&e.constructor===Object,n=e=>"number"==typeof e&&isFinite(e);if(!s(e))return e;const r={};return Object.keys(e).forEach((i=>{const a=(e=>"string"==typeof e||e instanceof String)(i);let o=i;const c=e[i];if(t<2)if(a&&i.indexOf(",")>=0){o=i.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(n(i)||a&&!isNaN(Number(i)))&&(o=String.fromCharCode(n(i)?i:parseInt(i,10)));r[o]=s(c)?xe(c,t+1):c})),r}const qe=e=>{var t,s,n,r,i,a;return e.subscriptionWorkerUrl&&"undefined"==typeof SharedWorker&&(e.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,s,n,r,i,a,o,c,u,l,h,p,g,b,y;const m=Object.assign({},e);if(null!==(t=m.ssl)&&void 0!==t||(m.ssl=!0),null!==(s=m.transactionalRequestTimeout)&&void 0!==s||(m.transactionalRequestTimeout=15),null!==(n=m.subscribeRequestTimeout)&&void 0!==n||(m.subscribeRequestTimeout=310),null!==(r=m.fileRequestTimeout)&&void 0!==r||(m.fileRequestTimeout=300),null!==(i=m.restore)&&void 0!==i||(m.restore=!0),null!==(a=m.useInstanceId)&&void 0!==a||(m.useInstanceId=!1),null!==(o=m.suppressLeaveEvents)&&void 0!==o||(m.suppressLeaveEvents=!1),null!==(c=m.requestMessageCountThreshold)&&void 0!==c||(m.requestMessageCountThreshold=100),null!==(u=m.autoNetworkDetection)&&void 0!==u||(m.autoNetworkDetection=!1),null!==(l=m.enableEventEngine)&&void 0!==l||(m.enableEventEngine=!0),null!==(h=m.maintainPresenceState)&&void 0!==h||(m.maintainPresenceState=!0),null!==(p=m.useSmartHeartbeat)&&void 0!==p||(m.useSmartHeartbeat=!1),null!==(g=m.keepAlive)&&void 0!==g||(m.keepAlive=!1),m.userId&&m.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(b=m.userId)&&void 0!==b||(m.userId=m.uuid),!m.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(y=m.userId)||void 0===y?void 0:y.trim().length))throw new d("PubNub client configuration error: 'userId' is empty");m.origin||(m.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const f={subscribeKey:m.subscribeKey,publishKey:m.publishKey,secretKey:m.secretKey};void 0!==m.presenceTimeout&&(m.presenceTimeout>320?(m.presenceTimeout=320,console.warn("WARNING: Presence timeout is larger than the maximum. Using maximum value: ",320)):m.presenceTimeout<=0&&(console.warn("WARNING: Presence timeout should be larger than zero."),delete m.presenceTimeout)),void 0!==m.presenceTimeout?m.heartbeatInterval=m.presenceTimeout/2-1:m.presenceTimeout=300;let v=!1,O=!0,S=5,j=!1,w=100,k=!0;return void 0!==m.dedupeOnSubscribe&&"boolean"==typeof m.dedupeOnSubscribe&&(j=m.dedupeOnSubscribe),void 0!==m.maximumCacheSize&&"number"==typeof m.maximumCacheSize&&(w=m.maximumCacheSize),void 0!==m.useRequestId&&"boolean"==typeof m.useRequestId&&(k=m.useRequestId),void 0!==m.announceSuccessfulHeartbeats&&"boolean"==typeof m.announceSuccessfulHeartbeats&&(v=m.announceSuccessfulHeartbeats),void 0!==m.announceFailedHeartbeats&&"boolean"==typeof m.announceFailedHeartbeats&&(O=m.announceFailedHeartbeats),void 0!==m.fileUploadPublishRetryLimit&&"number"==typeof m.fileUploadPublishRetryLimit&&(S=m.fileUploadPublishRetryLimit),Object.assign(Object.assign({},m),{keySet:f,dedupeOnSubscribe:j,maximumCacheSize:w,useRequestId:k,announceSuccessfulHeartbeats:v,announceFailedHeartbeats:O,fileUploadPublishRetryLimit:S})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,subscriptionWorkerUrl:e.subscriptionWorkerUrl,subscriptionWorkerOfflineClientsCheckInterval:null!==(s=e.subscriptionWorkerOfflineClientsCheckInterval)&&void 0!==s?s:10,subscriptionWorkerUnsubscribeOfflineClients:null!==(n=e.subscriptionWorkerUnsubscribeOfflineClients)&&void 0!==n&&n,subscriptionWorkerLogVerbosity:null!==(r=e.subscriptionWorkerLogVerbosity)&&void 0!==r&&r,transport:null!==(i=e.transport)&&void 0!==i?i:"fetch",keepAlive:null===(a=e.keepAlive)||void 0===a||a})};var Le;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warn=3]="Warn",e[e.Error=4]="Error",e[e.None=5]="None"}(Le||(Le={}));class Ge{debug(e){this.log(e)}error(e){this.log(e)}info(e){this.log(e)}trace(e){this.log(e)}warn(e){this.log(e)}toString(){return"ConsoleLogger {}"}log(e){const t=Le[e.level],s=t.toLowerCase();console["trace"===s?"debug":s](`${e.timestamp.toISOString()} PubNub-${e.pubNubId} ${t.padEnd(5," ")}${e.location?` ${e.location}`:""} ${this.logMessage(e)}`)}logMessage(e){if("text"===e.messageType)return e.message;if("object"===e.messageType)return`${e.details?`${e.details}\n`:""}${this.formattedObject(e)}`;if("network-request"===e.messageType){const t=!!e.canceled||!!e.failed,s=e.minimumLevel!==Le.Trace||t?void 0:this.formattedHeaders(e),n=e.message,r=n.queryParameters&&Object.keys(n.queryParameters).length>0?je(n.queryParameters):void 0,i=`${n.origin}${n.path}${r?`?${r}`:""}`,a=t?void 0:this.formattedBody(e);let o="Sending";t&&(o=`${e.canceled?"Canceled":"Failed"}${e.details?` (${e.details})`:""}`);const c=((null==a?void 0:a.formData)?"FormData":"Method").length;return`${o} HTTP request:\n ${this.paddedString("Method",c)}: ${n.method}\n ${this.paddedString("URL",c)}: ${i}${s?`\n ${this.paddedString("Headers",c)}:\n${s}`:""}${(null==a?void 0:a.formData)?`\n ${this.paddedString("FormData",c)}:\n${a.formData}`:""}${(null==a?void 0:a.body)?`\n ${this.paddedString("Body",c)}:\n${a.body}`:""}`}if("network-response"===e.messageType){const t=e.minimumLevel===Le.Trace?this.formattedHeaders(e):void 0,s=this.formattedBody(e),n=((null==s?void 0:s.formData)?"Headers":"Status").length,r=e.message;return`Received HTTP response:\n ${this.paddedString("URL",n)}: ${r.url}\n ${this.paddedString("Status",n)}: ${r.status}${e.details?`\n ${this.paddedString("Details",n)}: ${e.details}`:""}${t?`\n ${this.paddedString("Headers",n)}:\n${t}`:""}${(null==s?void 0:s.body)?`\n ${this.paddedString("Body",n)}:\n${s.body}`:""}`}if("error"===e.messageType){const t=this.formattedErrorStatus(e),s=e.message;return`${s.name}: ${s.message}${t?`\n${t}`:""}`}return""}formattedObject(e){const t=(s,n=1,r=!1)=>{const i=10===n,a=" ".repeat(2*n),o=[],c=(t,s)=>!!e.ignoredKeys&&("function"==typeof e.ignoredKeys?e.ignoredKeys(t,s):e.ignoredKeys.includes(t));if("string"==typeof s)o.push(`${a}- ${s}`);else if("number"==typeof s)o.push(`${a}- ${s}`);else if("boolean"==typeof s)o.push(`${a}- ${s}`);else if(null===s)o.push(`${a}- null`);else if(void 0===s)o.push(`${a}- undefined`);else if("function"==typeof s)o.push(`${a}- `);else if("object"==typeof s)if(Array.isArray(s)||"function"!=typeof s.toString||0===s.toString().indexOf("[object"))if(Array.isArray(s))for(const e of s){const s=r?"":a;if(null===e)o.push(`${s}- null`);else if(void 0===e)o.push(`${s}- undefined`);else if("function"==typeof e)o.push(`${s}- `);else if("object"==typeof e){const r=Array.isArray(e),a=i?"...":t(e,n+1,!r);o.push(`${s}-${r&&!i?"\n":" "}${a}`)}else o.push(`${s}- ${e}`);r=!1}else{const e=s,u=Object.keys(e),l=u.reduce(((t,s)=>Math.max(t,c(s,e)?t:s.length)),0);for(const s of u){if(c(s,e))continue;const u=r?"":a,h=e[s],d=s.padEnd(l," ");if(null===h)o.push(`${u}${d}: null`);else if(void 0===h)o.push(`${u}${d}: undefined`);else if("function"==typeof h)o.push(`${u}${d}: `);else if("object"==typeof h){const e=Array.isArray(h),s=e&&0===h.length,r=!(e||h instanceof String||0!==Object.keys(h).length),a=!e&&"function"==typeof h.toString&&0!==h.toString().indexOf("[object"),c=i?"...":s?"[]":r?"{}":t(h,n+1,a);o.push(`${u}${d}:${i||a||s||r?" ":"\n"}${c}`)}else o.push(`${u}${d}: ${h}`);r=!1}}else o.push(`${r?"":a}${s.toString()}`),r=!1;return o.join("\n")};return t(e.message)}formattedHeaders(e){if(!e.message.headers)return;const t=e.message.headers,s=Object.keys(t).reduce(((e,t)=>Math.max(e,t.length)),0);return Object.keys(t).map((e=>` - ${e.toLowerCase().padEnd(s," ")}: ${t[e]}`)).join("\n")}formattedBody(e){var t;if(!e.message.headers)return;let s,n;const r=e.message.headers,i=null!==(t=r["content-type"])&&void 0!==t?t:r["Content-Type"],a="formData"in e.message?e.message.formData:void 0,o=e.message.body;if(a){const e=a.reduce(((e,{key:t})=>Math.max(e,t.length)),0);s=a.map((({key:t,value:s})=>` - ${t.padEnd(e," ")}: ${s}`)).join("\n")}return o?(n="string"==typeof o?` ${o}`:o instanceof ArrayBuffer||"[object ArrayBuffer]"===Object.prototype.toString.call(o)?!i||-1===i.indexOf("javascript")&&-1===i.indexOf("json")?` ArrayBuffer { byteLength: ${o.byteLength} }`:` ${Ge.decoder.decode(o)}`:` File { name: ${o.name}${o.contentLength?`, contentLength: ${o.contentLength}`:""}${o.mimeType?`, mimeType: ${o.mimeType}`:""} }`,{body:n,formData:s}):{formData:s}}formattedErrorStatus(e){if(!e.message.status)return;const t=e.message.status,s=t.errorData;let n;if(Ge.isError(s))n=` ${s.name}: ${s.message}`,s.stack&&(n+=`\n${s.stack.split("\n").map((e=>` ${e}`)).join("\n")}`);else if(s)try{n=` ${JSON.stringify(s)}`}catch(e){n=` ${s}`}return` Category : ${t.category}\n Operation : ${t.operation}\n Status : ${t.statusCode}${n?`\n Error data:\n${n}`:""}`}paddedString(e,t){return e.padEnd(t-e.length," ")}static isError(e){return!!e&&(e instanceof Error||"[object Error]"===Object.prototype.toString.call(e))}}Ge.decoder=new TextDecoder;const Ke=[404,409];var He;!function(e){e.Unknown="UnknownEndpoint",e.MessageSend="MessageSendEndpoint",e.Subscribe="SubscribeEndpoint",e.Presence="PresenceEndpoint",e.Files="FilesEndpoint",e.MessageStorage="MessageStorageEndpoint",e.ChannelGroups="ChannelGroupsEndpoint",e.DevicePushNotifications="DevicePushNotificationsEndpoint",e.AppContext="AppContextEndpoint",e.MessageReactions="MessageReactionsEndpoint"}(He||(He={}));class Ve{static None(){return{shouldRetry:(e,t,s,n,r)=>!1,getDelay:(e,t)=>-1,validate:()=>!0}}static LinearRetryPolicy(e){var t;return{delay:e.delay,maximumRetry:e.maximumRetry,excluded:null!==(t=e.excluded)&&void 0!==t?t:[],shouldRetry(e,t,s,n,r){return We(e,t,s,null!=n?n:0,this.maximumRetry,this.excluded,r)},getDelay(e,t){let s=-1;return t&&void 0!==t.headers["retry-after"]&&(s=parseInt(t.headers["retry-after"],10)),-1===s&&(s=this.delay),1e3*(s+Math.random())},validate(){if(this.delay<2)throw new Error("Delay can not be set less than 2 seconds for retry")}}}static ExponentialRetryPolicy(e){var t;return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,excluded:null!==(t=e.excluded)&&void 0!==t?t:[],shouldRetry(e,t,s,n,r){return We(e,t,s,null!=n?n:0,this.maximumRetry,this.excluded,r)},getDelay(e,t){let s=-1;return t&&void 0!==t.headers["retry-after"]&&(s=parseInt(t.headers["retry-after"],10)),-1===s&&(s=Math.min(this.minimumDelay*Math.pow(2,e),this.maximumDelay)),1e3*(s+Math.random())},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry")}}}}const We=(e,t,s,n,r,i,a)=>{var o;if(s&&(s===h.PNCancelledCategory||s===h.PNBadRequestCategory||s===h.PNAccessDeniedCategory))return!1;if(Be(e,i))return!1;if(n>r)return!1;const c=null!==(o=null==t?void 0:t.status)&&void 0!==o?o:a;return(void 0===c||!Ke.includes(c))&&(!t||(429===t.status||t.status>=500))},Be=(e,t)=>!!(t&&t.length>0)&&t.includes(ze(e)),ze=e=>{let t=He.Unknown;return e.path.startsWith("/v2/subscribe")?t=He.Subscribe:e.path.startsWith("/publish/")||e.path.startsWith("/signal/")?t=He.MessageSend:e.path.startsWith("/v2/presence")?t=He.Presence:e.path.startsWith("/v2/history")||e.path.startsWith("/v3/history")?t=He.MessageStorage:e.path.startsWith("/v1/message-actions/")?t=He.MessageReactions:e.path.startsWith("/v1/channel-registration/")||e.path.startsWith("/v2/objects/")?t=He.ChannelGroups:e.path.startsWith("/v1/push/")||e.path.startsWith("/v2/push/")?t=He.DevicePushNotifications:e.path.startsWith("/v1/files/")&&(t=He.Files),t};class Je{constructor(e,t,s){this.previousEntryTimestamp=0,this.pubNubId=e,this.minLogLevel=t,this.loggers=s}get logLevel(){return this.minLogLevel}trace(e,t){this.log(Le.Trace,e,t)}debug(e,t){this.log(Le.Debug,e,t)}info(e,t){this.log(Le.Info,e,t)}warn(e,t){this.log(Le.Warn,e,t)}error(e,t){this.log(Le.Error,e,t)}log(e,t,s){if(ee[r](i)))}}var Ye={exports:{}}; +/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",s={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};function n(){var e,t,s="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(s+="-"),s+=(12===e?4:16===e?3&t|8:t).toString(16);return s}function r(e,t){var n=s[t||"all"];return n&&n.test(e)||!1}n.isUUID=r,n.VERSION=t,e.uuid=n,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(Ye,Ye.exports);var Xe=t(Ye.exports),Qe={createUUID:()=>Xe.uuid?Xe.uuid():Xe()};const Ze=(e,t)=>{var s,n,r,i;!e.retryConfiguration&&e.enableEventEngine&&(e.retryConfiguration=Ve.ExponentialRetryPolicy({minimumDelay:2,maximumDelay:150,maximumRetry:6,excluded:[He.MessageSend,He.Presence,He.Files,He.MessageStorage,He.ChannelGroups,He.DevicePushNotifications,He.AppContext,He.MessageReactions]}));const a=`pn-${Qe.createUUID()}`;e.logVerbosity?e.logLevel=Le.Debug:void 0===e.logLevel&&(e.logLevel=Le.None);const o=new Je(tt(a),e.logLevel,[...null!==(s=e.loggers)&&void 0!==s?s:[],new Ge]);void 0!==e.logVerbosity&&o.warn("Configuration","'logVerbosity' is deprecated. Use 'logLevel' instead."),null===(n=e.retryConfiguration)||void 0===n||n.validate();const c=e.useRandomIVs;null!==(r=e.useRandomIVs)&&void 0!==r||(e.useRandomIVs=true),void 0!==c&&(o.warn("Configuration","'useRandomIVs' is deprecated. Pass it to 'cryptoModule' instead."),!1===c&&o.warn("Configuration","Setting 'useRandomIVs' to false is insecure and should only be used to support legacy clients.\n Do not disable random IVs in new applications.")),e.origin=et(null!==(i=e.ssl)&&void 0!==i&&i,e.origin);const u=e.cryptoModule;u&&delete e.cryptoModule;const l=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_loggerManager:o,_instanceId:a,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(e.useInstanceId)return this._instanceId},getInstanceId(){if(e.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},logger(){return this._loggerManager},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt(),logger:this.logger()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,isSharedWorkerEnabled:()=>"Web"===e.sdkFamily&&e.subscriptionWorkerUrl,getKeepPresenceChannelsInPresenceRequests:()=>"Web"===e.sdkFamily&&e.subscriptionWorkerUrl,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},getFileTimeout(){return this.fileRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"13.1.2"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?(o.warn("Configuration","'cipherKey' is deprecated. Use 'cryptoModule' instead."),l.setCipherKey(e.cipherKey)):u&&(l._cryptoModule=u),l},et=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`},tt=e=>{let t=2166136261;for(let s=0;s>>0;return t.toString(16).padStart(8,"0")};class st{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){var t,s;const n=this.cbor.decodeToken(e);if(void 0!==n){const e=n.res.uuid?Object.keys(n.res.uuid):[],r=n.res.usr?Object.keys(n.res.usr):[],i=Object.keys(n.res.chan),a=Object.keys(n.res.grp),o=n.pat.uuid?Object.keys(n.pat.uuid):[],c=n.pat.usr?Object.keys(n.pat.usr):[],u=Object.keys(n.pat.chan),l=Object.keys(n.pat.grp),h={version:n.v,timestamp:n.t,ttl:n.ttl,authorized_uuid:n.uuid,signature:n.sig},d=e.length>0,p=r.length>0,g=i.length>0,b=a.length>0;if(d||p||g||b){if(h.resources={},d){const t=h.resources.uuids={};e.forEach((e=>t[e]=this.extractPermissions(n.res.uuid[e])))}if(p){const e=h.resources.users={};r.forEach((t=>e[t]=this.extractCrudPermissions(n.res.usr[t])))}if(g){const e=h.resources.channels={};i.forEach((t=>e[t]=this.extractPermissions(n.res.chan[t])))}if(b){const e=h.resources.groups={};a.forEach((t=>e[t]=this.extractPermissions(n.res.grp[t])))}}const y=this.extractDataSyncScopes(n.res);y&&((null!==(t=h.resources)&&void 0!==t?t:h.resources={}).dataSync=y);const m=o.length>0,f=c.length>0,v=u.length>0,O=l.length>0;if(m||f||v||O){if(h.patterns={},m){const e=h.patterns.uuids={};o.forEach((t=>e[t]=this.extractPermissions(n.pat.uuid[t])))}if(f){const e=h.patterns.users={};c.forEach((t=>e[t]=this.extractCrudPermissions(n.pat.usr[t])))}if(v){const e=h.patterns.channels={};u.forEach((t=>e[t]=this.extractPermissions(n.pat.chan[t])))}if(O){const e=h.patterns.groups={};l.forEach((t=>e[t]=this.extractPermissions(n.pat.grp[t])))}}const S=this.extractDataSyncScopes(n.pat);S&&((null!==(s=h.patterns)&&void 0!==s?s:h.patterns={}).dataSync=S);const j=this.extractCategories(n.cat);return j&&(h.categories=j),n.meta&&Object.keys(n.meta).length>0&&(h.meta=n.meta),h}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}extractCategories(e){if(!e)return;const t={};return"number"==typeof e.chan&&(t.channels={get:!(32&~e.chan)}),"number"==typeof e.uuid&&(t.uuids={get:!(32&~e.uuid)}),Object.keys(t).length>0?t:void 0}extractDataSyncScopes(e){let t;return[["entities","datasync:entities"],["relationships","datasync:relationships"],["memberships","datasync:memberships"]].forEach((([s,n])=>{const r=e[n];if(!r)return;const i=Object.keys(r);if(0===i.length)return;const a=(null!=t?t:t={})[s]={};i.forEach((e=>a[e]=this.extractCrudPermissions(r[e])))})),t}extractCrudPermissions(e){return{create:!(16&~e),get:!(32&~e),update:!(64&~e),delete:!(8&~e)}}}var nt;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.PUT="PUT",e.DELETE="DELETE",e.LOCAL="LOCAL"}(nt||(nt={}));class rt{constructor(e,t,s,n){this.publishKey=e,this.secretKey=t,this.hasher=s,this.logger=n}signature(e){const t=e.path.startsWith("/publish")?nt.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===nt.POST||t===nt.PATCH||t===nt.PUT){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=rt.textDecoder.decode(t):t&&"object"!=typeof t&&(n=t),n&&(s+=n)}return this.logger.trace("RequestSignature",(()=>({messageType:"text",message:`Request signature input:\n${s}`}))),`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((e=>`${t}=${fe(e)}`)).join("&"):`${t}=${fe(s)}`})).join("&")}}rt.textDecoder=new TextDecoder("utf-8");class it{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new rt(t.publishKey,t.secretKey,s,this.logger))}get logger(){return this.configuration.clientConfiguration.logger()}makeSendable(e){const t=this.configuration.clientConfiguration.retryConfiguration,s=this.configuration.transport;if(void 0!==t){let n,r,i=!1,a=0;const o={abort:e=>{i=!0,n&&clearTimeout(n),r&&r.abort(e)}};return[new Promise(((o,c)=>{const u=()=>{if(i)return;const[l,h]=s.makeSendable(this.request(e));r=h;const d=(s,r)=>{let i=-1;t.shouldRetry(e,s,null==r?void 0:r.category,a+1,null==r?void 0:r.statusCode)&&(i=t.getDelay(a,s)),i>0?(a++,this.logger.warn("PubNubMiddleware",`HTTP request retry #${a} in ${i}ms.`),n=setTimeout((()=>u()),i)):s?o(s):r&&c(r)};l.then((e=>d(e))).catch((e=>d(void 0,e)))};u()})),r?o:void 0]}return s.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.getInstanceId()),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,r=null!==(t=n&&n.getToken())&&void 0!==t?t:s.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class at{constructor(e,t="fetch"){this.logger=e,this.transport=t,e.debug("WebTransport",`Create with configuration:\n - transport: ${t}`),"fetch"===t&&"undefined"==typeof fetch&&(e.warn("WebTransport",`'${t}' not supported in this browser. Fallback to the 'xhr' transport.`),this.transport="xhr"),"fetch"===this.transport&&(at.originalFetch=at.getOriginalFetch(),this.isFetchMonkeyPatched()&&e.warn("WebTransport","Native Web Fetch API 'fetch' function monkey patched."))}makeSendable(e){const t=new AbortController,s={abortController:t,abort:e=>{t.signal.aborted||(this.logger.trace("WebTransport",`On-demand request aborting: ${e}`),t.abort(e))}};return[this.webTransportRequestFromTransportRequest(e).then((t=>(this.logger.debug("WebTransport",(()=>({messageType:"network-request",message:e}))),this.sendRequest(t,s).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const s=e[1].byteLength>0?e[1]:void 0,{status:n,headers:r}=e[0],i={};r.forEach(((e,t)=>i[t]=e.toLowerCase()));const a={status:n,url:t.url,headers:i,body:s};if(this.logger.debug("WebTransport",(()=>({messageType:"network-response",message:a}))),n>=400)throw De.create(a);return a})).catch((t=>{const s=("string"==typeof t?t:t.message).toLowerCase();let n="string"==typeof t?new Error(t):t;throw s.includes("timeout")?this.logger.warn("WebTransport",(()=>({messageType:"network-request",message:e,details:"Timeout",canceled:!0}))):s.includes("cancel")||s.includes("abort")?(this.logger.debug("WebTransport",(()=>({messageType:"network-request",message:e,details:"Aborted",canceled:!0}))),n=new Error("Aborted"),n.name="AbortError"):s.includes("network")?this.logger.warn("WebTransport",(()=>({messageType:"network-request",message:e,details:"Network error",failed:!0}))):this.logger.warn("WebTransport",(()=>({messageType:"network-request",message:e,details:De.create(n).message,failed:!0}))),De.create(n)}))))),s]}request(e){return e}sendRequest(e,t){return i(this,void 0,void 0,(function*(){return"fetch"===this.transport?this.sendFetchRequest(e,t):this.sendXHRRequest(e,t)}))}sendFetchRequest(e,t){return i(this,void 0,void 0,(function*(){let s;const n=new Promise(((n,r)=>{s=setTimeout((()=>{clearTimeout(s),r(new Error("Request timeout")),t.abort("Cancel because of timeout")}),1e3*e.timeout)})),r=new Request(e.url,{method:e.method,headers:e.headers,redirect:"follow",body:e.body});return Promise.race([at.originalFetch(r,{signal:t.abortController.signal,credentials:"omit",cache:"no-cache"}).then((e=>(s&&clearTimeout(s),e))),n])}))}sendXHRRequest(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((s,n)=>{var r;const i=new XMLHttpRequest;i.open(e.method,e.url,!0);let a=!1;i.responseType="arraybuffer",i.timeout=1e3*e.timeout,t.abortController.signal.onabort=()=>{i.readyState!=XMLHttpRequest.DONE&&i.readyState!=XMLHttpRequest.UNSENT&&(a=!0,i.abort())},Object.entries(null!==(r=e.headers)&&void 0!==r?r:{}).forEach((([e,t])=>i.setRequestHeader(e,t))),i.onabort=()=>{n(new Error("Aborted"))},i.ontimeout=()=>{n(new Error("Request timeout"))},i.onerror=()=>{if(!a){const t=this.transportResponseFromXHR(e.url,i);n(new Error(De.create(t).message))}},i.onload=()=>{const e=new Headers;i.getAllResponseHeaders().split("\r\n").forEach((t=>{const[s,n]=t.split(": ");s.length>1&&n.length>1&&e.append(s,n)})),s(new Response(i.response,{status:i.status,headers:e,statusText:i.statusText}))},i.send(e.body)}))}))}webTransportRequestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,s=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const s=e.body,n=new FormData;for(const{key:t,value:s}of e.formData)n.append(t,s);try{const e=yield s.toArrayBuffer();n.append("file",new Blob([e],{type:"application/octet-stream"}),s.name)}catch(e){this.logger.warn("WebTransport",(()=>({messageType:"error",message:e})));try{const e=yield s.toFileUri();n.append("file",e,s.name)}catch(e){this.logger.error("WebTransport",(()=>({messageType:"error",message:e})))}}t=n}else if(e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer))if(e.compressible&&"undefined"!=typeof CompressionStream){const s="string"==typeof e.body?at.encoder.encode(e.body):e.body,n=s.byteLength,r=new ReadableStream({start(e){e.enqueue(s),e.close()}});t=yield new Response(r.pipeThrough(new CompressionStream("deflate"))).arrayBuffer(),this.logger.trace("WebTransport",(()=>{const e=t.byteLength,s=(e/n).toFixed(2);return{messageType:"text",message:`Body of ${n} bytes, compressed by ${s}x to ${e} bytes.`}}))}else t=e.body;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(s=`${s}?${je(e.queryParameters)}`),{url:`${e.origin}${s}`,method:e.method,headers:e.headers,timeout:e.timeout,body:t}}))}isFetchMonkeyPatched(e){return!(null!=e?e:fetch).toString().includes("[native code]")&&"fetch"!==fetch.name}transportResponseFromXHR(e,t){const s=t.getAllResponseHeaders().split("\n"),n={};for(const e of s){const[t,s]=e.trim().split(":");t&&s&&(n[t.toLowerCase()]=s.trim())}return{status:t.status,url:e,headers:n,body:t.response}}static getOriginalFetch(){if("undefined"==typeof document||!document.body)return fetch.bind(globalThis);let e=document.querySelector('iframe[name="pubnub-context-unpatched-fetch"]');return e||(e=document.createElement("iframe"),e.style.display="none",e.name="pubnub-context-unpatched-fetch",e.src="about:blank",document.body.appendChild(e)),e.contentWindow?e.contentWindow.fetch.bind(e.contentWindow):fetch.bind(globalThis)}}at.encoder=new TextEncoder,at.decoder=new TextDecoder;class ot{constructor(e){this.params=e,this.requestIdentifier=Qe.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(e){this&&this.cancellationController&&this.cancellationController.abort(e)}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){return this.deserializeResponse(e)}))}request(){var e,t,s,n,r,i;const a={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:nt.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(n=null===(s=this.params)||void 0===s?void 0:s.cancellable)&&void 0!==n&&n,compressible:null!==(i=null===(r=this.params)||void 0===r?void 0:r.compressible)&&void 0!==i&&i,timeout:10,identifier:this.requestIdentifier},o=this.headers;if(o&&(a.headers=o),a.method===nt.POST||a.method===nt.PATCH||a.method===nt.PUT){const[e,t]=[this.body,this.formData];t&&(a.formData=t),e&&(a.body=e)}return a}get headers(){var e,t;return Object.assign({"Accept-Encoding":"gzip, deflate"},null!==(t=null===(e=this.params)||void 0===e?void 0:e.compressible)&&void 0!==t&&t?{"Content-Encoding":"deflate"}:{})}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=ot.decoder.decode(e.body),s=e.headers["content-type"];let n;if(!s||-1===s.indexOf("javascript")&&-1===s.indexOf("json"))throw new d("Service response error, check status for details",g(t,e.status));try{n=JSON.parse(t)}catch(s){throw console.error("Error parsing JSON response:",s),new d("Service response error, check status for details",g(t,e.status))}if("status"in n&&"number"==typeof n.status&&n.status>=400)throw De.create(e);return n}}ot.decoder=new TextDecoder;var ct;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files",e[e.DataSync=5]="DataSync"}(ct||(ct={}));const ut=new Set([ct.Presence,ct.Message,ct.Signal,ct.AppContext,ct.MessageAction,ct.Files,ct.DataSync]),lt={user:"user",channel:"channel",membership:"membership"};class ht extends ot{constructor(e){var t,s,n,r,i,a;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(s=(i=this.parameters).channelGroups)&&void 0!==s||(i.channelGroups=[]),null!==(n=(a=this.parameters).channels)&&void 0!==n||(a.channels=[])}operation(){return $e.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t,s;try{s=ot.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",g(s,e.status));const n=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;if(e.c.endsWith("-pnpres")?t=ct.Presence:null!=t||(t=ct.Message),!ut.has(t))return;const s=Ce(e.d);if(t!=ct.Presence&&t!=ct.Signal&&"string"==typeof e.d)return t==ct.Message?{type:ct.Message,data:this.messageFromEnvelope(e),pn_mfp:s}:{type:ct.Files,data:this.fileFromEnvelope(e),pn_mfp:s};if(t==ct.Message)return{type:ct.Message,data:this.messageFromEnvelope(e),pn_mfp:s};if(t===ct.Presence)return{type:ct.Presence,data:this.presenceEventFromEnvelope(e),pn_mfp:s};if(t==ct.Signal)return{type:ct.Signal,data:this.signalFromEnvelope(e),pn_mfp:s};if(t===ct.AppContext)return{type:ct.AppContext,data:this.appContextFromEnvelope(e),pn_mfp:s};if(t===ct.MessageAction)return{type:ct.MessageAction,data:this.messageActionFromEnvelope(e),pn_mfp:s};if(t===ct.DataSync){const t=this.dataSyncFromEnvelope(e);return t?{type:ct.DataSync,data:t,pn_mfp:s}:{type:ct.Message,data:this.messageFromEnvelope(e),pn_mfp:s}}return{type:ct.Files,data:this.fileFromEnvelope(e),pn_mfp:s}})).filter((e=>void 0!==e));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:n}}))}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{accept:"text/javascript"})}presenceEventFromEnvelope(e){var t;const{d:s}=e,[n,r]=this.subscriptionChannelFromEnvelope(e),i=n.replace("-pnpres",""),a=null!==r?i:null,o=null!==r?r:i;let c;if("string"==typeof s)try{const e=JSON.parse(s);null===e||"object"!=typeof e||Array.isArray(e)||(c=e)}catch(e){}else c=s;return c&&("data"in c?(c.state=c.data,delete c.data):"action"in c&&"interval"===c.action&&(c.hereNowRefresh=null!==(t=c.here_now_refresh)&&void 0!==t&&t,delete c.here_now_refresh)),Object.assign({channel:i,subscription:r,actualChannel:a,subscribedChannel:o,timetoken:e.p.t},null!=c?c:{})}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d),i={channel:t,subscription:s,actualChannel:null!==s?t:null,subscribedChannel:null!==s?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(i.userMetadata=e.u),e.cmt&&(i.customMessageType=e.cmt),r&&(i.error=r),i}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),e.cmt&&(n.customMessageType=e.cmt),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}dataSyncFromEnvelope(e){var t;const[s,n]=this.subscriptionChannelFromEnvelope(e),r=e.d,i=null==r?void 0:r.metadata;if(!i||"data-sync"!==i.source||!i.event||!i.type)return;const a=i.className?i.className.split(":"):[],o=a.filter((e=>e.length>0)),c=o.length>0?o[o.length-1]:void 0,u=i.classLevel,l=void 0===u?a[0]:"Global"===u?c:void 0,h=("entity"===i.type||"relationship"===i.type)&&l&<[l.toLowerCase()]||i.type,d=void 0!==i.classVersion?Number.parseInt(`${i.classVersion}`,10):NaN,p=Number.isNaN(d)?void 0:d,g=null!==(t=r.data)&&void 0!==t?t:{},b={version:r.version,source:i.source,type:i.type,className:c,classLevel:u,classVersion:p};let y;return y="delete"===i.event?Object.assign(Object.assign({},b),{event:i.event,objectType:h,data:{id:g.id,deletedAt:g.deletedAt}}):Object.assign(Object.assign({},b),{event:i.event,objectType:h,data:Object.assign({},g)}),{channel:s,subscription:n,timetoken:e.p.t,message:y}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d);let i=r;const a={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(a.userMetadata=e.u),n?"string"==typeof n?null!=i||(i="Unexpected file information payload data type."):(a.message=n.message,n.file&&(a.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):null!=i||(i="File information payload is missing."),e.cmt&&(a.customMessageType=e.cmt),i&&(a.error=i),a}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,s;try{const s=this.parameters.crypto.decrypt(e);t=s instanceof ArrayBuffer?JSON.parse(dt.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class dt extends ht{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${ve(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:r,region:i,onDemand:a}=this.parameters,o={};return a&&(o["on-demand"]=1),e&&e.length>0&&(o["channel-group"]=e.sort().join(",")),t&&t.length>0&&(o["filter-expr"]=t),s&&(o.heartbeat=s),n&&Object.keys(n).length>0&&(o.state=JSON.stringify(n)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(o.tt=r):void 0!==r&&r>0&&(o.tt=r),i&&(o.tr=i),o}}class pt{constructor(){this.hasListeners=!1,this.listeners=[{count:-1,listener:{}}]}set onStatus(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"status"})}set onMessage(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"message"})}set onPresence(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"presence"})}set onSignal(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"signal"})}set onObjects(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"objects"})}set onMessageAction(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"messageAction"})}set onFile(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"file"})}set onDataSync(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"dataSync"})}handleEvent(e){if(this.hasListeners)if(e.type===ct.Message)this.announce("message",e.data);else if(e.type===ct.Signal)this.announce("signal",e.data);else if(e.type===ct.Presence)this.announce("presence",e.data);else if(e.type===ct.AppContext){const{data:t}=e,{message:s}=t;if(this.announce("objects",t),"uuid"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:a,type:o}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"user"})});this.announce("user",u)}else if("channel"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:a,type:o}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"space"})});this.announce("space",u)}else if("membership"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:a,data:o}=s,c=r(s,["event","data"]),{uuid:u,channel:l}=o,h=r(o,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.announce("membership",d)}}else e.type===ct.MessageAction?this.announce("messageAction",e.data):e.type===ct.Files?this.announce("file",e.data):e.type===ct.DataSync&&this.announce("dataSync",e.data)}handleStatus(e){this.hasListeners&&this.announce("status",e)}addListener(e){this.updateTypeOrObjectListener({add:!0,listener:e})}removeListener(e){this.updateTypeOrObjectListener({add:!1,listener:e})}removeAllListeners(){this.listeners=[{count:-1,listener:{}}],this.hasListeners=!1}updateTypeOrObjectListener(e){if(e.type)"function"==typeof e.listener?this.listeners[0].listener[e.type]=e.listener:delete this.listeners[0].listener[e.type];else if(e.listener&&"function"!=typeof e.listener){let t,s=!1;for(t of this.listeners)if(t.listener===e.listener){e.add?(t.count++,s=!0):(t.count--,0===t.count&&this.listeners.splice(this.listeners.indexOf(t),1));break}e.add&&!s&&this.listeners.push({count:1,listener:e.listener})}this.hasListeners=this.listeners.length>1||Object.keys(this.listeners[0]).length>0}announce(e,t){this.listeners.forEach((({listener:s})=>{const n=s[e];n&&n(t)}))}}class gt{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class bt{constructor(e){this.config=e,e.logger().debug("DedupingManager",(()=>({messageType:"object",message:{maximumCacheSize:e.maximumCacheSize},details:"Create with configuration:"}))),this.maximumCacheSize=e.maximumCacheSize,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify(null!==(t=e.message)&&void 0!==t?t:"")).toString()}`}isDuplicate(e){return this.hashHistory.includes(this.getKey(e))}addEntry(e){this.hashHistory.length>=this.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}hashCode(e){let t=0;if(0===e.length)return t;for(let s=0;s{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==s||s.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t=!1){let{channels:s,channelGroups:n}=e;const i=new Set,a=new Set;if(null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],a.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],a.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===a.size&&0===i.size)return;const o=this.lastTimetoken,c=this.currentTimetoken;0===Object.keys(this.channels).length&&0===Object.keys(this.presenceChannels).length&&0===Object.keys(this.channelGroups).length&&0===Object.keys(this.presenceChannelGroups).length&&(this.lastTimetoken="0",this.currentTimetoken="0",this.referenceTimetoken=null,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect(!0),!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(i),s=Array.from(a),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,i=r(e,["error"]);let a;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?a=e.errorData.message:"message"in e&&"string"==typeof e.message&&(a=e.message)),this.emitStatus(Object.assign(Object.assign({},i),{error:null!=a&&a,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:c,lastTimetoken:o}))})))}unsubscribeAll(e=!1){this.disconnectedWhileHandledEvent=!0,this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(e=!1){this.disconnectedWhileHandledEvent=!1,this.stopSubscribeLoop();const t=[...Object.keys(this.channelGroups)],s=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((e=>t.push(`${e}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>s.push(`${e}-pnpres`))),0===s.length&&0===t.length||(this.subscribeCall(Object.assign(Object.assign(Object.assign({channels:s,channelGroups:t,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken},null!==this.region?{region:this.region}:{}),this.configuration.filterExpression?{filterExpression:this.configuration.filterExpression}:{}),{onDemand:!this.subscriptionStatusAnnounced||e}),((e,t)=>{this.processSubscribeResponse(e,t)})),!e&&this.configuration.useSmartHeartbeat&&this.startHeartbeatTimer())}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;return void(e.category===h.PNTimeoutCategory?this.startSubscribeLoop():e.category===h.PNNetworkIssuesCategory||e.category===h.PNMalformedResponseCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.emitStatus({category:h.PNNetworkDownCategory})),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.emitStatus({category:h.PNNetworkUpCategory})),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.emitStatus(t)})),this.reconnectionManager.startPolling(),this.emitStatus(Object.assign(Object.assign({},e),{category:h.PNNetworkIssuesCategory}))):e.category===h.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.emitStatus(e)):this.emitStatus(e))}if(this.referenceTimetoken=ke(t.cursor.timetoken,this.storedTimetoken),this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.emitStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:r}=this.configuration;n&&s.length>=n&&this.emitStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{const e={timetoken:this.currentTimetoken,region:this.region?this.region:void 0};this.configuration.logger().debug("SubscriptionManager",(()=>({messageType:"object",message:s.map((e=>({type:e.type,data:Object.assign(Object.assign({},e.data),{pn_mfp:e.pn_mfp})}))),details:"Received events:"}))),s.forEach((t=>{if(r&&"message"in t.data&&"timetoken"in t.data){if(this.dedupingManager.isDuplicate(t.data))return void this.configuration.logger().warn("SubscriptionManager",(()=>({messageType:"object",message:t.data,details:"Duplicate message detected (skipped):"})));this.dedupingManager.addEntry(t.data)}this.emitEvent(e,t)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.emitStatus(t)}this.region=t.cursor.region,this.disconnectedWhileHandledEvent?this.disconnectedWhileHandledEvent=!1:this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;null==s||s.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==n||n.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(null==s||s.forEach((e=>this.heartbeatChannels[e]={})),null==n||n.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==s||s.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==n||n.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:s,channelGroups:n},(e=>this.emitStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.configuration.useSmartHeartbeat||this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.emitStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.emitStatus({category:h.PNNetworkDownCategory}),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.emitStatus(e)}))}}class mt{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class ft extends mt{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,r={topic:t,environment:s};return n.length&&(r.excluded_devices=n),r}}class vt extends mt{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get androidNotification(){var e;return null===(e=this.payload.android)||void 0===e?void 0:e.notification}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this.androidNotification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this.androidNotification.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.androidNotification.notification_count=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.androidNotification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.androidNotification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.androidNotification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={},this.payload.android={notification:{}}}toObject(){var e,t;const s={},n=Object.assign({},this.payload.notification),i=Object.assign({},this.payload.android),a=r(Object.assign({},null!==(e=i.notification)&&void 0!==e?e:{}),["title","body"]);if(this._isSilent){const e={};this._title&&(e.title=this._title),this._body&&(e.body=this._body);for(const[t,s]of Object.entries(a))null!=s&&(e[t]=String(s));this.payload.data&&Object.assign(e,this.payload.data),Object.keys(e).length&&(s.data=e),delete i.notification,Object.keys(i).length&&(s.android=i)}else if(Object.keys(n).length&&(s.notification=n),this.payload.data&&Object.keys(this.payload.data).length&&(s.data=Object.assign({},this.payload.data)),Object.keys(a).length){const e=r(i,["notification"]);s.android=Object.assign(Object.assign({},e),{notification:a})}else{const e=r(i,["notification"]);Object.keys(e).length&&(s.android=e)}const o=r(this.payload,["notification","android","data","pn_exceptions"]);return Object.assign(s,o),(null===(t=this.payload.pn_exceptions)||void 0===t?void 0:t.length)&&(s.pn_exceptions=this.payload.pn_exceptions),Object.keys(s).length?s:null}}class Ot{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new ft(this._payload.apns,e,t),this.fcm=new vt(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_fcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class St{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class jt{transition(e,t){var s;if(this.transitionMap.has(t.type))return null===(s=this.transitionMap.get(t.type))||void 0===s?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class wt extends St{constructor(e){super(!0),this.logger=e,this._pendingEvents=[],this._inTransition=!1}get currentState(){return this._currentState}get currentContext(){return this._currentContext}describe(e){return new jt(e)}start(e,t){this._currentState=e,this._currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this._currentState)throw this.logger.error("Engine","Finite state machine is not started"),new Error("Start the engine first");if(this._inTransition)return this.logger.trace("Engine",(()=>({messageType:"object",message:e,details:"Event engine in transition. Enqueue received event:"}))),void this._pendingEvents.push(e);this._inTransition=!0,this.logger.trace("Engine",(()=>({messageType:"object",message:e,details:"Event engine received event:"}))),this.notify({type:"eventReceived",event:e});const t=this._currentState.transition(this._currentContext,e);if(t){const[s,n,r]=t;this.logger.trace("Engine",`Exiting state: ${this._currentState.label}`);for(const e of this._currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this._currentContext)});this.logger.trace("Engine",(()=>({messageType:"object",details:`Entering '${s.label}' state with context:`,message:n})));const i=this._currentState;this._currentState=s;const a=this._currentContext;this._currentContext=n,this.notify({type:"transitionDone",fromState:i,fromContext:a,toState:s,toContext:n,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this._currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this._currentContext)})}else this.logger.warn("Engine",`No transition from '${this._currentState.label}' found for event: ${e.type}`);if(this._inTransition=!1,this._pendingEvents.length>0){const e=this._pendingEvents.shift();e&&(this.logger.trace("Engine",(()=>({messageType:"object",message:e,details:"De-queueing pending event:"}))),this.transition(e))}}}class kt{constructor(e,t){this.dependencies=e,this.logger=t,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if(this.logger.trace("Dispatcher",`Process invocation: ${e.type}`),"CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw this.logger.error("Dispatcher",`Unhandled invocation '${e.type}'`),new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);this.logger.trace("Dispatcher",(()=>({messageType:"object",details:"Call invocation handler with parameters:",message:e.payload,ignoredKeys:["abortSignal"]}))),e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function Pt(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function Ct(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function Et(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!0});return s.type=e,s.cancel={type:"CANCEL",payload:e,managed:!1},s}class Nt extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class Tt extends St{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new Nt}abort(){this._aborted=!0,this.notify(new Nt)}}class It{constructor(e,t){this.payload=e,this.dependencies=t}}class Rt extends It{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new Tt}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const Mt=e=>(t,s)=>new Rt(t,s,e),Ut=Et("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),_t=Ct("LEAVE",((e,t)=>({channels:e,groups:t}))),Dt=Ct("EMIT_STATUS",(e=>e)),At=Et("WAIT",(()=>({}))),$t=Pt("RECONNECT",(()=>({}))),Ft=Pt("DISCONNECT",((e=!1)=>({isOffline:e}))),xt=Pt("JOINED",((e,t)=>({channels:e,groups:t}))),qt=Pt("LEFT",((e,t)=>({channels:e,groups:t}))),Lt=Pt("LEFT_ALL",((e=!1)=>({isOffline:e}))),Gt=Pt("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),Kt=Pt("HEARTBEAT_FAILURE",(e=>e)),Ht=Pt("TIMES_UP",(()=>({})));class Vt extends kt{constructor(e,t){super(t,t.config.logger()),this.on(Ut.type,Mt(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:r,config:i}){s.throwIfAborted();try{yield n(Object.assign(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Gt(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;e.transition(Kt(t))}}}))))),this.on(_t.type,Mt(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{leave:s,config:n}){if(!n.suppressLeaveEvents)try{s({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(At.type,Mt(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){const{cancelDelay:r,promise:i}=n();s.throwIfAborted();const a=s.subscribe((()=>r()));return yield i,a(),s.throwIfAborted(),e.transition(Ht())}))))),this.on(Dt.type,Mt(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s,config:n}){n.announceFailedHeartbeats&&!0===(null==e?void 0:e.error)?s(Object.assign(Object.assign({},e),{operation:$e.PNHeartbeatOperation})):n.announceSuccessfulHeartbeats&&200===e.statusCode&&s(Object.assign(Object.assign({},e),{error:!1,operation:$e.PNHeartbeatOperation,category:h.PNAcknowledgmentCategory}))})))))}}const Wt=new jt("HEARTBEAT_INACTIVE"),Bt=new jt("HEARTBEATING"),zt=new jt("HEARTBEAT_COOLDOWN"),Jt=new jt("HEARTBEAT_STOPPED"),Yt=new jt("HEARTBEAT_FAILED");Wt.on(xt.type,((e,t)=>Bt.with({channels:t.payload.channels,groups:t.payload.groups}))),Bt.onEnter((e=>Ut(e.channels,e.groups))),Bt.onExit((()=>Ut.cancel)),Bt.on(Gt.type,((e,t)=>zt.with({channels:e.channels,groups:e.groups},[Dt(Object.assign({},t.payload))]))),Bt.on(xt.type,((e,t)=>Bt.with({channels:[...e.channels,...t.payload.channels.filter((t=>!e.channels.includes(t)))],groups:[...e.groups,...t.payload.groups.filter((t=>!e.groups.includes(t)))]}))),Bt.on(qt.type,((e,t)=>Bt.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[_t(t.payload.channels,t.payload.groups)]))),Bt.on(Kt.type,((e,t)=>Yt.with(Object.assign({},e),[...t.payload.status?[Dt(Object.assign({},t.payload.status))]:[]]))),Bt.on(Ft.type,((e,t)=>Jt.with({channels:e.channels,groups:e.groups},[...t.payload.isOffline?[]:[_t(e.channels,e.groups)]]))),Bt.on(Lt.type,((e,t)=>Wt.with(void 0,[...t.payload.isOffline?[]:[_t(e.channels,e.groups)]]))),zt.onEnter((()=>At())),zt.onExit((()=>At.cancel)),zt.on(Ht.type,((e,t)=>Bt.with({channels:e.channels,groups:e.groups}))),zt.on(xt.type,((e,t)=>Bt.with({channels:[...e.channels,...t.payload.channels.filter((t=>!e.channels.includes(t)))],groups:[...e.groups,...t.payload.groups.filter((t=>!e.groups.includes(t)))]}))),zt.on(qt.type,((e,t)=>Bt.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[_t(t.payload.channels,t.payload.groups)]))),zt.on(Ft.type,((e,t)=>Jt.with({channels:e.channels,groups:e.groups},[...t.payload.isOffline?[]:[_t(e.channels,e.groups)]]))),zt.on(Lt.type,((e,t)=>Wt.with(void 0,[...t.payload.isOffline?[]:[_t(e.channels,e.groups)]]))),Jt.on(xt.type,((e,t)=>Jt.with({channels:[...e.channels,...t.payload.channels.filter((t=>!e.channels.includes(t)))],groups:[...e.groups,...t.payload.groups.filter((t=>!e.groups.includes(t)))]}))),Jt.on(qt.type,((e,t)=>Jt.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),Jt.on($t.type,((e,t)=>Bt.with({channels:e.channels,groups:e.groups}))),Jt.on(Lt.type,((e,t)=>Wt.with(void 0))),Yt.on(xt.type,((e,t)=>Bt.with({channels:[...e.channels,...t.payload.channels.filter((t=>!e.channels.includes(t)))],groups:[...e.groups,...t.payload.groups.filter((t=>!e.groups.includes(t)))]}))),Yt.on(qt.type,((e,t)=>Bt.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[_t(t.payload.channels,t.payload.groups)]))),Yt.on($t.type,((e,t)=>Bt.with({channels:e.channels,groups:e.groups}))),Yt.on(Ft.type,((e,t)=>Jt.with({channels:e.channels,groups:e.groups},[...t.payload.isOffline?[]:[_t(e.channels,e.groups)]]))),Yt.on(Lt.type,((e,t)=>Wt.with(void 0,[...t.payload.isOffline?[]:[_t(e.channels,e.groups)]])));class Xt{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.channels=[],this.groups=[],this.engine=new wt(e.config.logger()),this.dispatcher=new Vt(this.engine,e),e.config.logger().debug("PresenceEventEngine","Create presence event engine."),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(Wt,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...(null!=e?e:[]).filter((e=>!this.channels.includes(e)))],this.groups=[...this.groups,...(null!=t?t:[]).filter((e=>!this.groups.includes(e)))],0===this.channels.length&&0===this.groups.length||this.engine.transition(xt(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){e&&(this.channels=this.channels.filter((t=>!e.includes(t)))),t&&(this.groups=this.groups.filter((e=>!t.includes(e)))),this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(qt(null!=e?e:[],null!=t?t:[]))}leaveAll(e=!1){this.dependencies.presenceState&&(this.channels.forEach((e=>delete this.dependencies.presenceState[e])),this.groups.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=[],this.groups=[],this.engine.transition(Lt(e))}reconnect(){this.engine.transition($t())}disconnect(e=!1){this.engine.transition(Ft(e))}dispose(){this.disconnect(!0),this._unsubscribeEngine(),this.dispatcher.dispose()}}const Qt=Pt("SUBSCRIPTION_CHANGED",((e,t,s=!1)=>({channels:e,groups:t,isOffline:s}))),Zt=Pt("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),es=Pt("HANDSHAKE_SUCCESS",(e=>e)),ts=Pt("HANDSHAKE_FAILURE",(e=>e)),ss=Pt("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),ns=Pt("RECEIVE_FAILURE",(e=>e)),rs=Pt("DISCONNECT",((e=!1)=>({isOffline:e}))),is=Pt("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),as=Pt("UNSUBSCRIBE_ALL",(()=>({}))),os=new jt("UNSUBSCRIBED"),cs=new jt("HANDSHAKING"),us=new jt("HANDSHAKE_STOPPED"),ls=new jt("HANDSHAKE_FAILED"),hs=new jt("RECEIVING"),ds=new jt("RECEIVE_STOPPED"),ps=new jt("RECEIVE_FAILED");os.on(Qt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?os.with(void 0):cs.with({channels:t.channels,groups:t.groups,onDemand:!0}))),os.on(Zt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?os.with(void 0):cs.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region},onDemand:!0})));const gs=Et("HANDSHAKE",((e,t,s)=>({channels:e,groups:t,onDemand:s}))),bs=Et("RECEIVE_MESSAGES",((e,t,s,n)=>({channels:e,groups:t,cursor:s,onDemand:n}))),ys=Ct("EMIT_MESSAGES",((e,t)=>({cursor:e,events:t}))),ms=Ct("EMIT_STATUS",(e=>e));cs.onEnter((e=>{var t;return gs(e.channels,e.groups,null!==(t=e.onDemand)&&void 0!==t&&t)})),cs.onExit((()=>gs.cancel)),cs.on(Qt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?os.with(void 0):cs.with({channels:t.channels,groups:t.groups,cursor:e.cursor,onDemand:!0}))),cs.on(es.type,((e,{payload:t})=>{var s,n,r,i,a;return hs.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(s=e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=e.cursor)||void 0===n?void 0:n.timetoken:t.timetoken,region:t.region},referenceTimetoken:ke(t.timetoken,null===(r=e.cursor)||void 0===r?void 0:r.timetoken)},[ms({category:h.PNConnectedCategory,affectedChannels:e.channels.slice(0),affectedChannelGroups:e.groups.slice(0),operation:$e.PNSubscribeOperation,currentTimetoken:(null===(i=e.cursor)||void 0===i?void 0:i.timetoken)?null===(a=e.cursor)||void 0===a?void 0:a.timetoken:t.timetoken})])})),cs.on(ts.type,((e,t)=>{var s;return ls.with(Object.assign(Object.assign({},e),{reason:t.payload}),[ms({category:h.PNConnectionErrorCategory,error:null===(s=t.payload.status)||void 0===s?void 0:s.category})])})),cs.on(rs.type,((e,t)=>{var s;if(t.payload.isOffline){const t=De.create(new Error("Network connection error")).toPubNubError($e.PNSubscribeOperation);return ls.with(Object.assign(Object.assign({},e),{reason:t}),[ms({category:h.PNConnectionErrorCategory,error:null===(s=t.status)||void 0===s?void 0:s.category})])}return us.with(Object.assign({},e))})),cs.on(Zt.type,((e,{payload:t})=>{var s;return 0===t.channels.length&&0===t.groups.length?os.with(void 0):cs.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0},onDemand:!0})})),cs.on(as.type,(e=>os.with())),us.on(Qt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?os.with(void 0):us.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),us.on(is.type,((e,{payload:t})=>cs.with(Object.assign(Object.assign({},e),{cursor:t.cursor||e.cursor,onDemand:!0})))),us.on(Zt.type,((e,{payload:t})=>{var s;return 0===t.channels.length&&0===t.groups.length?os.with(void 0):us.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||(null===(s=e.cursor)||void 0===s?void 0:s.region)||0}})})),us.on(as.type,(e=>os.with())),ls.on(Qt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?os.with(void 0):cs.with({channels:t.channels,groups:t.groups,cursor:e.cursor,onDemand:!0}))),ls.on(is.type,((e,{payload:t})=>cs.with(Object.assign(Object.assign({},e),{cursor:t.cursor||e.cursor,onDemand:!0})))),ls.on(Zt.type,((e,{payload:t})=>{var s,n;return 0===t.channels.length&&0===t.groups.length?os.with(void 0):cs.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region?t.cursor.region:null!==(n=null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)&&void 0!==n?n:0},onDemand:!0})})),ls.on(as.type,(e=>os.with())),hs.onEnter((e=>{var t;return bs(e.channels,e.groups,e.cursor,null!==(t=e.onDemand)&&void 0!==t&&t)})),hs.onExit((()=>bs.cancel)),hs.on(ss.type,((e,{payload:t})=>hs.with({channels:e.channels,groups:e.groups,cursor:t.cursor,referenceTimetoken:ke(t.cursor.timetoken)},[ys(e.cursor,t.events)]))),hs.on(Qt.type,((e,{payload:t})=>{var s;if(0===t.channels.length&&0===t.groups.length){let e;return t.isOffline&&(e=null===(s=De.create(new Error("Network connection error")).toPubNubError($e.PNSubscribeOperation).status)||void 0===s?void 0:s.category),os.with(void 0,[ms(Object.assign({category:t.isOffline?h.PNDisconnectedUnexpectedlyCategory:h.PNDisconnectedCategory,operation:$e.PNUnsubscribeOperation},e?{error:e}:{}))])}return hs.with({channels:t.channels,groups:t.groups,cursor:e.cursor,referenceTimetoken:e.referenceTimetoken,onDemand:!0},[ms({category:h.PNSubscriptionChangedCategory,affectedChannels:t.channels.slice(0),affectedChannelGroups:t.groups.slice(0),currentTimetoken:e.cursor.timetoken})])})),hs.on(Zt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?os.with(void 0,[ms({category:h.PNDisconnectedCategory})]):hs.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||e.cursor.region},referenceTimetoken:ke(e.cursor.timetoken,`${t.cursor.timetoken}`,e.referenceTimetoken),onDemand:!0},[ms({category:h.PNSubscriptionChangedCategory,affectedChannels:t.channels.slice(0),affectedChannelGroups:t.groups.slice(0),currentTimetoken:t.cursor.timetoken})]))),hs.on(ns.type,((e,{payload:t})=>{var s;return ps.with(Object.assign(Object.assign({},e),{reason:t}),[ms({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.status)||void 0===s?void 0:s.category})])})),hs.on(rs.type,((e,t)=>{var s;if(t.payload.isOffline){const t=De.create(new Error("Network connection error")).toPubNubError($e.PNSubscribeOperation);return ps.with(Object.assign(Object.assign({},e),{reason:t}),[ms({category:h.PNDisconnectedUnexpectedlyCategory,operation:$e.PNSubscribeOperation,error:null===(s=t.status)||void 0===s?void 0:s.category})])}return ds.with(Object.assign({},e),[ms({category:h.PNDisconnectedCategory,operation:$e.PNSubscribeOperation})])})),hs.on(as.type,(e=>os.with(void 0,[ms({category:h.PNDisconnectedCategory,operation:$e.PNUnsubscribeOperation})]))),ds.on(Qt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?os.with(void 0):ds.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),ds.on(Zt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?os.with(void 0):ds.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||e.cursor.region}}))),ds.on(is.type,((e,{payload:t})=>{var s;return cs.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.cursor.timetoken?null===(s=t.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.cursor.region||e.cursor.region},onDemand:!0})})),ds.on(as.type,(()=>os.with(void 0))),ps.on(is.type,((e,{payload:t})=>{var s;return cs.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.cursor.timetoken?null===(s=t.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.cursor.region||e.cursor.region},onDemand:!0})})),ps.on(Qt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?os.with(void 0):cs.with({channels:t.channels,groups:t.groups,cursor:e.cursor,onDemand:!0}))),ps.on(Zt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?os.with(void 0):cs.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||e.cursor.region},onDemand:!0}))),ps.on(as.type,(e=>os.with(void 0)));class fs extends kt{constructor(e,t){super(t,t.config.logger()),this.on(gs.type,Mt(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:r,config:i}){s.throwIfAborted();try{const a=yield n(Object.assign(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}),{onDemand:t.onDemand}));return e.transition(es(a))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(ts(t))}}}))))),this.on(bs.type,Mt(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,config:r}){s.throwIfAborted();try{const i=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression,onDemand:t.onDemand});e.transition(ss(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!s.aborted)return e.transition(ns(t))}}}))))),this.on(ys.type,Mt(((e,t,s)=>i(this,[e,t,s],void 0,(function*({cursor:e,events:t},s,{emitMessages:n}){t.length>0&&n(e,t)}))))),this.on(ms.type,Mt(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){return s(e)})))))}}class vs{get _engine(){return this.engine}constructor(e){this.channels=[],this.groups=[],this.dependencies=e,this.engine=new wt(e.config.logger()),this.dispatcher=new fs(this.engine,e),e.config.logger().debug("EventEngine","Create subscribe event engine."),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(os,void 0)}get subscriptionTimetoken(){const e=this.engine.currentState;if(!e)return;let t,s="0";if(e.label===hs.label){const e=this.engine.currentContext;s=e.cursor.timetoken,t=e.referenceTimetoken}return we(s,null!=t?t:"0")}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){var r;const i=null==e?void 0:e.some((e=>!this.channels.includes(e))),a=null==t?void 0:t.some((e=>!this.groups.includes(e))),o=i||a;if(this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],n&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),s)this.engine.transition(Zt(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s));else if(o)this.engine.transition(Qt(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]]))));else{this.dependencies.config.logger().debug("EventEngine","Skipping state transition - all channels/groups already subscribed. Emitting SubscriptionChanged event.");const e=this.engine.currentState,t=this.engine.currentContext;let s="0";if((null==e?void 0:e.label)===hs.label&&t){s=null===(r=t.cursor)||void 0===r?void 0:r.timetoken}this.dependencies.emitStatus({category:h.PNSubscriptionChangedCategory,affectedChannels:Array.from(new Set(this.channels)),affectedChannelGroups:Array.from(new Set(this.groups)),currentTimetoken:s})}this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=Oe(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=Oe(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const r=Se(this.channels,e),i=Se(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=s,this.groups=n,this.engine.transition(Qt(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(e=!1){const t=this.getSubscribedChannelGroups(),s=this.getSubscribedChannels();this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(Qt(this.channels.slice(0),this.groups.slice(0),e)),this.dependencies.leaveAll&&this.dependencies.leaveAll({channels:s,groups:t,isOffline:e})}reconnect({timetoken:e,region:t}){const s=this.getSubscribedChannels(),n=this.getSubscribedChannels();this.engine.transition(is(e,t)),this.dependencies.presenceReconnect&&this.dependencies.presenceReconnect({channels:n,groups:s})}disconnect(e=!1){const t=this.getSubscribedChannels(),s=this.getSubscribedChannels();this.engine.transition(rs(e)),this.dependencies.presenceDisconnect&&this.dependencies.presenceDisconnect({channels:s,groups:t,isOffline:e})}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(!0),this._unsubscribeEngine(),this.dispatcher.dispose()}}class Os extends ot{constructor(e){var t;const s=null!==(t=e.sendByPost)&&void 0!==t&&t;super({method:s?nt.POST:nt.GET,compressible:s}),this.parameters=e,this.parameters.sendByPost=s}operation(){return $e.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${fe(t)}/0${this.parameters.sendByPost?"":`/${fe(n)}`}`}get queryParameters(){const{customMessageType:e,meta:t,replicate:s,storeInHistory:n,ttl:r}=this.parameters,i={};return e&&(i.custom_message_type=e),void 0!==n&&(i.store=n?"1":"0"),void 0!==r&&(i.ttl=r),void 0===s||s||(i.norep="true"),t&&"object"==typeof t&&(i.meta=JSON.stringify(t)),i}get headers(){var e;return this.parameters.sendByPost?Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"}):super.headers}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Ss extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,r=JSON.stringify(n);return`/signal/${e}/${t}/0/${fe(s)}/0/${fe(r)}`}get queryParameters(){const{customMessageType:e}=this.parameters,t={};return e&&(t.custom_message_type=e),t}}class js extends ht{operation(){return $e.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${ve(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n,heartbeat:r,onDemand:i}=this.parameters,a={ee:""};return i&&(a["on-demand"]=1),e&&e.length>0&&(a["channel-group"]=e.sort().join(",")),t&&t.length>0&&(a["filter-expr"]=t),"string"==typeof s?s&&"0"!==s&&s.length>0&&(a.tt=s):s&&s>0&&(a.tt=s),n&&(a.tr=n),r&&(a.heartbeat=r),a}}class ws extends ht{operation(){return $e.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${ve(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,heartbeat:t,filterExpression:s,state:n,onDemand:r}=this.parameters,i={ee:""};return r&&(i["on-demand"]=1),e&&e.length>0&&(i["channel-group"]=e.sort().join(",")),s&&s.length>0&&(i["filter-expr"]=s),n&&Object.keys(n).length>0&&(i.state=JSON.stringify(n)),t&&(i.heartbeat=t),i}}var ks;!function(e){e[e.Channel=0]="Channel",e[e.ChannelGroup=1]="ChannelGroup"}(ks||(ks={}));class Ps{constructor({channels:e,channelGroups:t}){this.isEmpty=!0,this._channelGroups=new Set((null!=t?t:[]).filter((e=>e.length>0))),this._channels=new Set((null!=e?e:[]).filter((e=>e.length>0))),this.isEmpty=0===this._channels.size&&0===this._channelGroups.size}get length(){return this.isEmpty?0:this._channels.size+this._channelGroups.size}get channels(){return this.isEmpty?[]:Array.from(this._channels)}get channelGroups(){return this.isEmpty?[]:Array.from(this._channelGroups)}contains(e){return!this.isEmpty&&(this._channels.has(e)||this._channelGroups.has(e))}with(e){return new Ps({channels:[...this._channels,...e._channels],channelGroups:[...this._channelGroups,...e._channelGroups]})}without(e){return new Ps({channels:[...this._channels].filter((t=>!e._channels.has(t))),channelGroups:[...this._channelGroups].filter((t=>!e._channelGroups.has(t)))})}add(e){return e._channelGroups.size>0&&(this._channelGroups=new Set([...this._channelGroups,...e._channelGroups])),e._channels.size>0&&(this._channels=new Set([...this._channels,...e._channels])),this.isEmpty=0===this._channels.size&&0===this._channelGroups.size,this}remove(e){return e._channelGroups.size>0&&(this._channelGroups=new Set([...this._channelGroups].filter((t=>!e._channelGroups.has(t))))),e._channels.size>0&&(this._channels=new Set([...this._channels].filter((t=>!e._channels.has(t))))),this}removeAll(){return this._channels.clear(),this._channelGroups.clear(),this.isEmpty=!0,this}toString(){return`SubscriptionInput { channels: [${this.channels.join(", ")}], channelGroups: [${this.channelGroups.join(", ")}], is empty: ${this.isEmpty?"true":"false"}} }`}}class Cs{constructor(e,t,s,n){this._isSubscribed=!1,this.clones={},this.parents=[],this._id=Qe.createUUID(),this.referenceTimetoken=n,this.subscriptionInput=t,this.options=s,this.client=e}get id(){return this._id}get isLastClone(){return 1===Object.keys(this.clones).length}get isSubscribed(){return!!this._isSubscribed||this.parents.length>0&&this.parents.some((e=>e.isSubscribed))}set isSubscribed(e){this.isSubscribed!==e&&(this._isSubscribed=e)}addParentState(e){this.parents.includes(e)||this.parents.push(e)}removeParentState(e){const t=this.parents.indexOf(e);-1!==t&&this.parents.splice(t,1)}storeClone(e,t){this.clones[e]||(this.clones[e]=t)}}class Es{constructor(e,t="Subscription"){this.subscriptionType=t,this.id=Qe.createUUID(),this.eventDispatcher=new pt,this._state=e}get state(){return this._state}get channels(){return this.state.subscriptionInput.channels.slice(0)}get channelGroups(){return this.state.subscriptionInput.channelGroups.slice(0)}set onMessage(e){this.eventDispatcher.onMessage=e}set onPresence(e){this.eventDispatcher.onPresence=e}set onSignal(e){this.eventDispatcher.onSignal=e}set onObjects(e){this.eventDispatcher.onObjects=e}set onMessageAction(e){this.eventDispatcher.onMessageAction=e}set onFile(e){this.eventDispatcher.onFile=e}set onDataSync(e){this.eventDispatcher.onDataSync=e}addListener(e){this.eventDispatcher.addListener(e)}removeListener(e){this.eventDispatcher.removeListener(e)}removeAllListeners(){this.eventDispatcher.removeAllListeners()}handleEvent(e,t){var s;if((!this.state.cursor||e>this.state.cursor)&&(this.state.cursor=e),this.state.referenceTimetoken&&t.data.timetoken({messageType:"text",message:`Event timetoken (${t.data.timetoken}) is older than reference timetoken (${this.state.referenceTimetoken}) for ${this.id} subscription object. Ignoring event.`})));if((null===(s=this.state.options)||void 0===s?void 0:s.filter)&&!this.state.options.filter(t))return void this.state.client.logger.trace(this.subscriptionType,`Event filtered out by filter function for ${this.id} subscription object. Ignoring event.`);const n=Object.values(this.state.clones);n.length>0&&this.state.client.logger.trace(this.subscriptionType,`Notify ${this.id} subscription object clones (count: ${n.length}) about received event.`),n.forEach((e=>e.eventDispatcher.handleEvent(t)))}dispose(){const e=Object.keys(this.state.clones);e.length>1?(this.state.client.logger.debug(this.subscriptionType,`Remove subscription object clone on dispose: ${this.id}`),delete this.state.clones[this.id]):1===e.length&&this.state.clones[this.id]&&(this.state.client.logger.debug(this.subscriptionType,`Unsubscribe subscription object on dispose: ${this.id}`),this.unsubscribe())}invalidate(e=!1){this.state._isSubscribed=!1,e&&(delete this.state.clones[this.id],0===Object.keys(this.state.clones).length&&(this.state.client.logger.trace(this.subscriptionType,"Last clone removed. Reset shared subscription state."),this.state.subscriptionInput.removeAll(),this.state.parents=[]))}subscribe(e){this.state.isSubscribed?this.state.client.logger.trace(this.subscriptionType,"Already subscribed. Ignoring subscribe request."):(this.state.client.logger.debug(this.subscriptionType,(()=>e?{messageType:"object",message:e,details:"Subscribe with parameters:"}:{messageType:"text",message:"Subscribe"})),this.state.isSubscribed=!0,this.updateSubscription({subscribing:!0,timetoken:null==e?void 0:e.timetoken}))}unsubscribe(){if(!this.state._isSubscribed||this.state.isSubscribed){if(!this.state._isSubscribed&&this.state.parents.length>0&&this.state.isSubscribed)return void this.state.client.logger.warn(this.subscriptionType,(()=>({messageType:"object",details:"Subscription is subscribed as part of a subscription set. Remove from active sets to unsubscribe:",message:this.state.parents.filter((e=>e.isSubscribed))})));if(!this.state._isSubscribed)return void this.state.client.logger.trace(this.subscriptionType,"Not subscribed. Ignoring unsubscribe request.")}this.state.client.logger.debug(this.subscriptionType,"Unsubscribe"),this.state.isSubscribed=!1,delete this.state.cursor,this.updateSubscription({subscribing:!1})}updateSubscription(e){var t,s;(null==e?void 0:e.timetoken)&&((null===(t=this.state.cursor)||void 0===t?void 0:t.timetoken)&&"0"!==(null===(s=this.state.cursor)||void 0===s?void 0:s.timetoken)?"0"!==e.timetoken&&e.timetoken>this.state.cursor.timetoken&&(this.state.cursor.timetoken=e.timetoken):this.state.cursor={timetoken:e.timetoken});const n=e.subscriptions&&e.subscriptions.length>0?e.subscriptions:void 0;e.subscribing?this.register(Object.assign(Object.assign({},e.timetoken?{cursor:this.state.cursor}:{}),n?{subscriptions:n}:{})):this.unregister(n)}}class Ns extends Cs{constructor(e){const t=new Ps({});e.subscriptions.forEach((e=>t.add(e.state.subscriptionInput))),super(e.client,t,e.options,e.client.subscriptionTimetoken),this.subscriptions=e.subscriptions}addSubscription(e){this.subscriptions.includes(e)||(e.state.addParentState(this),this.subscriptions.push(e),this.subscriptionInput.add(e.state.subscriptionInput))}removeSubscription(e,t){const s=this.subscriptions.indexOf(e);-1!==s&&(this.subscriptions.splice(s,1),t||e.state.removeParentState(this),this.subscriptionInput.remove(e.state.subscriptionInput))}removeAllSubscriptions(){this.subscriptions.forEach((e=>e.state.removeParentState(this))),this.subscriptions.splice(0,this.subscriptions.length),this.subscriptionInput.removeAll()}}class Ts extends Es{constructor(e){let t;if("client"in e){let s=[];!e.subscriptions&&e.entities?e.entities.forEach((t=>s.push(t.subscription(e.options)))):e.subscriptions&&(s=e.subscriptions),t=new Ns({client:e.client,subscriptions:s,options:e.options}),s.forEach((e=>e.state.addParentState(t))),t.client.logger.debug("SubscriptionSet",(()=>({messageType:"object",details:"Create subscription set with parameters:",message:Object.assign({subscriptions:t.subscriptions},e.options?e.options:{})})))}else t=e.state,t.client.logger.debug("SubscriptionSet","Create subscription set clone");super(t,"SubscriptionSet"),this.state.storeClone(this.id,this),t.subscriptions.forEach((e=>e.addParentSet(this)))}get state(){return super.state}get subscriptions(){return this.state.subscriptions.slice(0)}handleEvent(e,t){var s;this.state.subscriptionInput.contains(null!==(s=t.data.subscription)&&void 0!==s?s:t.data.channel)&&(this.state._isSubscribed?(super.handleEvent(e,t),this.state.subscriptions.length>0&&this.state.client.logger.trace(this.subscriptionType,`Notify ${this.id} subscription set subscriptions (count: ${this.state.subscriptions.length}) about received event.`),this.state.subscriptions.forEach((s=>s.handleEvent(e,t)))):this.state.client.logger.trace(this.subscriptionType,`Subscription set ${this.id} is not subscribed. Ignoring event.`))}subscriptionInput(e=!1){let t=this.state.subscriptionInput;return this.state.subscriptions.forEach((s=>{e&&s.state.entity.subscriptionsCount>0&&(t=t.without(s.state.subscriptionInput))})),t}cloneEmpty(){return new Ts({state:this.state})}dispose(){const e=this.state.isLastClone;this.state.subscriptions.forEach((t=>{t.removeParentSet(this),e&&t.state.removeParentState(this.state)})),super.dispose()}invalidate(e=!1){(e?this.state.subscriptions.slice(0):this.state.subscriptions).forEach((t=>{e&&(t.state.entity.decreaseSubscriptionCount(this.state.id),t.removeParentSet(this)),t.invalidate(e)})),e&&this.state.removeAllSubscriptions(),super.invalidate()}addSubscription(e){this.addSubscriptions([e])}addSubscriptions(e){const t=[],s=[];this.state.client.logger.debug(this.subscriptionType,(()=>{const t=[],s=[];return e.forEach((e=>{this.state.subscriptions.includes(e)?t.push(e):s.push(e)})),{messageType:"object",details:`Add subscriptions to ${this.id} (subscriptions count: ${this.state.subscriptions.length+s.length}):`,message:{addedSubscriptions:s,ignoredSubscriptions:t}}})),e.filter((e=>!this.state.subscriptions.includes(e))).forEach((e=>{e.state.isSubscribed?s.push(e):t.push(e),e.addParentSet(this),this.state.addSubscription(e)})),0===s.length&&0===t.length||!this.state.isSubscribed||(s.forEach((({state:e})=>e.entity.increaseSubscriptionCount(this.state.id))),t.length>0&&this.updateSubscription({subscribing:!0,subscriptions:t}))}removeSubscription(e){this.removeSubscriptions([e])}removeSubscriptions(e){const t=[];this.state.client.logger.debug(this.subscriptionType,(()=>{const t=[],s=[];return e.forEach((e=>{this.state.subscriptions.includes(e)?s.push(e):t.push(e)})),{messageType:"object",details:`Remove subscriptions from ${this.id} (subscriptions count: ${this.state.subscriptions.length}):`,message:{removedSubscriptions:s,ignoredSubscriptions:t}}})),e.filter((e=>this.state.subscriptions.includes(e))).forEach((e=>{e.state.isSubscribed&&t.push(e),e.removeParentSet(this),this.state.removeSubscription(e,e.parentSetsCount>1)})),0!==t.length&&this.state.isSubscribed&&this.updateSubscription({subscribing:!1,subscriptions:t})}addSubscriptionSet(e){this.addSubscriptions(e.subscriptions)}removeSubscriptionSet(e){this.removeSubscriptions(e.subscriptions)}register(e){var t;const s=null!==(t=e.subscriptions)&&void 0!==t?t:this.state.subscriptions;s.forEach((({state:e})=>e.entity.increaseSubscriptionCount(this.state.id))),this.state.client.logger.trace(this.subscriptionType,(()=>({messageType:"text",message:`Register subscription for real-time events: ${this}`}))),this.state.client.registerEventHandleCapable(this,e.cursor,s)}unregister(e){const t=null!=e?e:this.state.subscriptions;t.forEach((({state:e})=>e.entity.decreaseSubscriptionCount(this.state.id))),this.state.client.logger.trace(this.subscriptionType,(()=>e?{messageType:"object",message:{subscription:this,subscriptions:e},details:"Unregister subscriptions of subscription set from real-time events:"}:{messageType:"text",message:`Unregister subscription from real-time events: ${this}`})),this.state.client.unregisterEventHandleCapable(this,t)}toString(){const e=this.state;return`${this.subscriptionType} { id: ${this.id}, stateId: ${e.id}, clonesCount: ${Object.keys(this.state.clones).length}, isSubscribed: ${e.isSubscribed}, subscriptions: [${e.subscriptions.map((e=>e.toString())).join(", ")}] }`}}class Is extends Cs{constructor(e){var t,s;const n=e.entity.subscriptionNames(null!==(s=null===(t=e.options)||void 0===t?void 0:t.receivePresenceEvents)&&void 0!==s&&s),r=new Ps({[e.entity.subscriptionType==ks.Channel?"channels":"channelGroups"]:n});super(e.client,r,e.options,e.client.subscriptionTimetoken),this.entity=e.entity}}class Rs extends Es{constructor(e){"client"in e?e.client.logger.debug("Subscription",(()=>({messageType:"object",details:"Create subscription with parameters:",message:Object.assign({entity:e.entity},e.options?e.options:{})}))):e.state.client.logger.debug("Subscription","Create subscription clone"),super("state"in e?e.state:new Is(e)),this.parents=[],this.handledUpdates=[],this.state.storeClone(this.id,this)}get state(){return super.state}get parentSetsCount(){return this.parents.length}handleEvent(e,t){var s,n;if(this.state.isSubscribed&&this.state.subscriptionInput.contains(null!==(s=t.data.subscription)&&void 0!==s?s:t.data.channel)){if(this.parentSetsCount>0){const e=Ce(t.data);if(this.handledUpdates.includes(e))return void this.state.client.logger.trace(this.subscriptionType,`Event (${e}) already handled by ${this.id}. Ignoring.`);this.handledUpdates.push(e),this.handledUpdates.length>10&&this.handledUpdates.shift()}this.state.subscriptionInput.contains(null!==(n=t.data.subscription)&&void 0!==n?n:t.data.channel)&&super.handleEvent(e,t)}}subscriptionInput(e=!1){return e&&this.state.entity.subscriptionsCount>0?new Ps({}):this.state.subscriptionInput}cloneEmpty(){return new Rs({state:this.state})}dispose(){this.parentSetsCount>0?this.state.client.logger.debug(this.subscriptionType,(()=>({messageType:"text",message:`'${this.state.entity.subscriptionNames()}' subscription still in use. Ignore dispose request.`}))):(this.handledUpdates.splice(0,this.handledUpdates.length),super.dispose())}invalidate(e=!1){e&&this.state.entity.decreaseSubscriptionCount(this.state.id),this.handledUpdates.splice(0,this.handledUpdates.length),super.invalidate(e)}addParentSet(e){this.parents.includes(e)||(this.parents.push(e),this.state.client.logger.trace(this.subscriptionType,`Add parent subscription set for ${this.id}: ${e.id}. Parent subscription set count: ${this.parentSetsCount}`))}removeParentSet(e){const t=this.parents.indexOf(e);-1!==t&&(this.parents.splice(t,1),this.state.client.logger.trace(this.subscriptionType,`Remove parent subscription set from ${this.id}: ${e.id}. Parent subscription set count: ${this.parentSetsCount}`)),0===this.parentSetsCount&&this.handledUpdates.splice(0,this.handledUpdates.length)}addSubscription(e){this.state.client.logger.debug(this.subscriptionType,(()=>({messageType:"text",message:`Create set with subscription: ${e}`})));const t=new Ts({client:this.state.client,subscriptions:[this,e],options:this.state.options});return this.state.isSubscribed||e.state.isSubscribed?(this.state.client.logger.trace(this.subscriptionType,"Subscribe resulting set because the receiver is already subscribed."),t.subscribe(),t):t}register(e){this.state.entity.increaseSubscriptionCount(this.state.id),this.state.client.logger.trace(this.subscriptionType,(()=>({messageType:"text",message:`Register subscription for real-time events: ${this}`}))),this.state.client.registerEventHandleCapable(this,e.cursor)}unregister(e){this.state.entity.decreaseSubscriptionCount(this.state.id),this.state.client.logger.trace(this.subscriptionType,(()=>({messageType:"text",message:`Unregister subscription from real-time events: ${this}`}))),this.handledUpdates.splice(0,this.handledUpdates.length),this.state.client.unregisterEventHandleCapable(this)}toString(){const e=this.state;return`${this.subscriptionType} { id: ${this.id}, stateId: ${e.id}, entity: ${e.entity.subscriptionNames(!1).pop()}, clonesCount: ${Object.keys(e.clones).length}, isSubscribed: ${e.isSubscribed}, parentSetsCount: ${this.parentSetsCount}, cursor: ${e.cursor?e.cursor.timetoken:"not set"}, referenceTimetoken: ${e.referenceTimetoken?e.referenceTimetoken:"not set"} }`}}class Ms extends ot{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=(n=this.parameters).channels)&&void 0!==t||(n.channels=[]),null!==(s=(r=this.parameters).channelGroups)&&void 0!==s||(r.channelGroups=[])}operation(){return $e.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),{channels:s=[],channelGroups:n=[]}=this.parameters,r={channels:{}};return 1===s.length&&0===n.length?r.channels[s[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${ve(null!=s?s:[],",")}/uuid/${fe(null!=t?t:"")}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class Us extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?void 0===t?"Missing State":0===(null==s?void 0:s.length)&&0===(null==n?void 0:n.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{state:this.deserializeResponse(e).payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${ve(null!=s?s:[],",")}/uuid/${fe(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),s}}class _s extends ot{constructor(e){super({cancellable:!0}),this.parameters=e}operation(){return $e.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${ve(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),void 0!==t&&(n.state=JSON.stringify(t)),n}}class Ds extends ot{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return $e.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${ve(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class As extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${fe(t)}`}}class $s extends ot{constructor(e){var t,s,n,r,i,a,o,c;super(),this.parameters=e,null!==(t=(i=this.parameters).queryParameters)&&void 0!==t||(i.queryParameters={}),null!==(s=(a=this.parameters).includeUUIDs)&&void 0!==s||(a.includeUUIDs=true),null!==(n=(o=this.parameters).includeState)&&void 0!==n||(o.includeState=false),null!==(r=(c=this.parameters).limit)&&void 0!==r||(c.limit=1e3)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?$e.PNGlobalHereNowOperation:$e.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e),r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_occupancy,a={};let o={};const c=this.parameters.limit;let u=!1;if("occupancy"in n){const e=this.parameters.channels[0];o[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:i}}else o=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(o).forEach((e=>{const t=o[e];a[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy},u||t.occupancy!==c||(u=!0)})),{totalChannels:r,totalOccupancy:i,channels:a}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${ve(null!=t?t:[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,limit:n,offset:r,queryParameters:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.operation()===$e.PNHereNowOperation?{limit:n}:{}),this.operation()===$e.PNHereNowOperation&&null!=r&&r?{offset:r}:{}),t?{}:{disable_uuids:"1"}),null!=s&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),i)}}class Fs extends ot{constructor(e){super({method:nt.DELETE}),this.parameters=e}operation(){return $e.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${fe(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class xs extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${ve(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class qs extends ot{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(s=e.includeMeta)&&void 0!==s||(e.includeMeta=false),null!==(n=e.logVerbosity)&&void 0!==n||(e.logVerbosity=false)}operation(){return $e.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),s=t[0],n=t[1],r=t[2];return Array.isArray(s)?{messages:s.map((e=>{const t=this.processPayload(e.message),s={entry:t.payload,timetoken:e.timetoken};return t.error&&(s.error=t.error),e.meta&&(s.meta=e.meta),s})),startTimeToken:n,endTimeToken:r}:{messages:[],startTimeToken:n,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${fe(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=s?{reverse:s.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let n,r;try{const s=t.decrypt(e);n=s instanceof ArrayBuffer?JSON.parse(qs.decoder.decode(s)):s}catch(t){s&&console.log("decryption error",t.message),n=e,r=`Error while decrypting message content: ${t.message}`}return{payload:n,error:r}}}var Ls;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Ls||(Ls={}));class Gs extends ot{constructor(e){var t,s,n,r,i;super(),this.parameters=e;const a=null!==(t=e.includeMessageActions)&&void 0!==t&&t,o=e.channels.length>1||a?25:100;e.count?e.count=Math.min(e.count,o):e.count=o,e.includeUuid?e.includeUUID=e.includeUuid:null!==(s=e.includeUUID)&&void 0!==s||(e.includeUUID=true),null!==(n=e.stringifiedTimeToken)&&void 0!==n||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return $e.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?void 0!==s&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e),n=null!==(t=s.channels)&&void 0!==t?t:{},r={};return Object.keys(n).forEach((e=>{r[e]=n[e].map((t=>{null===t.message_type&&(t.message_type=Ls.Message);const s=this.processPayload(e,t),n=Object.assign(Object.assign({channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.message_type},t.custom_message_type?{customMessageType:t.custom_message_type}:{}),{uuid:t.uuid});if(t.actions){const e=n;e.actions=t.actions,e.data=t.actions}return t.meta&&(n.meta=t.meta),s.error&&(n.error=s.error),n}))})),s.more?{channels:r,more:s.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${ve(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeCustomMessageType:n,includeMessageType:r,includeMeta:i,includeUUID:a,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==i&&i?{include_meta:"true"}:{}),a?{include_uuid:"true"}:{}),null!=n?{include_custom_message_type:n?"true":"false"}:{}),r?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=s.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse(Gs.decoder.decode(e)):e}catch(e){n&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Ls.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class Ks extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${fe(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class Hs extends ot{constructor(e){super({method:nt.POST}),this.parameters=e}operation(){return $e.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${fe(t)}/message/${s}`}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){return JSON.stringify(this.parameters.action)}}class Vs extends ot{constructor(e){super({method:nt.DELETE}),this.parameters=e}operation(){return $e.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${fe(t)}/message/${n}/action/${s}`}}class Ws extends ot{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return $e.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:r,fileName:i}=this.parameters,a=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${fe(t)}/0/${fe(this.prepareMessagePayload(a))}`}get queryParameters(){const{customMessageType:e,storeInHistory:t,ttl:s,meta:n}=this.parameters;return Object.assign(Object.assign(Object.assign({store:t?"1":"0"},e?{custom_message_type:e}:{}),s?{ttl:s}:{}),n&&"object"==typeof n?{meta:JSON.stringify(n)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Bs extends ot{constructor(e){super({method:nt.LOCAL}),this.parameters=e}operation(){return $e.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${fe(e)}/files/${fe(t)}/${fe(s)}`}}class zs extends ot{constructor(e){super({method:nt.DELETE}),this.parameters=e}operation(){return $e.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${fe(s)}/files/${fe(t)}/${fe(n)}`}}class Js extends ot{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return $e.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${fe(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Ys extends ot{constructor(e){super({method:nt.POST}),this.parameters=e}operation(){return $e.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${fe(t)}/generate-upload-url`}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){return JSON.stringify({name:this.parameters.name})}}class Xs extends ot{constructor(e){super({method:nt.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return $e.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Xs.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class Qs{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:$e.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof De?e:De.create(e);throw new d("File upload error.",t.toStatus($e.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Ys(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:r}=this.parameters,{id:i,name:a,url:o,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&r&&(this.file=yield r.encryptFile(t,this.file,s))),this.parameters.sendRequest(new Xs({fileId:i,fileName:a,file:this.file,uploadUrl:o,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i;let a,o={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{o=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(a=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:o.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=a.status)||void 0===s?void 0:s.category)&&void 0!==n?n:h.PNUnknownCategory,statusCode:null!==(i=null===(r=a.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}class Zs{constructor(e,t){this.subscriptionStateIds=[],this.client=t,this._nameOrId=e}get entityType(){return"Channel"}get subscriptionType(){return ks.Channel}subscriptionNames(e){return[this._nameOrId,...e&&!this._nameOrId.endsWith("-pnpres")?[`${this._nameOrId}-pnpres`]:[]]}subscription(e){return new Rs({client:this.client,entity:this,options:e})}get subscriptionsCount(){return this.subscriptionStateIds.length}increaseSubscriptionCount(e){this.subscriptionStateIds.includes(e)||this.subscriptionStateIds.push(e)}decreaseSubscriptionCount(e){{const t=this.subscriptionStateIds.indexOf(e);t>=0&&this.subscriptionStateIds.splice(t,1)}}toString(){return`${this.entityType} { nameOrId: ${this._nameOrId}, subscriptionsCount: ${this.subscriptionsCount} }`}}const en=["default","__default__"],tn=e=>{if(!e)return;const t=e.trim();return 0===t.length||en.includes(t.toLowerCase())?void 0:t};class sn extends Zs{constructor(e,t,s){super(e,t),this._projection=tn(s)}get id(){return this._nameOrId}get projection(){return this._projection}get subscriptionChannel(){return this._projection?`__${this._projection}__${this._nameOrId}`:this._nameOrId}subscriptionNames(e){return[this.subscriptionChannel]}subscription(e){{const t=this.entityForProjection(tn(null==e?void 0:e.projection));return t!==this?t.subscription(e):super.subscription(e)}}entityForProjection(e){var t,s,n,r;if(e===this._projection)return this;const i=null!==(t=this.variants)&&void 0!==t?t:this.variants={};null!==(n=i[r=null!==(s=this._projection)&&void 0!==s?s:""])&&void 0!==n||(i[r]=this);const a=null!=e?e:"";let o=i[a];return o||(o=i[a]=this.withProjection(e),o.variants=i),o}toString(){var e;return`${this.entityType} { id: ${this._nameOrId}, projection: ${null!==(e=this._projection)&&void 0!==e?e:"none"}, channel: ${this.subscriptionChannel}, subscriptionsCount: ${this.subscriptionsCount} }`}}class nn extends sn{get entityType(){return"DataSyncRelationship"}withProjection(e){return new nn(this._nameOrId,this.client,e)}}class rn extends sn{get entityType(){return"DataSyncMembership"}withProjection(e){return new rn(this._nameOrId,this.client,e)}}class an extends sn{get entityType(){return"DataSyncChannel"}withProjection(e){return new an(this._nameOrId,this.client,e)}}class on extends sn{get entityType(){return"DataSyncEntity"}withProjection(e){return new on(this._nameOrId,this.client,e)}}class cn extends Zs{get entityType(){return"ChannelMetadata"}get id(){return this._nameOrId}subscriptionNames(e){return[this.id]}}class un extends sn{get entityType(){return"DataSyncUser"}withProjection(e){return new un(this._nameOrId,this.client,e)}}class ln extends Zs{get entityType(){return"ChannelGroups"}get name(){return this._nameOrId}get subscriptionType(){return ks.ChannelGroup}}class hn extends Zs{get entityType(){return"UserMetadata"}get id(){return this._nameOrId}subscriptionNames(e){return[this.id]}}class dn extends Zs{get entityType(){return"Channel"}get name(){return this._nameOrId}}class pn extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${fe(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class gn extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${fe(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class bn extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${fe(t)}`}}class yn extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${fe(t)}/remove`}}class mn extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{groups:this.deserializeResponse(e).payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class fn{constructor(e,t,s){this.sendRequest=s,this.logger=e,this.keySet=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List channel group channels with parameters:"})));const s=new bn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`List channel group channels success. Received ${e.channels.length} channels.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}listGroups(e){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub","List all channel groups.");const t=new mn({keySet:this.keySet}),s=e=>{e&&this.logger.debug("PubNub",`List all channel groups success. Received ${e.groups.length} groups.`)};return e?this.sendRequest(t,((t,n)=>{s(n),e(t,n)})):this.sendRequest(t).then((e=>(s(e),e)))}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add channels to the channel group with parameters:"})));const s=new gn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Add channels to the channel group success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove channels from the channel group with parameters:"})));const s=new pn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Remove channels from the channel group success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove a channel group with parameters:"})));const s=new yn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub",`Remove a channel group success. Removed '${e.channelGroup}' channel group.'`)};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}}class vn extends ot{constructor(e){var t,s;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(s=this.parameters).environment)&&void 0!==t||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?n?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: fcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let r="apns2"===n?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;s=Object.assign(Object.assign({},s),{environment:e,topic:t})}return s}}class On extends vn{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return $e.PNRemovePushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class Sn extends vn{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return $e.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e)}}))}}class jn extends vn{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return $e.PNAddPushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class wn extends vn{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return $e.PNRemoveAllPushNotificationsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class kn{constructor(e,t,s){this.sendRequest=s,this.logger=e,this.keySet=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List push-enabled channels with parameters:"})));const s=new Sn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`List push-enabled channels success. Received ${e.channels.length} channels.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add push-enabled channels with parameters:"})));const s=new jn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Add push-enabled channels success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove push-enabled channels with parameters:"})));const s=new On(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Remove push-enabled channels success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove push notifications for device with parameters:"})));const s=new wn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Remove push notifications for device success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}}class Pn extends ot{constructor(e){var t,s,n,r,i,a;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(i=e.include).customFields)&&void 0!==s||(i.customFields=false),null!==(n=(a=e.include).totalCount)&&void 0!==n||(a.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return $e.PNGetAllChannelMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class Cn extends ot{constructor(e){super({method:nt.DELETE}),this.parameters=e}operation(){return $e.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${fe(t)}`}}class En extends ot{constructor(e){var t,s,n,r,i,a,o,c,u,l,h,d,p,g,b,y,m,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(b=e.include).channelFields)&&void 0!==a||(b.channelFields=false),null!==(o=(y=e.include).customChannelFields)&&void 0!==o||(y.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(f=e.include).channelTypeField)&&void 0!==u||(f.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return $e.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${fe(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class Nn extends ot{constructor(e){var t,s,n,r,i,a,o,c,u,l,h,d,p,g,b,y,m,f;super({method:nt.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(b=e.include).channelFields)&&void 0!==a||(b.channelFields=false),null!==(o=(y=e.include).customChannelFields)&&void 0!==o||(y.customChannelFields=false),null!==(c=(m=e.include).channelStatusField)&&void 0!==c||(m.channelStatusField=false),null!==(u=(f=e.include).channelTypeField)&&void 0!==u||(f.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return $e.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${fe(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["channel.status","channel.type","status"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class Tn extends ot{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(r=e.include).customFields)&&void 0!==s||(r.customFields=false),null!==(n=e.limit)&&void 0!==n||(e.limit=100)}operation(){return $e.PNGetAllUUIDMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class In extends ot{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return $e.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${fe(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class Rn extends ot{constructor(e){var t,s,n;super({method:nt.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return $e.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json"})}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${fe(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Mn extends ot{constructor(e){super({method:nt.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return $e.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${fe(t)}`}}class Un extends ot{constructor(e){var t,s,n,r,i,a,o,c,u,l,h,d,p,g,b,y,m,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(b=e.include).UUIDFields)&&void 0!==a||(b.UUIDFields=false),null!==(o=(y=e.include).customUUIDFields)&&void 0!==o||(y.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(f=e.include).UUIDTypeField)&&void 0!==u||(f.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return $e.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${fe(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class _n extends ot{constructor(e){var t,s,n,r,i,a,o,c,u,l,h,d,p,g,b,y,m,f;super({method:nt.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(b=e.include).UUIDFields)&&void 0!==a||(b.UUIDFields=false),null!==(o=(y=e.include).customUUIDFields)&&void 0!==o||(y.customUUIDFields=false),null!==(c=(m=e.include).UUIDStatusField)&&void 0!==c||(m.UUIDStatusField=false),null!==(u=(f=e.include).UUIDTypeField)&&void 0!==u||(f.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return $e.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${fe(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["uuid.status","uuid.type","type"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class Dn extends ot{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return $e.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${fe(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class An extends ot{constructor(e){var t,s,n;super({method:nt.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return $e.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json"})}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${fe(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class $n{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}get logger(){return this.configuration.logger()}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Get all UUID metadata objects with parameters:"}))),this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new Tn(Object.assign(Object.assign({},s),{keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Get all UUID metadata success. Received ${e.totalCount} UUID metadata objects.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.configuration.userId},details:`Get ${e&&"function"!=typeof e?"":" current"} UUID metadata object with parameters:`}))),this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Dn(Object.assign(Object.assign({},n),{keySet:this.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Get UUID metadata object success. Received '${n.uuid}' UUID metadata object.`)};return t?this.sendRequest(r,((e,s)=>{i(s),t(e,s)})):this.sendRequest(r).then((e=>(i(e),e)))}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set UUID metadata object with parameters:"}))),this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new An(Object.assign(Object.assign({},e),{keySet:this.keySet})),r=t=>{t&&this.logger.debug("PubNub",`Set UUID metadata object success. Updated '${e.uuid}' UUID metadata object.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.configuration.userId},details:`Remove${e&&"function"!=typeof e?"":" current"} UUID metadata object with parameters:`}))),this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Mn(Object.assign(Object.assign({},n),{keySet:this.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Remove UUID metadata object success. Removed '${n.uuid}' UUID metadata object.`)};return t?this.sendRequest(r,((e,s)=>{i(s),t(e,s)})):this.sendRequest(r).then((e=>(i(e),e)))}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Get all Channel metadata objects with parameters:"}))),this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new Pn(Object.assign(Object.assign({},s),{keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Get all Channel metadata objects success. Received ${e.totalCount} Channel metadata objects.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Channel metadata object with parameters:"}))),this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new In(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Get Channel metadata object success. Received '${e.channel}' Channel metadata object.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Channel metadata object with parameters:"}))),this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new Rn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Set Channel metadata object success. Updated '${e.channel}' Channel metadata object.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Channel metadata object with parameters:"}))),this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new Cn(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Remove Channel metadata object success. Removed '${e.channel}' Channel metadata object.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get channel members with parameters:"})));const s=new Un(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Get channel members success. Received ${e.totalCount} channel members.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set channel members with parameters:"})));const s=new _n(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Set channel members success. There are ${e.totalCount} channel members now.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove channel members with parameters:"})));const s=new _n(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Remove channel members success. There are ${e.totalCount} channel members now.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},n),details:"Get memberships with parameters:"})));const r=new En(Object.assign(Object.assign({},n),{keySet:this.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Get memberships success. Received ${e.totalCount} memberships.`)};return t?this.sendRequest(r,((e,s)=>{i(s),t(e,s)})):this.sendRequest(r).then((e=>(i(e),e)))}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set memberships with parameters:"})));const n=new Nn(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Set memberships success. There are ${e.totalCount} memberships now.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove memberships with parameters:"})));const n=new Nn(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Remove memberships success. There are ${e.totalCount} memberships now.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n;if(this.logger.warn("PubNub","'fetchMemberships' is deprecated. Use 'pubnub.objects.getChannelMembers' or 'pubnub.objects.getMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch memberships with parameters:"}))),"spaceId"in e){const n=e,r={channel:null!==(s=n.spaceId)&&void 0!==s?s:n.channel,filter:n.filter,limit:n.limit,page:n.page,include:Object.assign({},n.include),sort:n.sort?Object.fromEntries(Object.entries(n.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,s)=>{t(e,s?i(s):s)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(n=r.userId)&&void 0!==n?n:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},a=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,s)=>{t(e,s?a(s):s)})):this.getMemberships(i).then(a)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i,a,o;if(this.logger.warn("PubNub","'addMemberships' is deprecated. Use 'pubnub.objects.setChannelMembers' or 'pubnub.objects.setMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add memberships with parameters:"}))),"spaceId"in e){const i=e,a={channel:null!==(s=i.spaceId)&&void 0!==s?s:i.channel,uuids:null!==(r=null===(n=i.users)||void 0===n?void 0:n.map((e=>"string"==typeof e?e:{id:e.userId,custom:e.custom})))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(a,t):this.setChannelMembers(a)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(o=null===(a=c.spaces)||void 0===a?void 0:a.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==o?o:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class Fn extends ot{constructor(e){super({method:nt.POST}),this.parameters=e}operation(){return $e.PNCreateDataSyncUserOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.data?void 0===this.parameters.data.classVersion||null===this.parameters.data.classVersion?"Entity class version cannot be empty":void 0:"User data cannot be empty"}get headers(){var e;const t=null!==(e=super.headers)&&void 0!==e?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.user+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/users`}get body(){const{id:e,class:t,classLevel:s,data:n}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e?{id:e}:{}),void 0!==t?{entityClass:t}:{}),{entityClassVersion:n.classVersion}),void 0!==s?{entityClassLevel:s}:{}),void 0!==n.status?{status:n.status}:{}),void 0!==n.payload?{payload:n.payload}:{})})}}function xn(e){return"string"==typeof e?e:Object.entries(null!=e?e:{}).map((([e,t])=>null!==t?`${e}:${t}`:e))}function qn(e){const{add:t,replace:s,remove:n,move:r,copy:i,test:a}=e,o=[];if(t)for(const[e,s]of Object.entries(t))o.push({op:"add",path:e,value:s});if(s)for(const[e,t]of Object.entries(s))o.push({op:"replace",path:e,value:t});if(n)for(const e of n)o.push({op:"remove",path:e});if(r)for(const{from:e,path:t}of r)o.push({op:"move",from:e,path:t});if(i)for(const{from:e,path:t}of i)o.push({op:"copy",from:e,path:t});if(a)for(const[e,t]of Object.entries(a))o.push({op:"test",path:e,value:t});return o}class Ln extends ot{constructor(e){var t;super(),this.parameters=e,null!==(t=e.limit)&&void 0!==t||(e.limit=20)}operation(){return $e.PNGetDataSyncUsersOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/users`}get queryParameters(){const{class:e,classVersion:t,classLevel:s,cursor:n,limit:r,filter:i,filterFast:a,sort:o}=this.parameters,c=xn(o);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e?{entity_class:e}:{}),void 0!==t?{entity_class_version:`${t}`}:{}),s?{entity_class_level:s}:{}),n?{cursor:n}:{}),r?{limit:`${r}`}:{}),i?{filter:i}:{}),a?{filter_fast:a}:{}),c.length?{sort:c}:{})}}class Gn extends ot{constructor(e){super({method:nt.PUT}),this.parameters=e}operation(){return $e.PNSetDataSyncUserOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.data?void 0===this.parameters.data.classVersion||null===this.parameters.data.classVersion?"Entity class version cannot be empty":void 0:"User data cannot be empty":"User id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.user+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/users/${fe(t)}`}get body(){const{data:e}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({entityClassVersion:e.classVersion},void 0!==e.status?{status:e.status}:{}),void 0!==e.payload?{payload:e.payload}:{})})}}class Kn extends ot{constructor(e){super({method:nt.DELETE}),this.parameters=e}operation(){return $e.PNRemoveDataSyncUserOperation}validate(){if(!this.parameters.id)return"User id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/users/${fe(t)}`}}class Hn extends ot{constructor(e){super({method:nt.PATCH}),this.parameters=e}operation(){return $e.PNUpdateDataSyncUserOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"User id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,a=e&&Object.keys(e).length>0,o=t&&Object.keys(t).length>0,c=s&&s.length>0,u=n&&n.length>0,l=r&&r.length>0,h=i&&Object.keys(i).length>0;return a||o||c||u||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/users/${fe(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,a=qn({add:e,replace:t,remove:s,move:n,copy:r,test:i});return JSON.stringify(a)}}class Vn extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNGetDataSyncUserOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"User id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/users/${fe(t)}`}}class Wn extends ot{constructor(e){super({method:nt.POST}),this.parameters=e}operation(){return $e.PNCreateDataSyncChannelOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.data?void 0===this.parameters.data.classVersion||null===this.parameters.data.classVersion?"Entity class version cannot be empty":void 0:"Channel data cannot be empty"}get headers(){var e;const t=null!==(e=super.headers)&&void 0!==e?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.channel+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/channels`}get body(){const{id:e,class:t,classLevel:s,data:n}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e?{id:e}:{}),void 0!==t?{entityClass:t}:{}),{entityClassVersion:n.classVersion}),void 0!==s?{entityClassLevel:s}:{}),void 0!==n.status?{status:n.status}:{}),void 0!==n.payload?{payload:n.payload}:{})})}}class Bn extends ot{constructor(e){var t;super(),this.parameters=e,null!==(t=e.limit)&&void 0!==t||(e.limit=20)}operation(){return $e.PNGetDataSyncChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{class:e,classVersion:t,classLevel:s,cursor:n,limit:r,filter:i,filterFast:a,sort:o}=this.parameters,c=xn(o);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e?{entity_class:e}:{}),void 0!==t?{entity_class_version:`${t}`}:{}),s?{entity_class_level:s}:{}),n?{cursor:n}:{}),r?{limit:`${r}`}:{}),i?{filter:i}:{}),a?{filter_fast:a}:{}),c.length?{sort:c}:{})}}class zn extends ot{constructor(e){super({method:nt.PUT}),this.parameters=e}operation(){return $e.PNSetDataSyncChannelOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.data?void 0===this.parameters.data.classVersion||null===this.parameters.data.classVersion?"Entity class version cannot be empty":void 0:"Channel data cannot be empty":"Channel id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.channel+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/channels/${fe(t)}`}get body(){const{data:e}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({entityClassVersion:e.classVersion},void 0!==e.status?{status:e.status}:{}),void 0!==e.payload?{payload:e.payload}:{})})}}class Jn extends ot{constructor(e){super({method:nt.DELETE}),this.parameters=e}operation(){return $e.PNRemoveDataSyncChannelOperation}validate(){if(!this.parameters.id)return"Channel id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/channels/${fe(t)}`}}class Yn extends ot{constructor(e){super({method:nt.PATCH}),this.parameters=e}operation(){return $e.PNUpdateDataSyncChannelOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Channel id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,a=e&&Object.keys(e).length>0,o=t&&Object.keys(t).length>0,c=s&&s.length>0,u=n&&n.length>0,l=r&&r.length>0,h=i&&Object.keys(i).length>0;return a||o||c||u||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/channels/${fe(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,a=qn({add:e,replace:t,remove:s,move:n,copy:r,test:i});return JSON.stringify(a)}}class Xn extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNGetDataSyncChannelOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Channel id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/channels/${fe(t)}`}}class Qn extends ot{constructor(e){super({method:nt.POST}),this.parameters=e}operation(){return $e.PNCreateDataSyncMembershipOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.userId?this.parameters.channelId?this.parameters.data?this.parameters.data.classVersion?void 0:"Membership class version cannot be empty":"Membership data cannot be empty":"Channel id cannot be empty":"User id cannot be empty"}get headers(){var e;const t=null!==(e=super.headers)&&void 0!==e?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.membership+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships`}get body(){const{id:e,userId:t,channelId:s,data:n}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e?{id:e}:{}),{userId:t,channelId:s,relationshipClassVersion:n.classVersion}),void 0!==n.status?{status:n.status}:{}),void 0!==n.payload?{payload:n.payload}:{})})}}class Zn extends ot{constructor(e){var t;super(),this.parameters=e,null!==(t=e.limit)&&void 0!==t||(e.limit=20)}operation(){return $e.PNGetDataSyncMembershipsOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/memberships`}get queryParameters(){const{userId:e,channelId:t,classVersion:s,cursor:n,limit:r,filter:i,filterFast:a,sort:o}=this.parameters,c=xn(o);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e?{user_id:e}:{}),t?{channel_id:t}:{}),void 0!==s?{relationship_class_version:`${s}`}:{}),n?{cursor:n}:{}),r?{limit:`${r}`}:{}),i?{filter:i}:{}),a?{filter_fast:a}:{}),c.length?{sort:c}:{})}}class er extends ot{constructor(e){super({method:nt.PUT}),this.parameters=e}operation(){return $e.PNSetDataSyncMembershipOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.userId?this.parameters.channelId?this.parameters.data?this.parameters.data.classVersion?void 0:"Membership class version cannot be empty":"Membership data cannot be empty":"Channel id cannot be empty":"User id cannot be empty":"Membership id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.membership+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships/${fe(t)}`}get body(){const{userId:e,channelId:t,data:s}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({userId:e,channelId:t,relationshipClassVersion:s.classVersion},void 0!==s.status?{status:s.status}:{}),void 0!==s.payload?{payload:s.payload}:{})})}}class tr extends ot{constructor(e){super({method:nt.DELETE}),this.parameters=e}operation(){return $e.PNRemoveDataSyncMembershipOperation}validate(){if(!this.parameters.id)return"Membership id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships/${fe(t)}`}}class sr extends ot{constructor(e){super({method:nt.PATCH}),this.parameters=e}operation(){return $e.PNUpdateDataSyncMembershipOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Membership id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,a=e&&Object.keys(e).length>0,o=t&&Object.keys(t).length>0,c=s&&s.length>0,u=n&&n.length>0,l=r&&r.length>0,h=i&&Object.keys(i).length>0;return a||o||c||u||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships/${fe(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,a=qn({add:e,replace:t,remove:s,move:n,copy:r,test:i});return JSON.stringify(a)}}class nr extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNGetDataSyncMembershipOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Membership id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/memberships/${fe(t)}`}}class rr extends ot{constructor(e){super({method:nt.POST}),this.parameters=e}operation(){return $e.PNCreateDataSyncRelationshipOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.entityAId?this.parameters.entityBId?this.parameters.class?this.parameters.data?this.parameters.data.classVersion?void 0:"Relationship class version cannot be empty":"Relationship data cannot be empty":"Relationship class cannot be empty":"Entity B id cannot be empty":"Entity A id cannot be empty"}get headers(){var e;const t=null!==(e=super.headers)&&void 0!==e?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.relationship+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships`}get body(){const{id:e,class:t,entityAId:s,entityBId:n,data:r}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e?{id:e}:{}),{entityAId:s,entityBId:n,relationshipClass:t,relationshipClassVersion:r.classVersion}),void 0!==r.status?{status:r.status}:{}),void 0!==r.payload?{payload:r.payload}:{})})}}class ir extends ot{constructor(e){var t;super(),this.parameters=e,null!==(t=e.limit)&&void 0!==t||(e.limit=20)}operation(){return $e.PNGetDataSyncRelationshipsOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.class)return"Relationship class cannot be empty"}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/relationships`}get queryParameters(){const{class:e,classVersion:t,entityAId:s,entityBId:n,cursor:r,limit:i,filter:a,filterFast:o,sort:c}=this.parameters,u=xn(c);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({relationship_class:e},void 0!==t?{relationship_class_version:`${t}`}:{}),s?{entity_a_id:s}:{}),n?{entity_b_id:n}:{}),r?{cursor:r}:{}),i?{limit:`${i}`}:{}),a?{filter:a}:{}),o?{filter_fast:o}:{}),u.length?{sort:u}:{})}}class ar extends ot{constructor(e){super({method:nt.PUT}),this.parameters=e}operation(){return $e.PNSetDataSyncRelationshipOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.entityAId?this.parameters.entityBId?this.parameters.data?this.parameters.data.classVersion?void 0:"Relationship class version cannot be empty":"Relationship data cannot be empty":"Entity B id cannot be empty":"Entity A id cannot be empty":"Relationship id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.relationship+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships/${fe(t)}`}get body(){const{entityAId:e,entityBId:t,data:s}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({entityAId:e,entityBId:t,relationshipClassVersion:s.classVersion},void 0!==s.status?{status:s.status}:{}),void 0!==s.payload?{payload:s.payload}:{})})}}class or extends ot{constructor(e){super({method:nt.DELETE}),this.parameters=e}operation(){return $e.PNRemoveDataSyncRelationshipOperation}validate(){if(!this.parameters.id)return"Relationship id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships/${fe(t)}`}}class cr extends ot{constructor(e){super({method:nt.PATCH}),this.parameters=e}operation(){return $e.PNUpdateDataSyncRelationshipOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Relationship id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,a=e&&Object.keys(e).length>0,o=t&&Object.keys(t).length>0,c=s&&s.length>0,u=n&&n.length>0,l=r&&r.length>0,h=i&&Object.keys(i).length>0;return a||o||c||u||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships/${fe(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,a=qn({add:e,replace:t,remove:s,move:n,copy:r,test:i});return JSON.stringify(a)}}class ur extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNGetDataSyncRelationshipOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Relationship id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/relationships/${fe(t)}`}}class lr extends ot{constructor(e){super({method:nt.POST}),this.parameters=e}operation(){return $e.PNCreateDataSyncEntityOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.class?this.parameters.data?void 0===this.parameters.data.classVersion||null===this.parameters.data.classVersion?"Entity class version cannot be empty":void 0:"Entity data cannot be empty":"Entity class cannot be empty"}get headers(){var e;const t=null!==(e=super.headers)&&void 0!==e?e:{};return Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.entity+json;version=1"})}get path(){const{keySet:{subscribeKey:e}}=this.parameters;return`/v1/datasync/subkeys/${e}/entities`}get body(){const{id:e,class:t,classLevel:s,data:n}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==e?{id:e}:{}),{entityClass:t,entityClassVersion:n.classVersion}),void 0!==s?{entityClassLevel:s}:{}),void 0!==n.status?{status:n.status}:{}),void 0!==n.payload?{payload:n.payload}:{})})}}class hr extends ot{constructor(e){var t;super(),this.parameters=e,null!==(t=e.limit)&&void 0!==t||(e.limit=20)}operation(){return $e.PNGetDataSyncEntitiesOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.class)return"Entity class cannot be empty"}get path(){return`/v1/datasync/subkeys/${this.parameters.keySet.subscribeKey}/entities`}get queryParameters(){const{class:e,classVersion:t,classLevel:s,cursor:n,limit:r,filter:i,filterFast:a,sort:o}=this.parameters,c=xn(o);return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({entity_class:e},void 0!==t?{entity_class_version:`${t}`}:{}),s?{entity_class_level:s}:{}),n?{cursor:n}:{}),r?{limit:`${r}`}:{}),i?{filter:i}:{}),a?{filter_fast:a}:{}),c.length?{sort:c}:{})}}class dr extends ot{constructor(e){super({method:nt.PUT}),this.parameters=e}operation(){return $e.PNSetDataSyncEntityOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){return this.parameters.id?this.parameters.data?void 0===this.parameters.data.classVersion||null===this.parameters.data.classVersion?"Entity class version cannot be empty":void 0:"Entity data cannot be empty":"Entity id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/vnd.pubnub.objects.entity+json;version=1"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/entities/${fe(t)}`}get body(){const{data:e}=this.parameters;return JSON.stringify({data:Object.assign(Object.assign({entityClassVersion:e.classVersion},void 0!==e.status?{status:e.status}:{}),void 0!==e.payload?{payload:e.payload}:{})})}}class pr extends ot{constructor(e){super({method:nt.DELETE}),this.parameters=e}operation(){return $e.PNRemoveDataSyncEntityOperation}validate(){if(!this.parameters.id)return"Entity id cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.keys(t).length>0?t:void 0}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status}}))}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/entities/${fe(t)}`}}class gr extends ot{constructor(e){super({method:nt.PATCH}),this.parameters=e}operation(){return $e.PNUpdateDataSyncEntityOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Entity id cannot be empty";const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,a=e&&Object.keys(e).length>0,o=t&&Object.keys(t).length>0,c=s&&s.length>0,u=n&&n.length>0,l=r&&r.length>0,h=i&&Object.keys(i).length>0;return a||o||c||u||l||h?void 0:"At least one of add, replace, remove, move, copy, or test must be provided"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json-patch+json"})}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/entities/${fe(t)}`}get body(){const{add:e,replace:t,remove:s,move:n,copy:r,test:i}=this.parameters,a=qn({add:e,replace:t,remove:s,move:n,copy:r,test:i});return JSON.stringify(a)}}class br extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNGetDataSyncEntityOperation}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return Object.assign(Object.assign({},t),{status:e.status})}))}validate(){if(!this.parameters.id)return"Entity id cannot be empty"}get path(){const{keySet:{subscribeKey:e},id:t}=this.parameters;return`/v1/datasync/subkeys/${e}/entities/${fe(t)}`}}class yr{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}get logger(){return this.configuration.logger()}createEntity(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Entity with parameters:"})));const s=new lr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getEntity(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Entity with parameters:"})));const s=new br(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getEntities(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Entities with parameters:"})));const s=new hr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setEntity(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Entity with parameters:"})));const s=new dr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateEntity(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Entity with parameters:"})));const s=new gr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeEntity(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Entity with parameters:"})));const s=new pr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}createRelationship(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Relationship with parameters:"})));const s=new rr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getRelationship(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Relationship with parameters:"})));const s=new ur(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getRelationships(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Relationships with parameters:"})));const s=new ir(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}setRelationship(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Relationship with parameters:"})));const s=new ar(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateRelationship(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Relationship with parameters:"})));const s=new cr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeRelationship(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Relationship with parameters:"})));const s=new or(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create User with parameters:"})));const s=new Fn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getUser(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get User with parameters:"})));const s=new Vn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getUsers(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},s),details:"Get Users with parameters:"})));const n=new Ln(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setUser(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set User with parameters:"})));const s=new Gn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update User with parameters:"})));const s=new Hn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove User with parameters:"})));const s=new Kn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}createChannel(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Channel with parameters:"})));const s=new Wn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannel(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Channel with parameters:"})));const s=new Xn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getChannels(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},s),details:"Get Channels with parameters:"})));const n=new Bn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setChannel(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Channel with parameters:"})));const s=new zn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateChannel(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Channel with parameters:"})));const s=new Yn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeChannel(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Channel with parameters:"})));const s=new Jn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}createMembership(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Membership with parameters:"})));const s=new Qn(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMembership(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Membership with parameters:"})));const s=new nr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},s),details:"Get Memberships with parameters:"})));const n=new Zn(Object.assign(Object.assign({},s),{keySet:this.keySet}));return t?this.sendRequest(n,t):this.sendRequest(n)}))}setMembership(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Membership with parameters:"})));const s=new er(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}updateMembership(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Membership with parameters:"})));const s=new sr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}removeMembership(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Membership with parameters:"})));const s=new tr(Object.assign(Object.assign({},e),{keySet:this.keySet}));return t?this.sendRequest(s,t):this.sendRequest(s)}))}}class mr extends ot{constructor(){super()}operation(){return $e.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[0]}}))}get path(){return"/time/0"}}class fr extends ot{constructor(e){super(),this.parameters=e}operation(){return $e.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:r,PubNubFile:i}=this.parameters,a=e.headers["content-type"];let o,c=e.body;return i.supportsEncryptFile&&(t||s)&&(t&&n?c=yield n.decrypt(t,c):!t&&s&&(o=yield s.decryptFile(i.create({data:c,name:r,mimeType:a}),i))),o||i.create({data:c,name:r,mimeType:a})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${fe(t)}/files/${fe(s)}/${fe(n)}`}}class vr{static notificationPayload(e,t){return new Ot(e,t)}static generateUUID(){return Qe.createUUID()}constructor(e){if(this.eventHandleCapable={},this.entities={},this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this.logger.debug("PubNub",(()=>({messageType:"object",message:e.configuration,details:"Create with configuration:",ignoredKeys:(e,t)=>"function"==typeof t[e]||e.startsWith("_")||"keySet"===e||me(e)}))),this._objects=new $n(this._configuration,this.sendRequest.bind(this)),this._dataSync=new yr(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new fn(this._configuration.logger(),this._configuration.keySet,this.sendRequest.bind(this)),this._push=new kn(this._configuration.logger(),this._configuration.keySet,this.sendRequest.bind(this)),this.eventDispatcher=new pt,this._configuration.enableEventEngine){this.logger.debug("PubNub","Using new subscription loop management.");let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new Xt({heartbeat:(e,t)=>(this.logger.trace("PresenceEventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Heartbeat with parameters:"}))),this.heartbeat(e,t)),leave:e=>{this.logger.trace("PresenceEventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),this.makeUnsubscribe(e,(()=>{}))},heartbeatDelay:()=>{let t=()=>{};const s=new Promise(((s,n)=>{if(e=this._configuration.getHeartbeatInterval(),e){const r=setTimeout((()=>{s()}),1e3*e);t=()=>{clearTimeout(r),n(new d("Heartbeat interval has been cancelled."))}}else n(new d("Heartbeat interval has been reset."))}));return{cancelDelay:t,promise:s}},emitStatus:e=>this.emitStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new vs({handshake:e=>(this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Handshake with parameters:",ignoredKeys:["abortSignal","crypto","timeout","keySet","getFileUrl"]}))),this.subscribeHandshake(e)),receiveMessages:e=>(this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Receive messages with parameters:",ignoredKeys:["abortSignal","crypto","timeout","keySet","getFileUrl"]}))),this.subscribeReceiveMessages(e)),join:e=>{var t,s;this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Join with parameters:"}))),e&&0===(null!==(t=e.channels)&&void 0!==t?t:[]).length&&0===(null!==(s=e.groups)&&void 0!==s?s:[]).length?this.logger.trace("EventEngine","Ignoring 'join' announcement request."):this.join(e)},leave:e=>{var t,s;this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),e&&0===(null!==(t=e.channels)&&void 0!==t?t:[]).length&&0===(null!==(s=e.groups)&&void 0!==s?s:[]).length?this.logger.trace("EventEngine","Ignoring 'leave' announcement request."):this.leave(e)},leaveAll:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave all with parameters:"}))),this.leaveAll(e)},presenceReconnect:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Reconnect with parameters:"}))),this.presenceReconnect(e)},presenceDisconnect:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Disconnect with parameters:"}))),this.presenceDisconnect(e)},presenceState:this.presenceState,config:this._configuration,emitMessages:(e,t)=>{try{this.logger.debug("EventEngine",(()=>({messageType:"object",message:t.map((e=>{const t=e.type===ct.Message||e.type===ct.Signal?Ce(e.data.message):void 0;return t?{type:e.type,data:Object.assign(Object.assign({},e.data),{pn_mfp:t})}:e})),details:"Received events:"}))),t.forEach((t=>this.emitEvent(e,t)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.emitStatus(t)}},emitStatus:e=>this.emitStatus(e)})}else this.logger.debug("PubNub","Using legacy subscription loop management."),this.subscriptionManager=new yt(this._configuration,((e,t)=>{try{this.emitEvent(e,t)}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.emitStatus(t)}}),this.emitStatus.bind(this),((e,t)=>{this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},e),details:"Subscribe with parameters:",ignoredKeys:["crypto","timeout","keySet","getFileUrl"]}))),this.makeSubscribe(e,t)}),((e,t)=>(this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},e),details:"Heartbeat with parameters:",ignoredKeys:["crypto","timeout","keySet","getFileUrl"]}))),this.heartbeat(e,t))),((e,t)=>{this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),this.makeUnsubscribe(e,t)}),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this.logger.debug("PubNub","Auth key updated."),this._configuration.setAuthKey(e),this.onAuthenticationChange&&this.onAuthenticationChange(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length){const e=new Error("Missing or invalid userId parameter. Provide a valid string userId");throw this.logger.error("PubNub",(()=>({messageType:"error",message:e}))),e}this.logger.debug("PubNub",`Set user ID: ${e}`),this._configuration.userId=e,this.onUserIdChange&&this.onUserIdChange(this._configuration.userId)}getUserId(){return this._configuration.userId}setUserId(e){this.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this.logger.debug("PubNub",`Set filter expression: ${e}`),this._configuration.setFilterExpression(e)}setFilterExpression(e){this.logger.debug("PubNub",`Set filter expression: ${e}`),this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.logger.debug("PubNub","Cipher key updated."),this.cipherKey=e}set heartbeatInterval(e){var t;this.logger.debug("PubNub",`Set heartbeat interval: ${e}`),this._configuration.setHeartbeatInterval(e),this.onHeartbeatIntervalChange&&this.onHeartbeatIntervalChange(null!==(t=this._configuration.getHeartbeatInterval())&&void 0!==t?t:0)}setHeartbeatInterval(e){this.heartbeatInterval=e}get logger(){return this._configuration.logger()}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this.logger.debug("PubNub",`Add '${e}' 'pnsdk' suffix: ${t}`),this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.logger.warn("PubNub","'setUserId` is deprecated, please use 'setUserId' or 'userId' setter instead."),this.logger.debug("PubNub",`Set UUID: ${e}`),this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){let t=this.entities[`${e}_ch`];return t||(t=this.entities[`${e}_ch`]=new dn(e,this)),t}channelGroup(e){let t=this.entities[`${e}_chg`];return t||(t=this.entities[`${e}_chg`]=new ln(e,this)),t}channelMetadata(e){let t=this.entities[`${e}_chm`];return t||(t=this.entities[`${e}_chm`]=new cn(e,this)),t}userMetadata(e){let t=this.entities[`${e}_um`];return t||(t=this.entities[`${e}_um`]=new hn(e,this)),t}dataSyncUser(e){let t=this.entities[`${e}_dsu`];return t||(t=this.entities[`${e}_dsu`]=new un(e,this)),t}dataSyncChannel(e){let t=this.entities[`${e}_dsc`];return t||(t=this.entities[`${e}_dsc`]=new an(e,this)),t}dataSyncMembership(e){let t=this.entities[`${e}_dsm`];return t||(t=this.entities[`${e}_dsm`]=new rn(e,this)),t}dataSyncEntity(e){let t=this.entities[`${e}_dse`];return t||(t=this.entities[`${e}_dse`]=new on(e,this)),t}dataSyncRelationship(e){let t=this.entities[`${e}_dsr`];return t||(t=this.entities[`${e}_dsr`]=new nn(e,this)),t}subscriptionSet(e){var t,s;{const n=[];return null===(t=e.channels)||void 0===t||t.forEach((e=>n.push(this.channel(e)))),null===(s=e.channelGroups)||void 0===s||s.forEach((e=>n.push(this.channelGroup(e)))),new Ts({client:this,entities:n,options:e.subscriptionOptions})}}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const s=e.validate();if(s){const e=(n=s,p(Object.assign({message:n},{}),h.PNValidationErrorCategory));if(this.logger.error("PubNub",(()=>({messageType:"error",message:e}))),t)return t(e,null);throw new d("Validation failed, check status for details",e)}var n;const r=e.request(),i=e.operation();r.formData&&r.formData.length>0||i===$e.PNDownloadFileOperation?r.timeout=this._configuration.getFileTimeout():i===$e.PNSubscribeOperation||i===$e.PNReceiveMessagesOperation?r.timeout=this._configuration.getSubscribeTimeout():r.timeout=this._configuration.getTransactionTimeout();const a={error:!1,operation:i,category:h.PNAcknowledgmentCategory,statusCode:0},[o,c]=this.transport.makeSendable(r);return e.cancellationController=c||null,o.then((t=>{if(a.statusCode=t.status,200!==t.status&&204!==t.status){const e=vr.decoder.decode(t.body),s=t.headers["content-type"];if(s||-1!==s.indexOf("javascript")||-1!==s.indexOf("json")){const t=JSON.parse(e);"object"==typeof t&&"error"in t&&t.error&&"object"==typeof t.error&&(a.errorData=t.error)}else a.responseText=e}return e.parse(t)})).then((e=>t?t(a,e):e)).catch((e=>{const s=e instanceof De?e:De.create(e);if(t)return s.category!==h.PNCancelledCategory&&this.logger.error("PubNub",(()=>({messageType:"error",message:s.toPubNubError(i,"REST API request processing error, check status for details")}))),t(s.toStatus(i),null);const n=s.toPubNubError(i,"REST API request processing error, check status for details");throw s.category!==h.PNCancelledCategory&&this.logger.error("PubNub",(()=>({messageType:"error",message:n}))),n}))}))}destroy(e=!1){this.logger.info("PubNub","Destroying PubNub client."),this._globalSubscriptionSet&&(this._globalSubscriptionSet.invalidate(!0),this._globalSubscriptionSet=void 0),Object.values(this.eventHandleCapable).forEach((e=>e.invalidate(!0))),this.eventHandleCapable={},this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.unsubscribeAll(e),this.presenceEventEngine&&this.presenceEventEngine.leaveAll(e)}stop(){this.logger.warn("PubNub","'stop' is deprecated, please use 'destroy' instead."),this.destroy()}publish(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Publish with parameters:"})));const s=!1===e.replicate&&!1===e.storeInHistory,n=new Os(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),r=e=>{e&&this.logger.debug("PubNub",`${s?"Fire":"Publish"} success with timetoken: ${e.timetoken}`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}}))}signal(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Signal with parameters:"})));const s=new Ss(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Publish success with timetoken: ${e.timetoken}`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}fire(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fire with parameters:"}))),null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}get globalSubscriptionSet(){return this._globalSubscriptionSet||(this._globalSubscriptionSet=this.subscriptionSet({})),this._globalSubscriptionSet}get subscriptionTimetoken(){return this.subscriptionManager?this.subscriptionManager.subscriptionTimetoken:this.eventEngine?this.eventEngine.subscriptionTimetoken:void 0}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}registerEventHandleCapable(e,t,s){{let n;this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign(Object.assign({subscription:e},t?{cursor:t}:[]),s?{subscriptions:s}:{}),details:"Register event handle capable:"}))),this.eventHandleCapable[e.state.id]||(this.eventHandleCapable[e.state.id]=e),s&&0!==s.length?(n=new Ps({}),s.forEach((e=>n.add(e.subscriptionInput(!1))))):n=e.subscriptionInput(!1);const r={};r.channels=n.channels,r.channelGroups=n.channelGroups,t&&(r.timetoken=t.timetoken),this.subscriptionManager?this.subscriptionManager.subscribe(r):this.eventEngine&&this.eventEngine.subscribe(r)}}unregisterEventHandleCapable(e,t){{if(!this.eventHandleCapable[e.state.id])return;const s=[];this.logger.trace("PubNub",(()=>({messageType:"object",message:{subscription:e,subscriptions:t},details:"Unregister event handle capable:"})));let n,r=!t||0===t.length;if(!r&&e instanceof Ts&&e.subscriptions.length===(null==t?void 0:t.length)&&(r=e.subscriptions.every((e=>t.includes(e)))),r&&delete this.eventHandleCapable[e.state.id],t&&0!==t.length?(n=new Ps({}),t.forEach((e=>{const t=e.subscriptionInput(!0);t.isEmpty?s.push(e):n.add(t)}))):(n=e.subscriptionInput(!0),n.isEmpty&&s.push(e)),s.length>0&&this.logger.trace("PubNub",(()=>{const e=[];return s[0]instanceof Ts?s[0].subscriptions.forEach((t=>e.push(t.state.entity))):s.forEach((t=>e.push(t.state.entity))),{messageType:"object",message:{entities:e},details:"Can't unregister event handle capable because entities still in use:"}})),n.isEmpty)return;{const e=[],t=[];if(Object.values(this.eventHandleCapable).forEach((s=>{const r=s.subscriptionInput(!1),i=r.channelGroups,a=r.channels;e.push(...n.channelGroups.filter((e=>i.includes(e)))),t.push(...n.channels.filter((e=>a.includes(e))))})),(t.length>0||e.length>0)&&(this.logger.trace("PubNub",(()=>{const s=[],r=n=>{const r=n.subscriptionNames(!0),i=n.subscriptionType===ks.Channel?t:e;r.some((e=>i.includes(e)))&&s.push(n)};Object.values(this.eventHandleCapable).forEach((e=>{e instanceof Ts?e.subscriptions.forEach((e=>{r(e.state.entity)})):e instanceof Rs&&r(e.state.entity)}));let i="Some entities still in use:";return t.length+e.length===n.length&&(i="Can't unregister event handle capable because entities still in use:"),{messageType:"object",message:{entities:s},details:i}})),n.remove(new Ps({channels:t,channelGroups:e})),n.isEmpty))return}const i={};i.channels=n.channels,i.channelGroups=n.channelGroups,this.subscriptionManager?this.subscriptionManager.unsubscribe(i):this.eventEngine&&this.eventEngine.unsubscribe(i)}}subscribe(e){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Subscribe with parameters:"})));const t=this.subscriptionSet(Object.assign(Object.assign({},e),{subscriptionOptions:{receivePresenceEvents:e.withPresence}}));this.globalSubscriptionSet.addSubscriptionSet(t),t.dispose();const s="number"==typeof e.timetoken?`${e.timetoken}`:e.timetoken;this.globalSubscriptionSet.subscribe({timetoken:s})}}makeSubscribe(e,t){{this._configuration.isSharedWorkerEnabled()||(e.onDemand=!1);const s=new dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((e,n)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,n)})),this.subscriptionManager){const e=()=>s.abort("Cancel long-poll subscribe request");e.identifier=s.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){{if(this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Unsubscribe with parameters:"}))),!this._globalSubscriptionSet)return void this.logger.debug("PubNub","There are no active subscriptions. Ignore.");const t=this.globalSubscriptionSet.subscriptions.filter((t=>{var s,n;const r=t.subscriptionInput(!1);if(r.isEmpty)return!1;for(const t of null!==(s=e.channels)&&void 0!==s?s:[])if(r.contains(t))return!0;for(const t of null!==(n=e.channelGroups)&&void 0!==n?n:[])if(r.contains(t))return!0}));t.length>0&&this.globalSubscriptionSet.removeSubscriptions(t)}}makeUnsubscribe(e,t){{let{channels:s,channelGroups:n}=e;if(this._configuration.getKeepPresenceChannelsInPresenceRequests()||(n&&(n=n.filter((e=>!e.endsWith("-pnpres")))),s&&(s=s.filter((e=>!e.endsWith("-pnpres"))))),0===(null!=n?n:[]).length&&0===(null!=s?s:[]).length)return t({error:!1,operation:$e.PNUnsubscribeOperation,category:h.PNAcknowledgmentCategory,statusCode:200});this.sendRequest(new Ds({channels:s,channelGroups:n,keySet:this._configuration.keySet}),t)}}unsubscribeAll(){this.logger.debug("PubNub","Unsubscribe all channels and groups"),this._globalSubscriptionSet&&this._globalSubscriptionSet.invalidate(!1),Object.values(this.eventHandleCapable).forEach((e=>e.invalidate(!1))),this.eventHandleCapable={},this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(e=!1){this.logger.debug("PubNub",`Disconnect (while offline? ${e?"yes":"no"})`),this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect(e)}reconnect(e){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Reconnect with parameters:"}))),this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){{this._configuration.isSharedWorkerEnabled()||(e.onDemand=!1),e.heartbeat||(e.heartbeat=this._configuration.getPresenceTimeout());const t=new ws(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort("Cancel subscribe handshake request")}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){{this._configuration.isSharedWorkerEnabled()||(e.onDemand=!1),e.heartbeat||(e.heartbeat=this._configuration.getPresenceTimeout());const t=new js(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort("Cancel long-poll subscribe request")}));return this.sendRequest(t).then((e=>(s(),e)))}}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get message actions with parameters:"})));const s=new Ks(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Get message actions success. Received ${e.data.length} message actions.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add message action with parameters:"})));const s=new Hs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Message action add success. Message action added with timetoken: ${e.data.actionTimetoken}`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove message action with parameters:"})));const s=new Vs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Message action remove success. Removed message action with ${e.actionTimetoken} timetoken.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch messages with parameters:"})));const s=new Gs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e=>{if(!e)return;const t=Object.values(e.channels).reduce(((e,t)=>e+t.length),0);this.logger.debug("PubNub",`Fetch messages success. Received ${t} messages.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Delete messages with parameters:"})));const s=new Fs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub","Delete messages success.")};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get messages count with parameters:"})));const s=new xs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=t=>{if(!t)return;const s=Object.values(t.channels).reduce(((e,t)=>e+t),0);this.logger.debug("PubNub",`Get messages count success. There are ${s} messages since provided reference timetoken${e.channelTimetokens?e.channelTimetokens.join(","):""}.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}history(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch history with parameters:"})));const s=new qs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),n=e=>{e&&this.logger.debug("PubNub",`Fetch history success. Received ${e.messages.length} messages.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Here now with parameters:"})));const s=new $s(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Here now success. There are ${e.totalOccupancy} participants in ${e.totalChannels} channels.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var s;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Where now with parameters:"})));const n=new As({uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet}),r=e=>{e&&this.logger.debug("PubNub",`Where now success. Currently present in ${e.channels.length} channels.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}}))}getState(e,t){return i(this,void 0,void 0,(function*(){var s;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get presence state with parameters:"})));const n=new Ms(Object.assign(Object.assign({},e),{uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Get presence state success. Received presence state for ${Object.keys(e.channels).length} channels.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}}))}setState(e,t){return i(this,void 0,void 0,(function*(){var s,n;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set presence state with parameters:"})));const{keySet:r,userId:i}=this._configuration,a=this._configuration.getPresenceTimeout();let o;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(s=e.channels)||void 0===s||s.forEach((s=>t[s]=e.state)),"channelGroups"in e&&(null===(n=e.channelGroups)||void 0===n||n.forEach((s=>t[s]=e.state))),this.onPresenceStateChange&&this.onPresenceStateChange(this.presenceState)}o="withHeartbeat"in e&&e.withHeartbeat?new _s(Object.assign(Object.assign({},e),{keySet:r,heartbeat:a})):new Us(Object.assign(Object.assign({},e),{keySet:r,uuid:i}));const c=e=>{e&&this.logger.debug("PubNub","Set presence state success."+(o instanceof _s?" Presence state has been set using heartbeat endpoint.":""))};return this.subscriptionManager&&(this.subscriptionManager.setState(e),this.onPresenceStateChange&&this.onPresenceStateChange(this.subscriptionManager.presenceState)),t?this.sendRequest(o,((e,s)=>{c(s),t(e,s)})):this.sendRequest(o).then((e=>(c(e),e)))}}))}presence(e){var t;this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Change presence with parameters:"}))),null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){var s;{this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Heartbeat with parameters:"})));let{channels:n,channelGroups:r}=e;if(r&&(r=r.filter((e=>!e.endsWith("-pnpres")))),n&&(n=n.filter((e=>!e.endsWith("-pnpres")))),0===(null!=r?r:[]).length&&0===(null!=n?n:[]).length){const e={error:!1,operation:$e.PNHeartbeatOperation,category:h.PNAcknowledgmentCategory,statusCode:200};return this.logger.trace("PubNub","There are no active subscriptions. Ignore."),t?t(e,{}):Promise.resolve(e)}const i=new _s(Object.assign(Object.assign({},e),{channels:[...new Set(n)],channelGroups:[...new Set(r)],keySet:this._configuration.keySet})),a=e=>{e&&this.logger.trace("PubNub","Heartbeat success.")},o=null===(s=e.abortSignal)||void 0===s?void 0:s.subscribe((e=>{i.abort("Cancel long-poll subscribe request")}));return t?this.sendRequest(i,((e,s)=>{a(s),o&&o(),t(e,s)})):this.sendRequest(i).then((e=>(a(e),o&&o(),e)))}}))}join(e){var t,s;this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Join with parameters:"}))),e&&0===(null!==(t=e.channels)&&void 0!==t?t:[]).length&&0===(null!==(s=e.groups)&&void 0!==s?s:[]).length?this.logger.trace("PubNub","Ignoring 'join' announcement request."):this.presenceEventEngine?this.presenceEventEngine.join(e):this.heartbeat(Object.assign(Object.assign({channels:e.channels,channelGroups:e.groups},this._configuration.maintainPresenceState&&this.presenceState&&Object.keys(this.presenceState).length>0&&{state:this.presenceState}),{heartbeat:this._configuration.getPresenceTimeout()}),(()=>{}))}presenceReconnect(e){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Presence reconnect with parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.reconnect():this.heartbeat(Object.assign(Object.assign({channels:e.channels,channelGroups:e.groups},this._configuration.maintainPresenceState&&{state:this.presenceState}),{heartbeat:this._configuration.getPresenceTimeout()}),(()=>{}))}leave(e){var t,s,n;this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),e&&0===(null!==(t=e.channels)&&void 0!==t?t:[]).length&&0===(null!==(s=e.groups)&&void 0!==s?s:[]).length?this.logger.trace("PubNub","Ignoring 'leave' announcement request."):this.presenceEventEngine?null===(n=this.presenceEventEngine)||void 0===n||n.leave(e):this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}leaveAll(e={}){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave all with parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.leaveAll(!!e.isOffline):e.isOffline||this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}presenceDisconnect(e){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Presence disconnect parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.disconnect(!!e.isOffline):e.isOffline||this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}grantToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e),this.onAuthenticationChange&&this.onAuthenticationChange(e)}setToken(e){this.logger.debug("PubNub","Access token updated."),this.token=e}parseToken(e){return this.logger.debug("PubNub","Parse access token."),this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}get dataSync(){return this._dataSync}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchUsers' is deprecated. Use 'pubnub.objects.getAllUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Fetch all User objects with parameters:"}))),this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchUser' is deprecated. Use 'pubnub.objects.getUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.userId},details:`Fetch${e&&"function"!=typeof e?"":" current"} User object with parameters:`}))),this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'createUser' is deprecated. Use 'pubnub.objects.setUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create User object with parameters:"}))),this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'updateUser' is deprecated. Use 'pubnub.objects.setUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update User object with parameters:"}))),this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'removeUser' is deprecated. Use 'pubnub.objects.removeUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.userId},details:`Remove${e&&"function"!=typeof e?"":" current"} User object with parameters:`}))),this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchSpaces' is deprecated. Use 'pubnub.objects.getAllChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Fetch all Space objects with parameters:"}))),this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchSpace' is deprecated. Use 'pubnub.objects.getChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch Space object with parameters:"}))),this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'createSpace' is deprecated. Use 'pubnub.objects.setChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Space object with parameters:"}))),this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'updateSpace' is deprecated. Use 'pubnub.objects.setChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Space object with parameters:"}))),this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'removeSpace' is deprecated. Use 'pubnub.objects.removeChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Space object with parameters:"}))),this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'addMemberships' is deprecated. Use 'pubnub.objects.setChannelMembers' or 'pubnub.objects.setMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update memberships with parameters:"}))),this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r;{if(this.logger.warn("PubNub","'removeMemberships' is deprecated. Use 'pubnub.objects.removeMemberships' or 'pubnub.objects.removeChannelMembers' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove memberships with parameters:"}))),"spaceId"in e){const r=e,i={channel:null!==(s=r.spaceId)&&void 0!==s?s:r.channel,uuids:null!==(n=r.userIds)&&void 0!==n?n:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,a={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(a,t):this.objects.removeMemberships(a)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Send file with parameters:"})));const s=new Qs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:$e.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0},r=e=>{e&&this.logger.debug("PubNub",`Send file success. File shared with ${e.id} ID.`)};return s.process().then((e=>(n.statusCode=e.status,r(e),t?t(n,e):e))).catch((e=>{let s;throw e instanceof d?s=e.status:e instanceof De&&(s=e.toStatus(n.operation)),this.logger.error("PubNub",(()=>({messageType:"error",message:new d("File sending error. Check status for details",s)}))),t&&s&&t(s,null),new d("REST API request processing error. Check status for details",s)}))}}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Publish file message with parameters:"})));const s=new Ws(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),n=e=>{e&&this.logger.debug("PubNub",`Publish file message success. File message published with timetoken: ${e.timetoken}`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List files with parameters:"})));const s=new Js(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`List files success. There are ${e.count} uploaded files.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}getFileUrl(e){var t;{const s=this.transport.request(new Bs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=null!==(t=s.queryParameters)&&void 0!==t?t:{},r=Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${fe(t)}`)).join("&"):`${e}=${fe(t)}`})).join("&");return`${s.origin}${s.path}?${r}`}}downloadFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Download file with parameters:"})));const s=new fr(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()})),n=e=>{e&&this.logger.debug("PubNub","Download file success.")};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):yield this.sendRequest(s).then((e=>(n(e),e)))}}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Delete file with parameters:"})));const s=new zs(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Delete file success. Deleted file with ${e.id} ID.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}time(e){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub","Get service time.");const t=new mr,s=e=>{e&&this.logger.debug("PubNub",`Get service time success. Current timetoken: ${e.timetoken}`)};return e?this.sendRequest(t,((t,n)=>{s(n),e(t,n)})):this.sendRequest(t).then((e=>(s(e),e)))}))}emitStatus(e){var t;null===(t=this.eventDispatcher)||void 0===t||t.handleStatus(e)}emitEvent(e,t){var s;this._globalSubscriptionSet&&this._globalSubscriptionSet.handleEvent(e,t),null===(s=this.eventDispatcher)||void 0===s||s.handleEvent(t),Object.values(this.eventHandleCapable).forEach((s=>{s!==this._globalSubscriptionSet&&s.handleEvent(e,t)}))}set onStatus(e){this.eventDispatcher&&(this.eventDispatcher.onStatus=e)}set onMessage(e){this.eventDispatcher&&(this.eventDispatcher.onMessage=e)}set onPresence(e){this.eventDispatcher&&(this.eventDispatcher.onPresence=e)}set onSignal(e){this.eventDispatcher&&(this.eventDispatcher.onSignal=e)}set onObjects(e){this.eventDispatcher&&(this.eventDispatcher.onObjects=e)}set onMessageAction(e){this.eventDispatcher&&(this.eventDispatcher.onMessageAction=e)}set onFile(e){this.eventDispatcher&&(this.eventDispatcher.onFile=e)}set onDataSync(e){this.eventDispatcher&&(this.eventDispatcher.onDataSync=e)}addListener(e){this.eventDispatcher&&this.eventDispatcher.addListener(e)}removeListener(e){this.eventDispatcher&&this.eventDispatcher.removeListener(e)}removeAllListeners(){this.eventDispatcher&&this.eventDispatcher.removeAllListeners()}encrypt(e,t){this.logger.warn("PubNub","'encrypt' is deprecated. Use cryptoModule instead.");const s=this._configuration.getCryptoModule();if(!t&&s&&"string"==typeof e){const t=s.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){this.logger.warn("PubNub","'decrypt' is deprecated. Use cryptoModule instead.");const s=this._configuration.getCryptoModule();if(!t&&s){const t=s.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}vr.decoder=new TextDecoder,vr.OPERATIONS=$e,vr.CATEGORIES=h,vr.Endpoint=He,vr.ExponentialRetryPolicy=Ve.ExponentialRetryPolicy,vr.LinearRetryPolicy=Ve.LinearRetryPolicy,vr.NoneRetryPolicy=Ve.None,vr.LogLevel=Le;class Or{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return"object"==typeof n?n:void 0}}class Sr extends vr{constructor(e){var t;const s=void 0!==e.subscriptionWorkerUrl,r=qe(e),i=Object.assign(Object.assign({},r),{sdkFamily:"Web"});i.PubNubFile=o;const a=Ze(i,(e=>{if(e.cipherKey){return new Me({default:new Re(Object.assign(Object.assign({},e),e.logger?{}:{logger:a.logger()})),cryptors:[new pe({cipherKey:e.cipherKey})]})}}));let u,l;e.subscriptionWorkerLogVerbosity?e.subscriptionWorkerLogLevel=Le.Debug:void 0===e.subscriptionWorkerLogLevel&&(e.subscriptionWorkerLogLevel=Le.None),void 0!==e.subscriptionWorkerLogVerbosity&&a.logger().warn("Configuration","'subscriptionWorkerLogVerbosity' is deprecated. Use 'subscriptionWorkerLogLevel' instead."),a.getCryptoModule()&&(a.getCryptoModule().logger=a.logger()),u=new st(new Or((e=>xe(n.decode(e))),c)),(a.getCipherKey()||a.secretKey)&&(l=new Te({secretKey:a.secretKey,cipherKey:a.getCipherKey(),useRandomIVs:a.getUseRandomIVs(),customEncrypt:a.getCustomEncrypt(),customDecrypt:a.getCustomDecrypt(),logger:a.logger()}));let h,d=()=>{},p=()=>{},g=()=>{},b=()=>{};h=new Ie;let y=new at(a.logger(),i.transport);if(r.subscriptionWorkerUrl)try{const e=new Fe({clientIdentifier:a._instanceId,subscriptionKey:a.subscribeKey,userId:a.getUserId(),workerUrl:r.subscriptionWorkerUrl,sdkVersion:a.getVersion(),heartbeatInterval:a.getHeartbeatInterval(),announceSuccessfulHeartbeats:a.announceSuccessfulHeartbeats,announceFailedHeartbeats:a.announceFailedHeartbeats,workerOfflineClientsCheckInterval:i.subscriptionWorkerOfflineClientsCheckInterval,workerUnsubscribeOfflineClients:i.subscriptionWorkerUnsubscribeOfflineClients,workerLogLevel:i.subscriptionWorkerLogLevel,tokenManager:u,transport:y,logger:a.logger()});p=t=>e.onPresenceStateChange(t),d=t=>e.onHeartbeatIntervalChange(t),g=t=>e.onTokenChange(t),b=t=>e.onUserIdChange(t),y=e,r.subscriptionWorkerUnsubscribeOfflineClients&&"undefined"!=typeof window&&window.addEventListener&&window.addEventListener("pagehide",(t=>{t.persisted||e.terminate()}),{once:!0})}catch(e){a.logger().error("PubNub",(()=>({messageType:"error",message:e})))}else s&&a.logger().warn("PubNub","SharedWorker not supported in this browser. Fallback to the original transport.");const m=new it({clientConfiguration:a,tokenManager:u,transport:y});if(super({configuration:a,transport:m,cryptography:h,tokenManager:u,crypto:l}),this.File=o,this.onHeartbeatIntervalChange=d,this.onAuthenticationChange=g,this.onPresenceStateChange=p,this.onUserIdChange=b,y instanceof Fe){y.emitStatus=this.emitStatus.bind(this);const e=this.disconnect.bind(this);this.disconnect=t=>{y.disconnect(),e()}}(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.logger.debug("PubNub","Network down detected"),this.emitStatus({category:Sr.CATEGORIES.PNNetworkDownCategory}),this._configuration.restore?this.disconnect(!0):this.destroy(!0)}networkUpDetected(){this.logger.debug("PubNub","Network up detected"),this.emitStatus({category:Sr.CATEGORIES.PNNetworkUpCategory}),this.reconnect()}}return Sr.CryptoModule=Me,Sr})); diff --git a/lib/core/components/cryptography/hmac-sha256.js b/lib/core/components/cryptography/hmac-sha256.js deleted file mode 100644 index b22f461a1..000000000 --- a/lib/core/components/cryptography/hmac-sha256.js +++ /dev/null @@ -1,692 +0,0 @@ -"use strict"; -/** - * CryptoJS implementation. - * - * @internal - */ -/*eslint-disable */ -/* - CryptoJS v3.1.2 - code.google.com/p/crypto-js - (c) 2009-2013 by Jeff Mott. All rights reserved. - code.google.com/p/crypto-js/wiki/License - */ -var CryptoJS = CryptoJS || - (function (h, s) { - var f = {}, g = (f.lib = {}), q = function () { }, m = (g.Base = { - extend: function (a) { - q.prototype = this; - var c = new q(); - a && c.mixIn(a); - c.hasOwnProperty('init') || - (c.init = function () { - c.$super.init.apply(this, arguments); - }); - c.init.prototype = c; - c.$super = this; - return c; - }, - create: function () { - var a = this.extend(); - a.init.apply(a, arguments); - return a; - }, - init: function () { }, - mixIn: function (a) { - for (var c in a) - a.hasOwnProperty(c) && (this[c] = a[c]); - a.hasOwnProperty('toString') && (this.toString = a.toString); - }, - clone: function () { - return this.init.prototype.extend(this); - }, - }), r = (g.WordArray = m.extend({ - init: function (a, c) { - a = this.words = a || []; - this.sigBytes = c != s ? c : 4 * a.length; - }, - toString: function (a) { - return (a || k).stringify(this); - }, - concat: function (a) { - var c = this.words, d = a.words, b = this.sigBytes; - a = a.sigBytes; - this.clamp(); - if (b % 4) - for (var e = 0; e < a; e++) - c[(b + e) >>> 2] |= ((d[e >>> 2] >>> (24 - 8 * (e % 4))) & 255) << (24 - 8 * ((b + e) % 4)); - else if (65535 < d.length) - for (e = 0; e < a; e += 4) - c[(b + e) >>> 2] = d[e >>> 2]; - else - c.push.apply(c, d); - this.sigBytes += a; - return this; - }, - clamp: function () { - var a = this.words, c = this.sigBytes; - a[c >>> 2] &= 4294967295 << (32 - 8 * (c % 4)); - a.length = h.ceil(c / 4); - }, - clone: function () { - var a = m.clone.call(this); - a.words = this.words.slice(0); - return a; - }, - random: function (a) { - for (var c = [], d = 0; d < a; d += 4) - c.push((4294967296 * h.random()) | 0); - return new r.init(c, a); - }, - })), l = (f.enc = {}), k = (l.Hex = { - stringify: function (a) { - var c = a.words; - a = a.sigBytes; - for (var d = [], b = 0; b < a; b++) { - var e = (c[b >>> 2] >>> (24 - 8 * (b % 4))) & 255; - d.push((e >>> 4).toString(16)); - d.push((e & 15).toString(16)); - } - return d.join(''); - }, - parse: function (a) { - for (var c = a.length, d = [], b = 0; b < c; b += 2) - d[b >>> 3] |= parseInt(a.substr(b, 2), 16) << (24 - 4 * (b % 8)); - return new r.init(d, c / 2); - }, - }), n = (l.Latin1 = { - stringify: function (a) { - var c = a.words; - a = a.sigBytes; - for (var d = [], b = 0; b < a; b++) - d.push(String.fromCharCode((c[b >>> 2] >>> (24 - 8 * (b % 4))) & 255)); - return d.join(''); - }, - parse: function (a) { - for (var c = a.length, d = [], b = 0; b < c; b++) - d[b >>> 2] |= (a.charCodeAt(b) & 255) << (24 - 8 * (b % 4)); - return new r.init(d, c); - }, - }), j = (l.Utf8 = { - stringify: function (a) { - try { - return decodeURIComponent(escape(n.stringify(a))); - } - catch (c) { - throw Error('Malformed UTF-8 data'); - } - }, - parse: function (a) { - return n.parse(unescape(encodeURIComponent(a))); - }, - }), u = (g.BufferedBlockAlgorithm = m.extend({ - reset: function () { - this._data = new r.init(); - this._nDataBytes = 0; - }, - _append: function (a) { - 'string' == typeof a && (a = j.parse(a)); - this._data.concat(a); - this._nDataBytes += a.sigBytes; - }, - _process: function (a) { - var c = this._data, d = c.words, b = c.sigBytes, e = this.blockSize, f = b / (4 * e), f = a ? h.ceil(f) : h.max((f | 0) - this._minBufferSize, 0); - a = f * e; - b = h.min(4 * a, b); - if (a) { - for (var g = 0; g < a; g += e) - this._doProcessBlock(d, g); - g = d.splice(0, a); - c.sigBytes -= b; - } - return new r.init(g, b); - }, - clone: function () { - var a = m.clone.call(this); - a._data = this._data.clone(); - return a; - }, - _minBufferSize: 0, - })); - g.Hasher = u.extend({ - cfg: m.extend(), - init: function (a) { - this.cfg = this.cfg.extend(a); - this.reset(); - }, - reset: function () { - u.reset.call(this); - this._doReset(); - }, - update: function (a) { - this._append(a); - this._process(); - return this; - }, - finalize: function (a) { - a && this._append(a); - return this._doFinalize(); - }, - blockSize: 16, - _createHelper: function (a) { - return function (c, d) { - return new a.init(d).finalize(c); - }; - }, - _createHmacHelper: function (a) { - return function (c, d) { - return new t.HMAC.init(a, d).finalize(c); - }; - }, - }); - var t = (f.algo = {}); - return f; - })(Math); -// SHA256 -(function (h) { - for (var s = CryptoJS, f = s.lib, g = f.WordArray, q = f.Hasher, f = s.algo, m = [], r = [], l = function (a) { - return (4294967296 * (a - (a | 0))) | 0; - }, k = 2, n = 0; 64 > n;) { - var j; - a: { - j = k; - for (var u = h.sqrt(j), t = 2; t <= u; t++) - if (!(j % t)) { - j = !1; - break a; - } - j = !0; - } - j && (8 > n && (m[n] = l(h.pow(k, 0.5))), (r[n] = l(h.pow(k, 1 / 3))), n++); - k++; - } - var a = [], f = (f.SHA256 = q.extend({ - _doReset: function () { - this._hash = new g.init(m.slice(0)); - }, - _doProcessBlock: function (c, d) { - for (var b = this._hash.words, e = b[0], f = b[1], g = b[2], j = b[3], h = b[4], m = b[5], n = b[6], q = b[7], p = 0; 64 > p; p++) { - if (16 > p) - a[p] = c[d + p] | 0; - else { - var k = a[p - 15], l = a[p - 2]; - a[p] = - (((k << 25) | (k >>> 7)) ^ ((k << 14) | (k >>> 18)) ^ (k >>> 3)) + - a[p - 7] + - (((l << 15) | (l >>> 17)) ^ ((l << 13) | (l >>> 19)) ^ (l >>> 10)) + - a[p - 16]; - } - k = - q + - (((h << 26) | (h >>> 6)) ^ ((h << 21) | (h >>> 11)) ^ ((h << 7) | (h >>> 25))) + - ((h & m) ^ (~h & n)) + - r[p] + - a[p]; - l = - (((e << 30) | (e >>> 2)) ^ ((e << 19) | (e >>> 13)) ^ ((e << 10) | (e >>> 22))) + - ((e & f) ^ (e & g) ^ (f & g)); - q = n; - n = m; - m = h; - h = (j + k) | 0; - j = g; - g = f; - f = e; - e = (k + l) | 0; - } - b[0] = (b[0] + e) | 0; - b[1] = (b[1] + f) | 0; - b[2] = (b[2] + g) | 0; - b[3] = (b[3] + j) | 0; - b[4] = (b[4] + h) | 0; - b[5] = (b[5] + m) | 0; - b[6] = (b[6] + n) | 0; - b[7] = (b[7] + q) | 0; - }, - _doFinalize: function () { - var a = this._data, d = a.words, b = 8 * this._nDataBytes, e = 8 * a.sigBytes; - d[e >>> 5] |= 128 << (24 - (e % 32)); - d[(((e + 64) >>> 9) << 4) + 14] = h.floor(b / 4294967296); - d[(((e + 64) >>> 9) << 4) + 15] = b; - a.sigBytes = 4 * d.length; - this._process(); - return this._hash; - }, - clone: function () { - var a = q.clone.call(this); - a._hash = this._hash.clone(); - return a; - }, - })); - s.SHA256 = q._createHelper(f); - s.HmacSHA256 = q._createHmacHelper(f); -})(Math); -// HMAC SHA256 -(function () { - var h = CryptoJS, s = h.enc.Utf8; - h.algo.HMAC = h.lib.Base.extend({ - init: function (f, g) { - f = this._hasher = new f.init(); - 'string' == typeof g && (g = s.parse(g)); - var h = f.blockSize, m = 4 * h; - g.sigBytes > m && (g = f.finalize(g)); - g.clamp(); - for (var r = (this._oKey = g.clone()), l = (this._iKey = g.clone()), k = r.words, n = l.words, j = 0; j < h; j++) - (k[j] ^= 1549556828), (n[j] ^= 909522486); - r.sigBytes = l.sigBytes = m; - this.reset(); - }, - reset: function () { - var f = this._hasher; - f.reset(); - f.update(this._iKey); - }, - update: function (f) { - this._hasher.update(f); - return this; - }, - finalize: function (f) { - var g = this._hasher; - f = g.finalize(f); - g.reset(); - return g.finalize(this._oKey.clone().concat(f)); - }, - }); -})(); -// Base64 -(function () { - var u = CryptoJS, p = u.lib.WordArray; - u.enc.Base64 = { - stringify: function (d) { - var l = d.words, p = d.sigBytes, t = this._map; - d.clamp(); - d = []; - for (var r = 0; r < p; r += 3) - for (var w = (((l[r >>> 2] >>> (24 - 8 * (r % 4))) & 255) << 16) | - (((l[(r + 1) >>> 2] >>> (24 - 8 * ((r + 1) % 4))) & 255) << 8) | - ((l[(r + 2) >>> 2] >>> (24 - 8 * ((r + 2) % 4))) & 255), v = 0; 4 > v && r + 0.75 * v < p; v++) - d.push(t.charAt((w >>> (6 * (3 - v))) & 63)); - if ((l = t.charAt(64))) - for (; d.length % 4;) - d.push(l); - return d.join(''); - }, - parse: function (d) { - var l = d.length, s = this._map, t = s.charAt(64); - t && ((t = d.indexOf(t)), -1 != t && (l = t)); - for (var t = [], r = 0, w = 0; w < l; w++) - if (w % 4) { - var v = s.indexOf(d.charAt(w - 1)) << (2 * (w % 4)), b = s.indexOf(d.charAt(w)) >>> (6 - 2 * (w % 4)); - t[r >>> 2] |= (v | b) << (24 - 8 * (r % 4)); - r++; - } - return p.create(t, r); - }, - _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', - }; -})(); -// BlockCipher -(function (u) { - function p(b, n, a, c, e, j, k) { - b = b + ((n & a) | (~n & c)) + e + k; - return ((b << j) | (b >>> (32 - j))) + n; - } - function d(b, n, a, c, e, j, k) { - b = b + ((n & c) | (a & ~c)) + e + k; - return ((b << j) | (b >>> (32 - j))) + n; - } - function l(b, n, a, c, e, j, k) { - b = b + (n ^ a ^ c) + e + k; - return ((b << j) | (b >>> (32 - j))) + n; - } - function s(b, n, a, c, e, j, k) { - b = b + (a ^ (n | ~c)) + e + k; - return ((b << j) | (b >>> (32 - j))) + n; - } - for (var t = CryptoJS, r = t.lib, w = r.WordArray, v = r.Hasher, r = t.algo, b = [], x = 0; 64 > x; x++) - b[x] = (4294967296 * u.abs(u.sin(x + 1))) | 0; - r = r.MD5 = v.extend({ - _doReset: function () { - this._hash = new w.init([1732584193, 4023233417, 2562383102, 271733878]); - }, - _doProcessBlock: function (q, n) { - for (var a = 0; 16 > a; a++) { - var c = n + a, e = q[c]; - q[c] = (((e << 8) | (e >>> 24)) & 16711935) | (((e << 24) | (e >>> 8)) & 4278255360); - } - var a = this._hash.words, c = q[n + 0], e = q[n + 1], j = q[n + 2], k = q[n + 3], z = q[n + 4], r = q[n + 5], t = q[n + 6], w = q[n + 7], v = q[n + 8], A = q[n + 9], B = q[n + 10], C = q[n + 11], u = q[n + 12], D = q[n + 13], E = q[n + 14], x = q[n + 15], f = a[0], m = a[1], g = a[2], h = a[3], f = p(f, m, g, h, c, 7, b[0]), h = p(h, f, m, g, e, 12, b[1]), g = p(g, h, f, m, j, 17, b[2]), m = p(m, g, h, f, k, 22, b[3]), f = p(f, m, g, h, z, 7, b[4]), h = p(h, f, m, g, r, 12, b[5]), g = p(g, h, f, m, t, 17, b[6]), m = p(m, g, h, f, w, 22, b[7]), f = p(f, m, g, h, v, 7, b[8]), h = p(h, f, m, g, A, 12, b[9]), g = p(g, h, f, m, B, 17, b[10]), m = p(m, g, h, f, C, 22, b[11]), f = p(f, m, g, h, u, 7, b[12]), h = p(h, f, m, g, D, 12, b[13]), g = p(g, h, f, m, E, 17, b[14]), m = p(m, g, h, f, x, 22, b[15]), f = d(f, m, g, h, e, 5, b[16]), h = d(h, f, m, g, t, 9, b[17]), g = d(g, h, f, m, C, 14, b[18]), m = d(m, g, h, f, c, 20, b[19]), f = d(f, m, g, h, r, 5, b[20]), h = d(h, f, m, g, B, 9, b[21]), g = d(g, h, f, m, x, 14, b[22]), m = d(m, g, h, f, z, 20, b[23]), f = d(f, m, g, h, A, 5, b[24]), h = d(h, f, m, g, E, 9, b[25]), g = d(g, h, f, m, k, 14, b[26]), m = d(m, g, h, f, v, 20, b[27]), f = d(f, m, g, h, D, 5, b[28]), h = d(h, f, m, g, j, 9, b[29]), g = d(g, h, f, m, w, 14, b[30]), m = d(m, g, h, f, u, 20, b[31]), f = l(f, m, g, h, r, 4, b[32]), h = l(h, f, m, g, v, 11, b[33]), g = l(g, h, f, m, C, 16, b[34]), m = l(m, g, h, f, E, 23, b[35]), f = l(f, m, g, h, e, 4, b[36]), h = l(h, f, m, g, z, 11, b[37]), g = l(g, h, f, m, w, 16, b[38]), m = l(m, g, h, f, B, 23, b[39]), f = l(f, m, g, h, D, 4, b[40]), h = l(h, f, m, g, c, 11, b[41]), g = l(g, h, f, m, k, 16, b[42]), m = l(m, g, h, f, t, 23, b[43]), f = l(f, m, g, h, A, 4, b[44]), h = l(h, f, m, g, u, 11, b[45]), g = l(g, h, f, m, x, 16, b[46]), m = l(m, g, h, f, j, 23, b[47]), f = s(f, m, g, h, c, 6, b[48]), h = s(h, f, m, g, w, 10, b[49]), g = s(g, h, f, m, E, 15, b[50]), m = s(m, g, h, f, r, 21, b[51]), f = s(f, m, g, h, u, 6, b[52]), h = s(h, f, m, g, k, 10, b[53]), g = s(g, h, f, m, B, 15, b[54]), m = s(m, g, h, f, e, 21, b[55]), f = s(f, m, g, h, v, 6, b[56]), h = s(h, f, m, g, x, 10, b[57]), g = s(g, h, f, m, t, 15, b[58]), m = s(m, g, h, f, D, 21, b[59]), f = s(f, m, g, h, z, 6, b[60]), h = s(h, f, m, g, C, 10, b[61]), g = s(g, h, f, m, j, 15, b[62]), m = s(m, g, h, f, A, 21, b[63]); - a[0] = (a[0] + f) | 0; - a[1] = (a[1] + m) | 0; - a[2] = (a[2] + g) | 0; - a[3] = (a[3] + h) | 0; - }, - _doFinalize: function () { - var b = this._data, n = b.words, a = 8 * this._nDataBytes, c = 8 * b.sigBytes; - n[c >>> 5] |= 128 << (24 - (c % 32)); - var e = u.floor(a / 4294967296); - n[(((c + 64) >>> 9) << 4) + 15] = (((e << 8) | (e >>> 24)) & 16711935) | (((e << 24) | (e >>> 8)) & 4278255360); - n[(((c + 64) >>> 9) << 4) + 14] = (((a << 8) | (a >>> 24)) & 16711935) | (((a << 24) | (a >>> 8)) & 4278255360); - b.sigBytes = 4 * (n.length + 1); - this._process(); - b = this._hash; - n = b.words; - for (a = 0; 4 > a; a++) - (c = n[a]), (n[a] = (((c << 8) | (c >>> 24)) & 16711935) | (((c << 24) | (c >>> 8)) & 4278255360)); - return b; - }, - clone: function () { - var b = v.clone.call(this); - b._hash = this._hash.clone(); - return b; - }, - }); - t.MD5 = v._createHelper(r); - t.HmacMD5 = v._createHmacHelper(r); -})(Math); -(function () { - var u = CryptoJS, p = u.lib, d = p.Base, l = p.WordArray, p = u.algo, s = (p.EvpKDF = d.extend({ - cfg: d.extend({ keySize: 4, hasher: p.MD5, iterations: 1 }), - init: function (d) { - this.cfg = this.cfg.extend(d); - }, - compute: function (d, r) { - for (var p = this.cfg, s = p.hasher.create(), b = l.create(), u = b.words, q = p.keySize, p = p.iterations; u.length < q;) { - n && s.update(n); - var n = s.update(d).finalize(r); - s.reset(); - for (var a = 1; a < p; a++) - (n = s.finalize(n)), s.reset(); - b.concat(n); - } - b.sigBytes = 4 * q; - return b; - }, - })); - u.EvpKDF = function (d, l, p) { - return s.create(p).compute(d, l); - }; -})(); -// Cipher -CryptoJS.lib.Cipher || - (function (u) { - var p = CryptoJS, d = p.lib, l = d.Base, s = d.WordArray, t = d.BufferedBlockAlgorithm, r = p.enc.Base64, w = p.algo.EvpKDF, v = (d.Cipher = t.extend({ - cfg: l.extend(), - createEncryptor: function (e, a) { - return this.create(this._ENC_XFORM_MODE, e, a); - }, - createDecryptor: function (e, a) { - return this.create(this._DEC_XFORM_MODE, e, a); - }, - init: function (e, a, b) { - this.cfg = this.cfg.extend(b); - this._xformMode = e; - this._key = a; - this.reset(); - }, - reset: function () { - t.reset.call(this); - this._doReset(); - }, - process: function (e) { - this._append(e); - return this._process(); - }, - finalize: function (e) { - e && this._append(e); - return this._doFinalize(); - }, - keySize: 4, - ivSize: 4, - _ENC_XFORM_MODE: 1, - _DEC_XFORM_MODE: 2, - _createHelper: function (e) { - return { - encrypt: function (b, k, d) { - return ('string' == typeof k ? c : a).encrypt(e, b, k, d); - }, - decrypt: function (b, k, d) { - return ('string' == typeof k ? c : a).decrypt(e, b, k, d); - }, - }; - }, - })); - d.StreamCipher = v.extend({ - _doFinalize: function () { - return this._process(!0); - }, - blockSize: 1, - }); - var b = (p.mode = {}), x = function (e, a, b) { - var c = this._iv; - c ? (this._iv = u) : (c = this._prevBlock); - for (var d = 0; d < b; d++) - e[a + d] ^= c[d]; - }, q = (d.BlockCipherMode = l.extend({ - createEncryptor: function (e, a) { - return this.Encryptor.create(e, a); - }, - createDecryptor: function (e, a) { - return this.Decryptor.create(e, a); - }, - init: function (e, a) { - this._cipher = e; - this._iv = a; - }, - })).extend(); - q.Encryptor = q.extend({ - processBlock: function (e, a) { - var b = this._cipher, c = b.blockSize; - x.call(this, e, a, c); - b.encryptBlock(e, a); - this._prevBlock = e.slice(a, a + c); - }, - }); - q.Decryptor = q.extend({ - processBlock: function (e, a) { - var b = this._cipher, c = b.blockSize, d = e.slice(a, a + c); - b.decryptBlock(e, a); - x.call(this, e, a, c); - this._prevBlock = d; - }, - }); - b = b.CBC = q; - q = (p.pad = {}).Pkcs7 = { - pad: function (a, b) { - for (var c = 4 * b, c = c - (a.sigBytes % c), d = (c << 24) | (c << 16) | (c << 8) | c, l = [], n = 0; n < c; n += 4) - l.push(d); - c = s.create(l, c); - a.concat(c); - }, - unpad: function (a) { - a.sigBytes -= a.words[(a.sigBytes - 1) >>> 2] & 255; - }, - }; - d.BlockCipher = v.extend({ - cfg: v.cfg.extend({ mode: b, padding: q }), - reset: function () { - v.reset.call(this); - var a = this.cfg, b = a.iv, a = a.mode; - if (this._xformMode == this._ENC_XFORM_MODE) - var c = a.createEncryptor; - else - (c = a.createDecryptor), (this._minBufferSize = 1); - this._mode = c.call(a, this, b && b.words); - }, - _doProcessBlock: function (a, b) { - this._mode.processBlock(a, b); - }, - _doFinalize: function () { - var a = this.cfg.padding; - if (this._xformMode == this._ENC_XFORM_MODE) { - a.pad(this._data, this.blockSize); - var b = this._process(!0); - } - else - (b = this._process(!0)), a.unpad(b); - return b; - }, - blockSize: 4, - }); - var n = (d.CipherParams = l.extend({ - init: function (a) { - this.mixIn(a); - }, - toString: function (a) { - return (a || this.formatter).stringify(this); - }, - })), b = ((p.format = {}).OpenSSL = { - stringify: function (a) { - var b = a.ciphertext; - a = a.salt; - return (a ? s.create([1398893684, 1701076831]).concat(a).concat(b) : b).toString(r); - }, - parse: function (a) { - a = r.parse(a); - var b = a.words; - if (1398893684 == b[0] && 1701076831 == b[1]) { - var c = s.create(b.slice(2, 4)); - b.splice(0, 4); - a.sigBytes -= 16; - } - return n.create({ ciphertext: a, salt: c }); - }, - }), a = (d.SerializableCipher = l.extend({ - cfg: l.extend({ format: b }), - encrypt: function (a, b, c, d) { - d = this.cfg.extend(d); - var l = a.createEncryptor(c, d); - b = l.finalize(b); - l = l.cfg; - return n.create({ - ciphertext: b, - key: c, - iv: l.iv, - algorithm: a, - mode: l.mode, - padding: l.padding, - blockSize: a.blockSize, - formatter: d.format, - }); - }, - decrypt: function (a, b, c, d) { - d = this.cfg.extend(d); - b = this._parse(b, d.format); - return a.createDecryptor(c, d).finalize(b.ciphertext); - }, - _parse: function (a, b) { - return 'string' == typeof a ? b.parse(a, this) : a; - }, - })), p = ((p.kdf = {}).OpenSSL = { - execute: function (a, b, c, d) { - d || (d = s.random(8)); - a = w.create({ keySize: b + c }).compute(a, d); - c = s.create(a.words.slice(b), 4 * c); - a.sigBytes = 4 * b; - return n.create({ key: a, iv: c, salt: d }); - }, - }), c = (d.PasswordBasedCipher = a.extend({ - cfg: a.cfg.extend({ kdf: p }), - encrypt: function (b, c, d, l) { - l = this.cfg.extend(l); - d = l.kdf.execute(d, b.keySize, b.ivSize); - l.iv = d.iv; - b = a.encrypt.call(this, b, c, d.key, l); - b.mixIn(d); - return b; - }, - decrypt: function (b, c, d, l) { - l = this.cfg.extend(l); - c = this._parse(c, l.format); - d = l.kdf.execute(d, b.keySize, b.ivSize, c.salt); - l.iv = d.iv; - return a.decrypt.call(this, b, c, d.key, l); - }, - })); - })(); -// AES -(function () { - for (var u = CryptoJS, p = u.lib.BlockCipher, d = u.algo, l = [], s = [], t = [], r = [], w = [], v = [], b = [], x = [], q = [], n = [], a = [], c = 0; 256 > c; c++) - a[c] = 128 > c ? c << 1 : (c << 1) ^ 283; - for (var e = 0, j = 0, c = 0; 256 > c; c++) { - var k = j ^ (j << 1) ^ (j << 2) ^ (j << 3) ^ (j << 4), k = (k >>> 8) ^ (k & 255) ^ 99; - l[e] = k; - s[k] = e; - var z = a[e], F = a[z], G = a[F], y = (257 * a[k]) ^ (16843008 * k); - t[e] = (y << 24) | (y >>> 8); - r[e] = (y << 16) | (y >>> 16); - w[e] = (y << 8) | (y >>> 24); - v[e] = y; - y = (16843009 * G) ^ (65537 * F) ^ (257 * z) ^ (16843008 * e); - b[k] = (y << 24) | (y >>> 8); - x[k] = (y << 16) | (y >>> 16); - q[k] = (y << 8) | (y >>> 24); - n[k] = y; - e ? ((e = z ^ a[a[a[G ^ z]]]), (j ^= a[a[j]])) : (e = j = 1); - } - var H = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54], d = (d.AES = p.extend({ - _doReset: function () { - for (var a = this._key, c = a.words, d = a.sigBytes / 4, a = 4 * ((this._nRounds = d + 6) + 1), e = (this._keySchedule = []), j = 0; j < a; j++) - if (j < d) - e[j] = c[j]; - else { - var k = e[j - 1]; - j % d - ? 6 < d && - 4 == j % d && - (k = (l[k >>> 24] << 24) | (l[(k >>> 16) & 255] << 16) | (l[(k >>> 8) & 255] << 8) | l[k & 255]) - : ((k = (k << 8) | (k >>> 24)), - (k = (l[k >>> 24] << 24) | (l[(k >>> 16) & 255] << 16) | (l[(k >>> 8) & 255] << 8) | l[k & 255]), - (k ^= H[(j / d) | 0] << 24)); - e[j] = e[j - d] ^ k; - } - c = this._invKeySchedule = []; - for (d = 0; d < a; d++) - (j = a - d), - (k = d % 4 ? e[j] : e[j - 4]), - (c[d] = - 4 > d || 4 >= j ? k : b[l[k >>> 24]] ^ x[l[(k >>> 16) & 255]] ^ q[l[(k >>> 8) & 255]] ^ n[l[k & 255]]); - }, - encryptBlock: function (a, b) { - this._doCryptBlock(a, b, this._keySchedule, t, r, w, v, l); - }, - decryptBlock: function (a, c) { - var d = a[c + 1]; - a[c + 1] = a[c + 3]; - a[c + 3] = d; - this._doCryptBlock(a, c, this._invKeySchedule, b, x, q, n, s); - d = a[c + 1]; - a[c + 1] = a[c + 3]; - a[c + 3] = d; - }, - _doCryptBlock: function (a, b, c, d, e, j, l, f) { - for (var m = this._nRounds, g = a[b] ^ c[0], h = a[b + 1] ^ c[1], k = a[b + 2] ^ c[2], n = a[b + 3] ^ c[3], p = 4, r = 1; r < m; r++) - var q = d[g >>> 24] ^ e[(h >>> 16) & 255] ^ j[(k >>> 8) & 255] ^ l[n & 255] ^ c[p++], s = d[h >>> 24] ^ e[(k >>> 16) & 255] ^ j[(n >>> 8) & 255] ^ l[g & 255] ^ c[p++], t = d[k >>> 24] ^ e[(n >>> 16) & 255] ^ j[(g >>> 8) & 255] ^ l[h & 255] ^ c[p++], n = d[n >>> 24] ^ e[(g >>> 16) & 255] ^ j[(h >>> 8) & 255] ^ l[k & 255] ^ c[p++], g = q, h = s, k = t; - q = ((f[g >>> 24] << 24) | (f[(h >>> 16) & 255] << 16) | (f[(k >>> 8) & 255] << 8) | f[n & 255]) ^ c[p++]; - s = ((f[h >>> 24] << 24) | (f[(k >>> 16) & 255] << 16) | (f[(n >>> 8) & 255] << 8) | f[g & 255]) ^ c[p++]; - t = ((f[k >>> 24] << 24) | (f[(n >>> 16) & 255] << 16) | (f[(g >>> 8) & 255] << 8) | f[h & 255]) ^ c[p++]; - n = ((f[n >>> 24] << 24) | (f[(g >>> 16) & 255] << 16) | (f[(h >>> 8) & 255] << 8) | f[k & 255]) ^ c[p++]; - a[b] = q; - a[b + 1] = s; - a[b + 2] = t; - a[b + 3] = n; - }, - keySize: 8, - })); - u.AES = p._createHelper(d); -})(); -// Mode ECB -CryptoJS.mode.ECB = (function () { - var ECB = CryptoJS.lib.BlockCipherMode.extend(); - ECB.Encryptor = ECB.extend({ - processBlock: function (words, offset) { - this._cipher.encryptBlock(words, offset); - }, - }); - ECB.Decryptor = ECB.extend({ - processBlock: function (words, offset) { - this._cipher.decryptBlock(words, offset); - }, - }); - return ECB; -})(); -module.exports = CryptoJS; diff --git a/lib/core/components/cryptography/index.js b/lib/core/components/cryptography/index.js index 016228ca1..f40803c8f 100644 --- a/lib/core/components/cryptography/index.js +++ b/lib/core/components/cryptography/index.js @@ -1,338 +1,20 @@ "use strict"; /** - * Legacy cryptography module. + * Legacy cryptography module (`@noble`-backed: Web, React Native). * * @internal */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const utils_1 = require("../../utils"); -const base64_codec_1 = require("../base64_codec"); -const hmac_sha256_1 = __importDefault(require("./hmac-sha256")); +const noble_primitives_1 = require("./noble-primitives"); +const legacy_crypto_1 = require("./legacy-crypto"); /** - * Convert bytes array to words array. - * - * @param b - Bytes array (buffer) which should be converted. - * - * @returns Word sized array. + * Legacy cryptography module for data encryption / decryption. * * @internal */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -function bufferToWordArray(b) { - const wa = []; - let i; - for (i = 0; i < b.length; i += 1) { - wa[(i / 4) | 0] |= b[i] << (24 - 8 * i); - } - // @ts-expect-error Bundled library without types. - return hmac_sha256_1.default.lib.WordArray.create(wa, b.length); -} -/** - * Legacy cryptography module for files and signature. - * - * @internal - */ -class default_1 { +class Crypto extends legacy_crypto_1.LegacyCrypto { constructor(configuration) { - this.configuration = configuration; - /** - * Crypto initialization vector. - */ - this.iv = '0123456789012345'; - /** - * List os allowed cipher key encodings. - */ - this.allowedKeyEncodings = ['hex', 'utf8', 'base64', 'binary']; - /** - * Allowed cipher key lengths. - */ - this.allowedKeyLengths = [128, 256]; - /** - * Allowed crypto modes. - */ - this.allowedModes = ['ecb', 'cbc']; - this.logger = configuration.logger; - this.defaultOptions = { - encryptKey: true, - keyEncoding: 'utf8', - keyLength: 256, - mode: 'cbc', - }; - } - /** - * Update registered loggers' manager. - * - * @param [logger] - Logger, which crypto should use. - */ - set logger(logger) { - this._logger = logger; - if (this.logger) { - this.logger.debug('Crypto', () => ({ - messageType: 'object', - message: this.configuration, - details: 'Create with configuration:', - ignoredKeys(key, obj) { - return typeof obj[key] === 'function' || key === 'logger' || (0, utils_1.isSensitiveLogKey)(key); - }, - })); - } - } - /** - * Get loggers' manager. - * - * @returns Loggers' manager (if set). - */ - get logger() { - return this._logger; - } - /** - * Generate HMAC-SHA256 hash from input data. - * - * @param data - Data from which hash should be generated. - * - * @returns HMAC-SHA256 hash from provided `data`. - */ - HMACSHA256(data) { - // @ts-expect-error Bundled library without types. - const hash = hmac_sha256_1.default.HmacSHA256(data, this.configuration.secretKey); - // @ts-expect-error Bundled library without types. - return hash.toString(hmac_sha256_1.default.enc.Base64); - } - /** - * Generate SHA256 hash from input data. - * - * @param data - Data from which hash should be generated. - * - * @returns SHA256 hash from provided `data`. - */ - SHA256(data) { - // @ts-expect-error Bundled library without types. - return hmac_sha256_1.default.SHA256(data).toString(hmac_sha256_1.default.enc.Hex); - } - /** - * Encrypt provided data. - * - * @param data - Source data which should be encrypted. - * @param [customCipherKey] - Custom cipher key (different from defined on client level). - * @param [options] - Specific crypto configuration options. - * - * @returns Encrypted `data`. - */ - encrypt(data, customCipherKey, options) { - if (this.configuration.customEncrypt) { - if (this.logger) - this.logger.warn('Crypto', "'customEncrypt' is deprecated. Consult docs for better alternative."); - return this.configuration.customEncrypt(data); - } - return this.pnEncrypt(data, customCipherKey, options); - } - /** - * Decrypt provided data. - * - * @param data - Encrypted data which should be decrypted. - * @param [customCipherKey] - Custom cipher key (different from defined on client level). - * @param [options] - Specific crypto configuration options. - * - * @returns Decrypted `data`. - */ - decrypt(data, customCipherKey, options) { - if (this.configuration.customDecrypt) { - if (this.logger) - this.logger.warn('Crypto', "'customDecrypt' is deprecated. Consult docs for better alternative."); - return this.configuration.customDecrypt(data); - } - return this.pnDecrypt(data, customCipherKey, options); - } - /** - * Encrypt provided data. - * - * @param data - Source data which should be encrypted. - * @param [customCipherKey] - Custom cipher key (different from defined on client level). - * @param [options] - Specific crypto configuration options. - * - * @returns Encrypted `data` as string. - */ - pnEncrypt(data, customCipherKey, options) { - const decidedCipherKey = customCipherKey !== null && customCipherKey !== void 0 ? customCipherKey : this.configuration.cipherKey; - if (!decidedCipherKey) - return data; - if (this.logger) { - this.logger.debug('Crypto', () => ({ - messageType: 'object', - message: Object.assign({ data }, (options !== null && options !== void 0 ? options : {})), - details: 'Encrypt with parameters:', - ignoredKeys: utils_1.isSensitiveLogKey, - })); - } - options = this.parseOptions(options); - const mode = this.getMode(options); - const cipherKey = this.getPaddedKey(decidedCipherKey, options); - if (this.configuration.useRandomIVs) { - const waIv = this.getRandomIV(); - // @ts-expect-error Bundled library without types. - const waPayload = hmac_sha256_1.default.AES.encrypt(data, cipherKey, { iv: waIv, mode }).ciphertext; - // @ts-expect-error Bundled library without types. - return waIv.clone().concat(waPayload.clone()).toString(hmac_sha256_1.default.enc.Base64); - } - const iv = this.getIV(options); - // @ts-expect-error Bundled library without types. - const encryptedHexArray = hmac_sha256_1.default.AES.encrypt(data, cipherKey, { iv, mode }).ciphertext; - // @ts-expect-error Bundled library without types. - const base64Encrypted = encryptedHexArray.toString(hmac_sha256_1.default.enc.Base64); - return base64Encrypted || data; - } - /** - * Decrypt provided data. - * - * @param data - Encrypted data which should be decrypted. - * @param [customCipherKey] - Custom cipher key (different from defined on client level). - * @param [options] - Specific crypto configuration options. - * - * @returns Decrypted `data`. - */ - pnDecrypt(data, customCipherKey, options) { - const decidedCipherKey = customCipherKey !== null && customCipherKey !== void 0 ? customCipherKey : this.configuration.cipherKey; - if (!decidedCipherKey) - return data; - if (this.logger) { - this.logger.debug('Crypto', () => ({ - messageType: 'object', - message: Object.assign({ data }, (options !== null && options !== void 0 ? options : {})), - details: 'Decrypt with parameters:', - ignoredKeys: utils_1.isSensitiveLogKey, - })); - } - options = this.parseOptions(options); - const mode = this.getMode(options); - const cipherKey = this.getPaddedKey(decidedCipherKey, options); - if (this.configuration.useRandomIVs) { - const ciphertext = new Uint8ClampedArray((0, base64_codec_1.decode)(data)); - const iv = bufferToWordArray(ciphertext.slice(0, 16)); - const payload = bufferToWordArray(ciphertext.slice(16)); - try { - // @ts-expect-error Bundled library without types. - const plainJSON = hmac_sha256_1.default.AES.decrypt({ ciphertext: payload }, cipherKey, { iv, mode }).toString( - // @ts-expect-error Bundled library without types. - hmac_sha256_1.default.enc.Utf8); - return JSON.parse(plainJSON); - } - catch (e) { - if (this.logger) - this.logger.error('Crypto', () => ({ messageType: 'error', message: e })); - return null; - } - } - else { - const iv = this.getIV(options); - try { - // @ts-expect-error Bundled library without types. - const ciphertext = hmac_sha256_1.default.enc.Base64.parse(data); - // @ts-expect-error Bundled library without types. - const plainJSON = hmac_sha256_1.default.AES.decrypt({ ciphertext }, cipherKey, { iv, mode }).toString(hmac_sha256_1.default.enc.Utf8); - return JSON.parse(plainJSON); - } - catch (e) { - if (this.logger) - this.logger.error('Crypto', () => ({ messageType: 'error', message: e })); - return null; - } - } - } - /** - * Pre-process provided custom crypto configuration. - * - * @param incomingOptions - Configuration which should be pre-processed before use. - * - * @returns Normalized crypto configuration options. - */ - parseOptions(incomingOptions) { - var _a, _b, _c, _d; - if (!incomingOptions) - return this.defaultOptions; - // Defaults - const options = { - encryptKey: (_a = incomingOptions.encryptKey) !== null && _a !== void 0 ? _a : this.defaultOptions.encryptKey, - keyEncoding: (_b = incomingOptions.keyEncoding) !== null && _b !== void 0 ? _b : this.defaultOptions.keyEncoding, - keyLength: (_c = incomingOptions.keyLength) !== null && _c !== void 0 ? _c : this.defaultOptions.keyLength, - mode: (_d = incomingOptions.mode) !== null && _d !== void 0 ? _d : this.defaultOptions.mode, - }; - // Validation - if (this.allowedKeyEncodings.indexOf(options.keyEncoding.toLowerCase()) === -1) - options.keyEncoding = this.defaultOptions.keyEncoding; - if (this.allowedKeyLengths.indexOf(options.keyLength) === -1) - options.keyLength = this.defaultOptions.keyLength; - if (this.allowedModes.indexOf(options.mode.toLowerCase()) === -1) - options.mode = this.defaultOptions.mode; - return options; - } - /** - * Decode provided cipher key. - * - * @param key - Key in `encoding` provided by `options`. - * @param options - Crypto configuration options with cipher key details. - * - * @returns Array buffer with decoded key. - */ - decodeKey(key, options) { - // @ts-expect-error Bundled library without types. - if (options.keyEncoding === 'base64') - return hmac_sha256_1.default.enc.Base64.parse(key); - // @ts-expect-error Bundled library without types. - if (options.keyEncoding === 'hex') - return hmac_sha256_1.default.enc.Hex.parse(key); - return key; - } - /** - * Add padding to the cipher key. - * - * @param key - Key which should be padded. - * @param options - Crypto configuration options with cipher key details. - * - * @returns Properly padded cipher key. - */ - getPaddedKey(key, options) { - key = this.decodeKey(key, options); - // @ts-expect-error Bundled library without types. - if (options.encryptKey) - return hmac_sha256_1.default.enc.Utf8.parse(this.SHA256(key).slice(0, 32)); - return key; - } - /** - * Cipher mode. - * - * @param options - Crypto configuration with information about cipher mode. - * - * @returns Crypto cipher mode. - */ - getMode(options) { - // @ts-expect-error Bundled library without types. - if (options.mode === 'ecb') - return hmac_sha256_1.default.mode.ECB; - // @ts-expect-error Bundled library without types. - return hmac_sha256_1.default.mode.CBC; - } - /** - * Cipher initialization vector. - * - * @param options - Crypto configuration with information about cipher mode. - * - * @returns Initialization vector. - */ - getIV(options) { - // @ts-expect-error Bundled library without types. - return options.mode === 'cbc' ? hmac_sha256_1.default.enc.Utf8.parse(this.iv) : null; - } - /** - * Random initialization vector. - * - * @returns Generated random initialization vector. - */ - getRandomIV() { - // @ts-expect-error Bundled library without types. - return hmac_sha256_1.default.lib.WordArray.random(16); + super(configuration, noble_primitives_1.noblePrimitives); } } -exports.default = default_1; +exports.default = Crypto; diff --git a/lib/core/components/cryptography/legacy-crypto.js b/lib/core/components/cryptography/legacy-crypto.js new file mode 100644 index 000000000..d5941de1f --- /dev/null +++ b/lib/core/components/cryptography/legacy-crypto.js @@ -0,0 +1,321 @@ +"use strict"; +/** + * Legacy cryptography module. + * + * Platform-agnostic implementation which relies on platform-provided crypto primitives. + * + * @internal + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LegacyCrypto = void 0; +const primitives_1 = require("./primitives"); +const utils_1 = require("../../utils"); +const base64_codec_1 = require("../base64_codec"); +/** + * Whether insecure random initialization vector fallback warning has been printed. + * + * @internal + */ +let insecureRandomWarningShown = false; +/** + * Legacy cryptography module for files and signature. + * + * @internal + */ +class LegacyCrypto { + constructor(configuration, primitives) { + this.configuration = configuration; + this.primitives = primitives; + /** + * Crypto initialization vector. + */ + this.iv = '0123456789012345'; + /** + * List os allowed cipher key encodings. + */ + this.allowedKeyEncodings = ['hex', 'utf8', 'base64', 'binary']; + /** + * Allowed cipher key lengths. + */ + this.allowedKeyLengths = [128, 256]; + /** + * Allowed crypto modes. + */ + this.allowedModes = ['ecb', 'cbc']; + this.logger = configuration.logger; + this.defaultOptions = { + encryptKey: true, + keyEncoding: 'utf8', + keyLength: 256, + mode: 'cbc', + }; + } + /** + * Update registered loggers' manager. + * + * @param [logger] - Logger, which crypto should use. + */ + set logger(logger) { + this._logger = logger; + if (this.logger) { + this.logger.debug('Crypto', () => ({ + messageType: 'object', + message: this.configuration, + details: 'Create with configuration:', + ignoredKeys(key, obj) { + return typeof obj[key] === 'function' || key === 'logger' || (0, utils_1.isSensitiveLogKey)(key); + }, + })); + } + } + /** + * Get loggers' manager. + * + * @returns Loggers' manager (if set). + */ + get logger() { + return this._logger; + } + /** + * Generate HMAC-SHA256 hash from input data. + * + * @param data - Data from which hash should be generated. + * + * @returns HMAC-SHA256 hash from provided `data`. + */ + HMACSHA256(data) { + var _a; + const hash = this.primitives.hmacSha256((0, primitives_1.encodeUtf8)((_a = this.configuration.secretKey) !== null && _a !== void 0 ? _a : ''), (0, primitives_1.encodeUtf8)(data)); + return (0, base64_codec_1.encode)((0, primitives_1.toArrayBuffer)(hash)); + } + /** + * Generate SHA256 hash from input data. + * + * @param data - Data from which hash should be generated. + * + * @returns SHA256 hash from provided `data`. + */ + SHA256(data) { + return (0, primitives_1.bytesToHex)(this.primitives.sha256((0, primitives_1.encodeUtf8)(data))); + } + /** + * Encrypt provided data. + * + * @param data - Source data which should be encrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Encrypted `data`. + */ + encrypt(data, customCipherKey, options) { + if (this.configuration.customEncrypt) { + if (this.logger) + this.logger.warn('Crypto', "'customEncrypt' is deprecated. Consult docs for better alternative."); + return this.configuration.customEncrypt(data); + } + return this.pnEncrypt(data, customCipherKey, options); + } + /** + * Decrypt provided data. + * + * @param data - Encrypted data which should be decrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Decrypted `data`. + */ + decrypt(data, customCipherKey, options) { + if (this.configuration.customDecrypt) { + if (this.logger) + this.logger.warn('Crypto', "'customDecrypt' is deprecated. Consult docs for better alternative."); + return this.configuration.customDecrypt(data); + } + return this.pnDecrypt(data, customCipherKey, options); + } + /** + * Encrypt provided data. + * + * @param data - Source data which should be encrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Encrypted `data` as string. + */ + pnEncrypt(data, customCipherKey, options) { + const decidedCipherKey = customCipherKey !== null && customCipherKey !== void 0 ? customCipherKey : this.configuration.cipherKey; + if (!decidedCipherKey) + return data; + if (this.logger) { + this.logger.debug('Crypto', () => ({ + messageType: 'object', + message: Object.assign({ data }, (options !== null && options !== void 0 ? options : {})), + details: 'Encrypt with parameters:', + ignoredKeys: utils_1.isSensitiveLogKey, + })); + } + if (typeof data !== 'string') + throw new Error('Encryption error: data should be a string'); + options = this.parseOptions(options); + const mode = this.getMode(options); + const cipherKey = this.getPaddedKey(decidedCipherKey, options); + const plaintext = (0, primitives_1.encodeUtf8)(data); + if (this.configuration.useRandomIVs) { + const iv = this.getRandomIV(); + const payload = this.primitives.aesEncrypt(mode, cipherKey, iv, plaintext); + return (0, base64_codec_1.encode)((0, primitives_1.toArrayBuffer)((0, primitives_1.concatBytes)(iv, payload))); + } + const encrypted = this.primitives.aesEncrypt(mode, cipherKey, this.getIV(options), plaintext); + const base64Encrypted = (0, base64_codec_1.encode)((0, primitives_1.toArrayBuffer)(encrypted)); + return base64Encrypted || data; + } + /** + * Decrypt provided data. + * + * @param data - Encrypted data which should be decrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Decrypted `data`. + */ + pnDecrypt(data, customCipherKey, options) { + const decidedCipherKey = customCipherKey !== null && customCipherKey !== void 0 ? customCipherKey : this.configuration.cipherKey; + if (!decidedCipherKey) + return data; + if (this.logger) { + this.logger.debug('Crypto', () => ({ + messageType: 'object', + message: Object.assign({ data }, (options !== null && options !== void 0 ? options : {})), + details: 'Decrypt with parameters:', + ignoredKeys: utils_1.isSensitiveLogKey, + })); + } + options = this.parseOptions(options); + const mode = this.getMode(options); + const cipherKey = this.getPaddedKey(decidedCipherKey, options); + if (this.configuration.useRandomIVs) { + const ciphertext = new Uint8Array((0, base64_codec_1.decode)(data)); + const iv = ciphertext.slice(0, 16); + const payload = ciphertext.slice(16); + try { + const plainJSON = (0, primitives_1.decodeUtf8)(this.primitives.aesDecrypt(mode, cipherKey, iv, payload)); + return JSON.parse(plainJSON); + } + catch (e) { + if (this.logger) + this.logger.error('Crypto', () => ({ messageType: 'error', message: e })); + return null; + } + } + else { + const iv = this.getIV(options); + try { + const ciphertext = new Uint8Array((0, base64_codec_1.decode)(data)); + const plainJSON = (0, primitives_1.decodeUtf8)(this.primitives.aesDecrypt(mode, cipherKey, iv, ciphertext)); + return JSON.parse(plainJSON); + } + catch (e) { + if (this.logger) + this.logger.error('Crypto', () => ({ messageType: 'error', message: e })); + return null; + } + } + } + /** + * Pre-process provided custom crypto configuration. + * + * @param incomingOptions - Configuration which should be pre-processed before use. + * + * @returns Normalized crypto configuration options. + */ + parseOptions(incomingOptions) { + var _a, _b, _c, _d; + if (!incomingOptions) + return this.defaultOptions; + // Defaults + const options = { + encryptKey: (_a = incomingOptions.encryptKey) !== null && _a !== void 0 ? _a : this.defaultOptions.encryptKey, + keyEncoding: (_b = incomingOptions.keyEncoding) !== null && _b !== void 0 ? _b : this.defaultOptions.keyEncoding, + keyLength: (_c = incomingOptions.keyLength) !== null && _c !== void 0 ? _c : this.defaultOptions.keyLength, + mode: (_d = incomingOptions.mode) !== null && _d !== void 0 ? _d : this.defaultOptions.mode, + }; + // Validation + if (this.allowedKeyEncodings.indexOf(options.keyEncoding.toLowerCase()) === -1) + options.keyEncoding = this.defaultOptions.keyEncoding; + if (this.allowedKeyLengths.indexOf(options.keyLength) === -1) + options.keyLength = this.defaultOptions.keyLength; + if (this.allowedModes.indexOf(options.mode.toLowerCase()) === -1) + options.mode = this.defaultOptions.mode; + return options; + } + /** + * Decode provided cipher key. + * + * @param key - Key in `encoding` provided by `options`. + * @param options - Crypto configuration options with cipher key details. + * + * @returns Bytes array with decoded key. + */ + decodeKey(key, options) { + if (options.keyEncoding === 'base64') + return new Uint8Array((0, base64_codec_1.decode)(key)); + if (options.keyEncoding === 'hex') + return (0, primitives_1.hexToBytes)(key); + return (0, primitives_1.encodeUtf8)(key); + } + /** + * Add padding to the cipher key. + * + * @param key - Key which should be padded. + * @param options - Crypto configuration options with cipher key details. + * + * @returns Properly padded cipher key. + */ + getPaddedKey(key, options) { + const decodedKey = this.decodeKey(key, options); + if (options.encryptKey) + return (0, primitives_1.encodeUtf8)((0, primitives_1.bytesToHex)(this.primitives.sha256(decodedKey)).slice(0, 32)); + return decodedKey; + } + /** + * Cipher mode. + * + * @param options - Crypto configuration with information about cipher mode. + * + * @returns Crypto cipher mode. + */ + getMode(options) { + return options.mode === 'ecb' ? 'ecb' : 'cbc'; + } + /** + * Cipher initialization vector. + * + * @param options - Crypto configuration with information about cipher mode. + * + * @returns Initialization vector. + */ + getIV(options) { + return options.mode === 'cbc' ? (0, primitives_1.encodeUtf8)(this.iv) : null; + } + /** + * Random initialization vector. + * + * Falls back to the insecure `Math.random()` source (previous behavior) when the platform doesn't provide + * `crypto.getRandomValues` (for example, React Native without polyfill). + * + * @returns Generated random initialization vector. + */ + getRandomIV() { + try { + return this.primitives.randomBytes(16); + } + catch (_) { + if (!insecureRandomWarningShown && this.logger) { + insecureRandomWarningShown = true; + this.logger.warn('Crypto', "'crypto.getRandomValues' is unavailable; falling back to insecure Math.random() IV. " + + "Install 'react-native-get-random-values'."); + } + return Uint8Array.from({ length: 16 }, () => Math.floor(Math.random() * 256)); + } + } +} +exports.LegacyCrypto = LegacyCrypto; diff --git a/lib/core/components/cryptography/noble-primitives.js b/lib/core/components/cryptography/noble-primitives.js new file mode 100644 index 000000000..5566a3bcd --- /dev/null +++ b/lib/core/components/cryptography/noble-primitives.js @@ -0,0 +1,47 @@ +"use strict"; +/** + * Cryptography primitives backed by `@noble` (Web, React Native). + * + * @internal + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.noblePrimitives = void 0; +const aes_js_1 = require("@noble/ciphers/aes.js"); +const utils_js_1 = require("@noble/ciphers/utils.js"); +const sha2_js_1 = require("@noble/hashes/sha2.js"); +const primitives_1 = require("./primitives"); +/** + * Prepare AES-CBC cipher instance. + * + * **Note:** AES-ECB isn't reachable through public API and intentionally not bundled. + * + * @param mode - AES block cipher mode. + * @param key - AES key. + * @param iv - Initialization vector. + * + * @returns AES-CBC cipher. + * + * @internal + */ +const aesCipher = (mode, key, iv, decrypt = false) => { + if (mode === 'ecb') + throw new Error('AES-ECB is not supported'); + // Padding removed leniently by `unpadLegacy` on decryption (CryptoJS-compatible). + return (0, aes_js_1.cbc)(key, iv, decrypt ? { disablePadding: true } : undefined); +}; +/** + * `@noble`-based cryptography primitives. + * + * **Note:** Request signature (HMAC-SHA256) is Node.js-only and intentionally not bundled. + * + * @internal + */ +exports.noblePrimitives = { + sha256: (data) => (0, sha2_js_1.sha256)(data), + hmacSha256: () => { + throw new Error('HMAC-SHA256 is not supported on this platform'); + }, + aesEncrypt: (mode, key, iv, data) => aesCipher(mode, key, iv).encrypt(data), + aesDecrypt: (mode, key, iv, data) => (0, primitives_1.unpadLegacy)(aesCipher(mode, key, iv, true).decrypt(data)), + randomBytes: (length) => (0, utils_js_1.randomBytes)(length), +}; diff --git a/lib/core/components/cryptography/node-primitives.js b/lib/core/components/cryptography/node-primitives.js new file mode 100644 index 000000000..7fca903a1 --- /dev/null +++ b/lib/core/components/cryptography/node-primitives.js @@ -0,0 +1,42 @@ +"use strict"; +/** + * Cryptography primitives backed by `node:crypto` (Node.js). + * + * @internal + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.nodePrimitives = void 0; +const crypto_1 = require("crypto"); +const buffer_1 = require("buffer"); +const primitives_1 = require("./primitives"); +/** + * OpenSSL cipher name for provided AES mode and key. + * + * @param mode - AES block cipher mode. + * @param key - AES key. + * + * @returns Cipher algorithm name. + * + * @internal + */ +const algorithm = (mode, key) => `aes-${key.length * 8}-${mode}`; +/** + * `node:crypto`-based cryptography primitives. + * + * @internal + */ +exports.nodePrimitives = { + sha256: (data) => (0, crypto_1.createHash)('sha256').update(data).digest(), + hmacSha256: (key, data) => (0, crypto_1.createHmac)('sha256', key).update(data).digest(), + aesEncrypt: (mode, key, iv, data) => { + const cipher = (0, crypto_1.createCipheriv)(algorithm(mode, key), key, mode === 'ecb' ? null : iv); + return buffer_1.Buffer.concat([cipher.update(data), cipher.final()]); + }, + aesDecrypt: (mode, key, iv, data) => { + const decipher = (0, crypto_1.createDecipheriv)(algorithm(mode, key), key, mode === 'ecb' ? null : iv); + // Padding removed leniently by `unpadLegacy` (CryptoJS-compatible). + decipher.setAutoPadding(false); + return (0, primitives_1.unpadLegacy)(buffer_1.Buffer.concat([decipher.update(data), decipher.final()])); + }, + randomBytes: (length) => (0, crypto_1.randomBytes)(length), +}; diff --git a/lib/core/components/cryptography/node.js b/lib/core/components/cryptography/node.js new file mode 100644 index 000000000..6263c685c --- /dev/null +++ b/lib/core/components/cryptography/node.js @@ -0,0 +1,20 @@ +"use strict"; +/** + * Legacy cryptography module (`node:crypto`-backed: Node.js). + * + * @internal + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const node_primitives_1 = require("./node-primitives"); +const legacy_crypto_1 = require("./legacy-crypto"); +/** + * Legacy cryptography module for data encryption / decryption and request signature. + * + * @internal + */ +class Crypto extends legacy_crypto_1.LegacyCrypto { + constructor(configuration) { + super(configuration, node_primitives_1.nodePrimitives); + } +} +exports.default = Crypto; diff --git a/lib/core/components/cryptography/primitives.js b/lib/core/components/cryptography/primitives.js new file mode 100644 index 000000000..eabc22330 --- /dev/null +++ b/lib/core/components/cryptography/primitives.js @@ -0,0 +1,188 @@ +"use strict"; +/** + * Platform-agnostic cryptography primitives contract and byte helpers. + * + * @internal + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toArrayBuffer = exports.concatBytes = exports.hexToBytes = exports.bytesToHex = exports.unpadLegacy = exports.decodeUtf8 = exports.isWellFormedUtf8 = exports.encodeUtf8 = void 0; +/** + * Encode string to UTF-8 bytes. + * + * **Note:** Strings with lone surrogates are rejected (as CryptoJS `Utf8.parse` did through `encodeURIComponent`) + * instead of being silently replaced with `U+FFFD` by `TextEncoder`. + * + * @param string - Source string. + * + * @returns UTF-8 bytes. + * + * @throws URIError if `string` contains lone surrogates. + * + * @internal + */ +const encodeUtf8 = (string) => { + for (let i = 0; i < string.length; i++) { + const code = string.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff) { + const next = i + 1 < string.length ? string.charCodeAt(i + 1) : 0; + if (next < 0xdc00 || next > 0xdfff) + throw new URIError('URI malformed'); + i++; + } + else if (code >= 0xdc00 && code <= 0xdfff) + throw new URIError('URI malformed'); + } + return new TextEncoder().encode(string); +}; +exports.encodeUtf8 = encodeUtf8; +/** + * Check whether bytes are well-formed UTF-8 (Unicode Table 3-7). + * + * Rejects the same sequences as `decodeURIComponent` (used by CryptoJS `Utf8.stringify`): invalid lead and + * continuation bytes, truncated, overlong, surrogate (`U+D800`–`U+DFFF`) and out of range (> `U+10FFFF`) sequences. + * + * **Note:** Bytes are validated (rather than decoded `U+FFFD` characters) because `U+FFFD` can be legitimate input. + * + * @param bytes - Bytes which should be validated. + * + * @returns `true` if `bytes` are well-formed UTF-8. + * + * @internal + */ +const isWellFormedUtf8 = (bytes) => { + const length = bytes.length; + let i = 0; + while (i < length) { + const lead = bytes[i]; + if (lead <= 0x7f) { + i++; + continue; + } + let count; + let min = 0x80; + let max = 0xbf; + if (lead >= 0xc2 && lead <= 0xdf) + count = 1; + else if (lead >= 0xe0 && lead <= 0xef) { + count = 2; + if (lead === 0xe0) + min = 0xa0; + else if (lead === 0xed) + max = 0x9f; + } + else if (lead >= 0xf0 && lead <= 0xf4) { + count = 3; + if (lead === 0xf0) + min = 0x90; + else if (lead === 0xf4) + max = 0x8f; + } + else + return false; + // Truncated sequence. + if (i + count >= length) + return false; + if (bytes[i + 1] < min || bytes[i + 1] > max) + return false; + for (let j = 2; j <= count; j++) + if (bytes[i + j] < 0x80 || bytes[i + j] > 0xbf) + return false; + i += count + 1; + } + return true; +}; +exports.isWellFormedUtf8 = isWellFormedUtf8; +/** + * Decode UTF-8 bytes to string. + * + * Preserves CryptoJS `Utf8.stringify` contract: + * - malformed UTF-8 is rejected (React Native `TextDecoder` polyfill doesn't support `fatal` option, so bytes + * validated with {@link isWellFormedUtf8}); + * - leading BOM is preserved (native `TextDecoder` strips it by default, the polyfill keeps it). + * + * @param bytes - UTF-8 bytes. + * + * @returns Decoded string. + * + * @throws Error if `bytes` aren't well-formed UTF-8. + * + * @internal + */ +const decodeUtf8 = (bytes) => { + if (!(0, exports.isWellFormedUtf8)(bytes)) + throw new Error('Malformed UTF-8 data'); + const string = new TextDecoder().decode(bytes); + const hasBOM = bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf; + return hasBOM && string.charCodeAt(0) !== 0xfeff ? `${string}` : string; +}; +exports.decodeUtf8 = decodeUtf8; +/** + * Remove block cipher padding leniently. + * + * Mirrors CryptoJS `Pkcs7.unpad`: strips the number of bytes stored in the last byte without validating padding + * bytes (so data padded with ANSI X.923 or ISO 10126 schemes still decrypts as before). + * + * @param bytes - Decrypted bytes with padding. + * + * @returns Bytes without padding (empty if padding length exceeds data length). + * + * @internal + */ +const unpadLegacy = (bytes) => { + const padding = bytes.length ? bytes[bytes.length - 1] : 0; + return padding > bytes.length ? new Uint8Array(0) : bytes.subarray(0, bytes.length - padding); +}; +exports.unpadLegacy = unpadLegacy; +/** + * Convert bytes to lowercase hex string. + * + * @param bytes - Source bytes. + * + * @returns Hex string. + * + * @internal + */ +const bytesToHex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); +exports.bytesToHex = bytesToHex; +/** + * Convert hex string to bytes. + * + * @param hex - Hex string. + * + * @returns Decoded bytes. + * + * @internal + */ +const hexToBytes = (hex) => { var _a; return Uint8Array.from((_a = hex.match(/.{1,2}/g)) !== null && _a !== void 0 ? _a : [], (byte) => parseInt(byte, 16)); }; +exports.hexToBytes = hexToBytes; +/** + * Concatenate two bytes arrays. + * + * @param a - First bytes array. + * @param b - Second bytes array. + * + * @returns Concatenated bytes. + * + * @internal + */ +const concatBytes = (a, b) => { + const result = new Uint8Array(a.length + b.length); + result.set(a); + result.set(b, a.length); + return result; +}; +exports.concatBytes = concatBytes; +/** + * Copy bytes into standalone `ArrayBuffer`. + * + * **Important:** Primitives may return views into larger buffers (noble subarrays, Node.js `Buffer` pool), so the + * underlying `.buffer` must never be used directly. + * + * @param bytes - Source bytes (possibly a view). + * + * @returns `ArrayBuffer` with exactly `bytes` content. + * + * @internal + */ +const toArrayBuffer = (bytes) => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength); +exports.toArrayBuffer = toArrayBuffer; diff --git a/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js index 8e446b76a..400172636 100644 --- a/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js +++ b/lib/crypto/modules/NodeCryptoModule/legacyCryptor.js @@ -17,11 +17,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -const index_1 = __importDefault(require("../../../core/components/cryptography/index")); +const node_1 = __importDefault(require("../../../core/components/cryptography/node")); const base64_codec_1 = require("../../../core/components/base64_codec"); const pubnub_error_1 = require("../../../errors/pubnub-error"); const utils_1 = require("../../../core/utils"); -const node_1 = __importDefault(require("../node")); +const node_2 = __importDefault(require("../node")); /** * Legacy cryptor. * @@ -30,8 +30,8 @@ const node_1 = __importDefault(require("../node")); class LegacyCryptor { constructor(config) { this.config = config; - this.cryptor = new index_1.default(Object.assign({}, config)); - this.fileCryptor = new node_1.default(); + this.cryptor = new node_1.default(Object.assign({}, config)); + this.fileCryptor = new node_2.default(); } /** * Update registered loggers' manager. diff --git a/lib/node/index.js b/lib/node/index.js index 3d52c5667..03d477649 100644 --- a/lib/node/index.js +++ b/lib/node/index.js @@ -13,7 +13,7 @@ const node_transport_1 = require("../transport/node-transport"); const middleware_1 = require("../transport/middleware"); const base64_codec_1 = require("../core/components/base64_codec"); const node_2 = __importDefault(require("../crypto/modules/node")); -const cryptography_1 = __importDefault(require("../core/components/cryptography")); +const node_3 = __importDefault(require("../core/components/cryptography/node")); const pubnub_error_1 = require("../errors/pubnub-error"); const pubnub_common_1 = require("../core/pubnub-common"); const common_1 = __importDefault(require("../cbor/common")); @@ -59,7 +59,7 @@ class PubNub extends pubnub_common_1.PubNubCore { // Legacy crypto (legacy data encryption / decryption and request signature support). let crypto; if (process.env.CRYPTO_MODULE !== 'disabled') { - crypto = new cryptography_1.default({ + crypto = new node_3.default({ secretKey: clientConfiguration.secretKey, cipherKey: clientConfiguration.getCipherKey(), useRandomIVs: clientConfiguration.getUseRandomIVs(), diff --git a/package-lock.json b/package-lock.json index f393329b7..265c938aa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,8 @@ "version": "13.1.2", "license": "SEE LICENSE IN LICENSE", "dependencies": { + "@noble/ciphers": "2.4.0", + "@noble/hashes": "2.4.0", "agentkeepalive": "^3.5.2", "buffer": "^6.0.3", "cbor-js": "^0.1.0", @@ -3686,6 +3688,30 @@ "node": ">=18" } }, + "node_modules/@noble/ciphers": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.4.0.tgz", + "integrity": "sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", + "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", diff --git a/package.json b/package.json index 40e5b5112..5f3f76143 100644 --- a/package.json +++ b/package.json @@ -59,6 +59,8 @@ "long-poll" ], "dependencies": { + "@noble/ciphers": "2.4.0", + "@noble/hashes": "2.4.0", "agentkeepalive": "^3.5.2", "buffer": "^6.0.3", "cbor-js": "^0.1.0", @@ -148,4 +150,4 @@ "engines": { "node": ">=22.0.0" } -} \ No newline at end of file +} diff --git a/src/core/components/cryptography/hmac-sha256.js b/src/core/components/cryptography/hmac-sha256.js deleted file mode 100755 index b0e785b15..000000000 --- a/src/core/components/cryptography/hmac-sha256.js +++ /dev/null @@ -1,915 +0,0 @@ -/** - * CryptoJS implementation. - * - * @internal - */ - -/*eslint-disable */ - -/* - CryptoJS v3.1.2 - code.google.com/p/crypto-js - (c) 2009-2013 by Jeff Mott. All rights reserved. - code.google.com/p/crypto-js/wiki/License - */ -var CryptoJS = - CryptoJS || - (function (h, s) { - var f = {}, - g = (f.lib = {}), - q = function () {}, - m = (g.Base = { - extend: function (a) { - q.prototype = this; - var c = new q(); - a && c.mixIn(a); - c.hasOwnProperty('init') || - (c.init = function () { - c.$super.init.apply(this, arguments); - }); - c.init.prototype = c; - c.$super = this; - return c; - }, - create: function () { - var a = this.extend(); - a.init.apply(a, arguments); - return a; - }, - init: function () {}, - mixIn: function (a) { - for (var c in a) a.hasOwnProperty(c) && (this[c] = a[c]); - a.hasOwnProperty('toString') && (this.toString = a.toString); - }, - clone: function () { - return this.init.prototype.extend(this); - }, - }), - r = (g.WordArray = m.extend({ - init: function (a, c) { - a = this.words = a || []; - this.sigBytes = c != s ? c : 4 * a.length; - }, - toString: function (a) { - return (a || k).stringify(this); - }, - concat: function (a) { - var c = this.words, - d = a.words, - b = this.sigBytes; - a = a.sigBytes; - this.clamp(); - if (b % 4) - for (var e = 0; e < a; e++) - c[(b + e) >>> 2] |= ((d[e >>> 2] >>> (24 - 8 * (e % 4))) & 255) << (24 - 8 * ((b + e) % 4)); - else if (65535 < d.length) for (e = 0; e < a; e += 4) c[(b + e) >>> 2] = d[e >>> 2]; - else c.push.apply(c, d); - this.sigBytes += a; - return this; - }, - clamp: function () { - var a = this.words, - c = this.sigBytes; - a[c >>> 2] &= 4294967295 << (32 - 8 * (c % 4)); - a.length = h.ceil(c / 4); - }, - clone: function () { - var a = m.clone.call(this); - a.words = this.words.slice(0); - return a; - }, - random: function (a) { - for (var c = [], d = 0; d < a; d += 4) c.push((4294967296 * h.random()) | 0); - return new r.init(c, a); - }, - })), - l = (f.enc = {}), - k = (l.Hex = { - stringify: function (a) { - var c = a.words; - a = a.sigBytes; - for (var d = [], b = 0; b < a; b++) { - var e = (c[b >>> 2] >>> (24 - 8 * (b % 4))) & 255; - d.push((e >>> 4).toString(16)); - d.push((e & 15).toString(16)); - } - return d.join(''); - }, - parse: function (a) { - for (var c = a.length, d = [], b = 0; b < c; b += 2) - d[b >>> 3] |= parseInt(a.substr(b, 2), 16) << (24 - 4 * (b % 8)); - return new r.init(d, c / 2); - }, - }), - n = (l.Latin1 = { - stringify: function (a) { - var c = a.words; - a = a.sigBytes; - for (var d = [], b = 0; b < a; b++) d.push(String.fromCharCode((c[b >>> 2] >>> (24 - 8 * (b % 4))) & 255)); - return d.join(''); - }, - parse: function (a) { - for (var c = a.length, d = [], b = 0; b < c; b++) d[b >>> 2] |= (a.charCodeAt(b) & 255) << (24 - 8 * (b % 4)); - return new r.init(d, c); - }, - }), - j = (l.Utf8 = { - stringify: function (a) { - try { - return decodeURIComponent(escape(n.stringify(a))); - } catch (c) { - throw Error('Malformed UTF-8 data'); - } - }, - parse: function (a) { - return n.parse(unescape(encodeURIComponent(a))); - }, - }), - u = (g.BufferedBlockAlgorithm = m.extend({ - reset: function () { - this._data = new r.init(); - this._nDataBytes = 0; - }, - _append: function (a) { - 'string' == typeof a && (a = j.parse(a)); - this._data.concat(a); - this._nDataBytes += a.sigBytes; - }, - _process: function (a) { - var c = this._data, - d = c.words, - b = c.sigBytes, - e = this.blockSize, - f = b / (4 * e), - f = a ? h.ceil(f) : h.max((f | 0) - this._minBufferSize, 0); - a = f * e; - b = h.min(4 * a, b); - if (a) { - for (var g = 0; g < a; g += e) this._doProcessBlock(d, g); - g = d.splice(0, a); - c.sigBytes -= b; - } - return new r.init(g, b); - }, - clone: function () { - var a = m.clone.call(this); - a._data = this._data.clone(); - return a; - }, - _minBufferSize: 0, - })); - g.Hasher = u.extend({ - cfg: m.extend(), - init: function (a) { - this.cfg = this.cfg.extend(a); - this.reset(); - }, - reset: function () { - u.reset.call(this); - this._doReset(); - }, - update: function (a) { - this._append(a); - this._process(); - return this; - }, - finalize: function (a) { - a && this._append(a); - return this._doFinalize(); - }, - blockSize: 16, - _createHelper: function (a) { - return function (c, d) { - return new a.init(d).finalize(c); - }; - }, - _createHmacHelper: function (a) { - return function (c, d) { - return new t.HMAC.init(a, d).finalize(c); - }; - }, - }); - var t = (f.algo = {}); - return f; - })(Math); - -// SHA256 -(function (h) { - for ( - var s = CryptoJS, - f = s.lib, - g = f.WordArray, - q = f.Hasher, - f = s.algo, - m = [], - r = [], - l = function (a) { - return (4294967296 * (a - (a | 0))) | 0; - }, - k = 2, - n = 0; - 64 > n; - - ) { - var j; - a: { - j = k; - for (var u = h.sqrt(j), t = 2; t <= u; t++) - if (!(j % t)) { - j = !1; - break a; - } - j = !0; - } - j && (8 > n && (m[n] = l(h.pow(k, 0.5))), (r[n] = l(h.pow(k, 1 / 3))), n++); - k++; - } - var a = [], - f = (f.SHA256 = q.extend({ - _doReset: function () { - this._hash = new g.init(m.slice(0)); - }, - _doProcessBlock: function (c, d) { - for ( - var b = this._hash.words, - e = b[0], - f = b[1], - g = b[2], - j = b[3], - h = b[4], - m = b[5], - n = b[6], - q = b[7], - p = 0; - 64 > p; - p++ - ) { - if (16 > p) a[p] = c[d + p] | 0; - else { - var k = a[p - 15], - l = a[p - 2]; - a[p] = - (((k << 25) | (k >>> 7)) ^ ((k << 14) | (k >>> 18)) ^ (k >>> 3)) + - a[p - 7] + - (((l << 15) | (l >>> 17)) ^ ((l << 13) | (l >>> 19)) ^ (l >>> 10)) + - a[p - 16]; - } - k = - q + - (((h << 26) | (h >>> 6)) ^ ((h << 21) | (h >>> 11)) ^ ((h << 7) | (h >>> 25))) + - ((h & m) ^ (~h & n)) + - r[p] + - a[p]; - l = - (((e << 30) | (e >>> 2)) ^ ((e << 19) | (e >>> 13)) ^ ((e << 10) | (e >>> 22))) + - ((e & f) ^ (e & g) ^ (f & g)); - q = n; - n = m; - m = h; - h = (j + k) | 0; - j = g; - g = f; - f = e; - e = (k + l) | 0; - } - b[0] = (b[0] + e) | 0; - b[1] = (b[1] + f) | 0; - b[2] = (b[2] + g) | 0; - b[3] = (b[3] + j) | 0; - b[4] = (b[4] + h) | 0; - b[5] = (b[5] + m) | 0; - b[6] = (b[6] + n) | 0; - b[7] = (b[7] + q) | 0; - }, - _doFinalize: function () { - var a = this._data, - d = a.words, - b = 8 * this._nDataBytes, - e = 8 * a.sigBytes; - d[e >>> 5] |= 128 << (24 - (e % 32)); - d[(((e + 64) >>> 9) << 4) + 14] = h.floor(b / 4294967296); - d[(((e + 64) >>> 9) << 4) + 15] = b; - a.sigBytes = 4 * d.length; - this._process(); - return this._hash; - }, - clone: function () { - var a = q.clone.call(this); - a._hash = this._hash.clone(); - return a; - }, - })); - s.SHA256 = q._createHelper(f); - s.HmacSHA256 = q._createHmacHelper(f); -})(Math); - -// HMAC SHA256 -(function () { - var h = CryptoJS, - s = h.enc.Utf8; - h.algo.HMAC = h.lib.Base.extend({ - init: function (f, g) { - f = this._hasher = new f.init(); - 'string' == typeof g && (g = s.parse(g)); - var h = f.blockSize, - m = 4 * h; - g.sigBytes > m && (g = f.finalize(g)); - g.clamp(); - for (var r = (this._oKey = g.clone()), l = (this._iKey = g.clone()), k = r.words, n = l.words, j = 0; j < h; j++) - (k[j] ^= 1549556828), (n[j] ^= 909522486); - r.sigBytes = l.sigBytes = m; - this.reset(); - }, - reset: function () { - var f = this._hasher; - f.reset(); - f.update(this._iKey); - }, - update: function (f) { - this._hasher.update(f); - return this; - }, - finalize: function (f) { - var g = this._hasher; - f = g.finalize(f); - g.reset(); - return g.finalize(this._oKey.clone().concat(f)); - }, - }); -})(); - -// Base64 -(function () { - var u = CryptoJS, - p = u.lib.WordArray; - u.enc.Base64 = { - stringify: function (d) { - var l = d.words, - p = d.sigBytes, - t = this._map; - d.clamp(); - d = []; - for (var r = 0; r < p; r += 3) - for ( - var w = - (((l[r >>> 2] >>> (24 - 8 * (r % 4))) & 255) << 16) | - (((l[(r + 1) >>> 2] >>> (24 - 8 * ((r + 1) % 4))) & 255) << 8) | - ((l[(r + 2) >>> 2] >>> (24 - 8 * ((r + 2) % 4))) & 255), - v = 0; - 4 > v && r + 0.75 * v < p; - v++ - ) - d.push(t.charAt((w >>> (6 * (3 - v))) & 63)); - if ((l = t.charAt(64))) for (; d.length % 4; ) d.push(l); - return d.join(''); - }, - parse: function (d) { - var l = d.length, - s = this._map, - t = s.charAt(64); - t && ((t = d.indexOf(t)), -1 != t && (l = t)); - for (var t = [], r = 0, w = 0; w < l; w++) - if (w % 4) { - var v = s.indexOf(d.charAt(w - 1)) << (2 * (w % 4)), - b = s.indexOf(d.charAt(w)) >>> (6 - 2 * (w % 4)); - t[r >>> 2] |= (v | b) << (24 - 8 * (r % 4)); - r++; - } - return p.create(t, r); - }, - _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', - }; -})(); - -// BlockCipher -(function (u) { - function p(b, n, a, c, e, j, k) { - b = b + ((n & a) | (~n & c)) + e + k; - return ((b << j) | (b >>> (32 - j))) + n; - } - function d(b, n, a, c, e, j, k) { - b = b + ((n & c) | (a & ~c)) + e + k; - return ((b << j) | (b >>> (32 - j))) + n; - } - function l(b, n, a, c, e, j, k) { - b = b + (n ^ a ^ c) + e + k; - return ((b << j) | (b >>> (32 - j))) + n; - } - function s(b, n, a, c, e, j, k) { - b = b + (a ^ (n | ~c)) + e + k; - return ((b << j) | (b >>> (32 - j))) + n; - } - for (var t = CryptoJS, r = t.lib, w = r.WordArray, v = r.Hasher, r = t.algo, b = [], x = 0; 64 > x; x++) - b[x] = (4294967296 * u.abs(u.sin(x + 1))) | 0; - r = r.MD5 = v.extend({ - _doReset: function () { - this._hash = new w.init([1732584193, 4023233417, 2562383102, 271733878]); - }, - _doProcessBlock: function (q, n) { - for (var a = 0; 16 > a; a++) { - var c = n + a, - e = q[c]; - q[c] = (((e << 8) | (e >>> 24)) & 16711935) | (((e << 24) | (e >>> 8)) & 4278255360); - } - var a = this._hash.words, - c = q[n + 0], - e = q[n + 1], - j = q[n + 2], - k = q[n + 3], - z = q[n + 4], - r = q[n + 5], - t = q[n + 6], - w = q[n + 7], - v = q[n + 8], - A = q[n + 9], - B = q[n + 10], - C = q[n + 11], - u = q[n + 12], - D = q[n + 13], - E = q[n + 14], - x = q[n + 15], - f = a[0], - m = a[1], - g = a[2], - h = a[3], - f = p(f, m, g, h, c, 7, b[0]), - h = p(h, f, m, g, e, 12, b[1]), - g = p(g, h, f, m, j, 17, b[2]), - m = p(m, g, h, f, k, 22, b[3]), - f = p(f, m, g, h, z, 7, b[4]), - h = p(h, f, m, g, r, 12, b[5]), - g = p(g, h, f, m, t, 17, b[6]), - m = p(m, g, h, f, w, 22, b[7]), - f = p(f, m, g, h, v, 7, b[8]), - h = p(h, f, m, g, A, 12, b[9]), - g = p(g, h, f, m, B, 17, b[10]), - m = p(m, g, h, f, C, 22, b[11]), - f = p(f, m, g, h, u, 7, b[12]), - h = p(h, f, m, g, D, 12, b[13]), - g = p(g, h, f, m, E, 17, b[14]), - m = p(m, g, h, f, x, 22, b[15]), - f = d(f, m, g, h, e, 5, b[16]), - h = d(h, f, m, g, t, 9, b[17]), - g = d(g, h, f, m, C, 14, b[18]), - m = d(m, g, h, f, c, 20, b[19]), - f = d(f, m, g, h, r, 5, b[20]), - h = d(h, f, m, g, B, 9, b[21]), - g = d(g, h, f, m, x, 14, b[22]), - m = d(m, g, h, f, z, 20, b[23]), - f = d(f, m, g, h, A, 5, b[24]), - h = d(h, f, m, g, E, 9, b[25]), - g = d(g, h, f, m, k, 14, b[26]), - m = d(m, g, h, f, v, 20, b[27]), - f = d(f, m, g, h, D, 5, b[28]), - h = d(h, f, m, g, j, 9, b[29]), - g = d(g, h, f, m, w, 14, b[30]), - m = d(m, g, h, f, u, 20, b[31]), - f = l(f, m, g, h, r, 4, b[32]), - h = l(h, f, m, g, v, 11, b[33]), - g = l(g, h, f, m, C, 16, b[34]), - m = l(m, g, h, f, E, 23, b[35]), - f = l(f, m, g, h, e, 4, b[36]), - h = l(h, f, m, g, z, 11, b[37]), - g = l(g, h, f, m, w, 16, b[38]), - m = l(m, g, h, f, B, 23, b[39]), - f = l(f, m, g, h, D, 4, b[40]), - h = l(h, f, m, g, c, 11, b[41]), - g = l(g, h, f, m, k, 16, b[42]), - m = l(m, g, h, f, t, 23, b[43]), - f = l(f, m, g, h, A, 4, b[44]), - h = l(h, f, m, g, u, 11, b[45]), - g = l(g, h, f, m, x, 16, b[46]), - m = l(m, g, h, f, j, 23, b[47]), - f = s(f, m, g, h, c, 6, b[48]), - h = s(h, f, m, g, w, 10, b[49]), - g = s(g, h, f, m, E, 15, b[50]), - m = s(m, g, h, f, r, 21, b[51]), - f = s(f, m, g, h, u, 6, b[52]), - h = s(h, f, m, g, k, 10, b[53]), - g = s(g, h, f, m, B, 15, b[54]), - m = s(m, g, h, f, e, 21, b[55]), - f = s(f, m, g, h, v, 6, b[56]), - h = s(h, f, m, g, x, 10, b[57]), - g = s(g, h, f, m, t, 15, b[58]), - m = s(m, g, h, f, D, 21, b[59]), - f = s(f, m, g, h, z, 6, b[60]), - h = s(h, f, m, g, C, 10, b[61]), - g = s(g, h, f, m, j, 15, b[62]), - m = s(m, g, h, f, A, 21, b[63]); - a[0] = (a[0] + f) | 0; - a[1] = (a[1] + m) | 0; - a[2] = (a[2] + g) | 0; - a[3] = (a[3] + h) | 0; - }, - _doFinalize: function () { - var b = this._data, - n = b.words, - a = 8 * this._nDataBytes, - c = 8 * b.sigBytes; - n[c >>> 5] |= 128 << (24 - (c % 32)); - var e = u.floor(a / 4294967296); - n[(((c + 64) >>> 9) << 4) + 15] = (((e << 8) | (e >>> 24)) & 16711935) | (((e << 24) | (e >>> 8)) & 4278255360); - n[(((c + 64) >>> 9) << 4) + 14] = (((a << 8) | (a >>> 24)) & 16711935) | (((a << 24) | (a >>> 8)) & 4278255360); - b.sigBytes = 4 * (n.length + 1); - this._process(); - b = this._hash; - n = b.words; - for (a = 0; 4 > a; a++) - (c = n[a]), (n[a] = (((c << 8) | (c >>> 24)) & 16711935) | (((c << 24) | (c >>> 8)) & 4278255360)); - return b; - }, - clone: function () { - var b = v.clone.call(this); - b._hash = this._hash.clone(); - return b; - }, - }); - t.MD5 = v._createHelper(r); - t.HmacMD5 = v._createHmacHelper(r); -})(Math); -(function () { - var u = CryptoJS, - p = u.lib, - d = p.Base, - l = p.WordArray, - p = u.algo, - s = (p.EvpKDF = d.extend({ - cfg: d.extend({ keySize: 4, hasher: p.MD5, iterations: 1 }), - init: function (d) { - this.cfg = this.cfg.extend(d); - }, - compute: function (d, r) { - for ( - var p = this.cfg, s = p.hasher.create(), b = l.create(), u = b.words, q = p.keySize, p = p.iterations; - u.length < q; - - ) { - n && s.update(n); - var n = s.update(d).finalize(r); - s.reset(); - for (var a = 1; a < p; a++) (n = s.finalize(n)), s.reset(); - b.concat(n); - } - b.sigBytes = 4 * q; - return b; - }, - })); - u.EvpKDF = function (d, l, p) { - return s.create(p).compute(d, l); - }; -})(); - -// Cipher -CryptoJS.lib.Cipher || - (function (u) { - var p = CryptoJS, - d = p.lib, - l = d.Base, - s = d.WordArray, - t = d.BufferedBlockAlgorithm, - r = p.enc.Base64, - w = p.algo.EvpKDF, - v = (d.Cipher = t.extend({ - cfg: l.extend(), - createEncryptor: function (e, a) { - return this.create(this._ENC_XFORM_MODE, e, a); - }, - createDecryptor: function (e, a) { - return this.create(this._DEC_XFORM_MODE, e, a); - }, - init: function (e, a, b) { - this.cfg = this.cfg.extend(b); - this._xformMode = e; - this._key = a; - this.reset(); - }, - reset: function () { - t.reset.call(this); - this._doReset(); - }, - process: function (e) { - this._append(e); - return this._process(); - }, - finalize: function (e) { - e && this._append(e); - return this._doFinalize(); - }, - keySize: 4, - ivSize: 4, - _ENC_XFORM_MODE: 1, - _DEC_XFORM_MODE: 2, - _createHelper: function (e) { - return { - encrypt: function (b, k, d) { - return ('string' == typeof k ? c : a).encrypt(e, b, k, d); - }, - decrypt: function (b, k, d) { - return ('string' == typeof k ? c : a).decrypt(e, b, k, d); - }, - }; - }, - })); - d.StreamCipher = v.extend({ - _doFinalize: function () { - return this._process(!0); - }, - blockSize: 1, - }); - var b = (p.mode = {}), - x = function (e, a, b) { - var c = this._iv; - c ? (this._iv = u) : (c = this._prevBlock); - for (var d = 0; d < b; d++) e[a + d] ^= c[d]; - }, - q = (d.BlockCipherMode = l.extend({ - createEncryptor: function (e, a) { - return this.Encryptor.create(e, a); - }, - createDecryptor: function (e, a) { - return this.Decryptor.create(e, a); - }, - init: function (e, a) { - this._cipher = e; - this._iv = a; - }, - })).extend(); - q.Encryptor = q.extend({ - processBlock: function (e, a) { - var b = this._cipher, - c = b.blockSize; - x.call(this, e, a, c); - b.encryptBlock(e, a); - this._prevBlock = e.slice(a, a + c); - }, - }); - q.Decryptor = q.extend({ - processBlock: function (e, a) { - var b = this._cipher, - c = b.blockSize, - d = e.slice(a, a + c); - b.decryptBlock(e, a); - x.call(this, e, a, c); - this._prevBlock = d; - }, - }); - b = b.CBC = q; - q = (p.pad = {}).Pkcs7 = { - pad: function (a, b) { - for ( - var c = 4 * b, c = c - (a.sigBytes % c), d = (c << 24) | (c << 16) | (c << 8) | c, l = [], n = 0; - n < c; - n += 4 - ) - l.push(d); - c = s.create(l, c); - a.concat(c); - }, - unpad: function (a) { - a.sigBytes -= a.words[(a.sigBytes - 1) >>> 2] & 255; - }, - }; - d.BlockCipher = v.extend({ - cfg: v.cfg.extend({ mode: b, padding: q }), - reset: function () { - v.reset.call(this); - var a = this.cfg, - b = a.iv, - a = a.mode; - if (this._xformMode == this._ENC_XFORM_MODE) var c = a.createEncryptor; - else (c = a.createDecryptor), (this._minBufferSize = 1); - this._mode = c.call(a, this, b && b.words); - }, - _doProcessBlock: function (a, b) { - this._mode.processBlock(a, b); - }, - _doFinalize: function () { - var a = this.cfg.padding; - if (this._xformMode == this._ENC_XFORM_MODE) { - a.pad(this._data, this.blockSize); - var b = this._process(!0); - } else (b = this._process(!0)), a.unpad(b); - return b; - }, - blockSize: 4, - }); - var n = (d.CipherParams = l.extend({ - init: function (a) { - this.mixIn(a); - }, - toString: function (a) { - return (a || this.formatter).stringify(this); - }, - })), - b = ((p.format = {}).OpenSSL = { - stringify: function (a) { - var b = a.ciphertext; - a = a.salt; - return (a ? s.create([1398893684, 1701076831]).concat(a).concat(b) : b).toString(r); - }, - parse: function (a) { - a = r.parse(a); - var b = a.words; - if (1398893684 == b[0] && 1701076831 == b[1]) { - var c = s.create(b.slice(2, 4)); - b.splice(0, 4); - a.sigBytes -= 16; - } - return n.create({ ciphertext: a, salt: c }); - }, - }), - a = (d.SerializableCipher = l.extend({ - cfg: l.extend({ format: b }), - encrypt: function (a, b, c, d) { - d = this.cfg.extend(d); - var l = a.createEncryptor(c, d); - b = l.finalize(b); - l = l.cfg; - return n.create({ - ciphertext: b, - key: c, - iv: l.iv, - algorithm: a, - mode: l.mode, - padding: l.padding, - blockSize: a.blockSize, - formatter: d.format, - }); - }, - decrypt: function (a, b, c, d) { - d = this.cfg.extend(d); - b = this._parse(b, d.format); - return a.createDecryptor(c, d).finalize(b.ciphertext); - }, - _parse: function (a, b) { - return 'string' == typeof a ? b.parse(a, this) : a; - }, - })), - p = ((p.kdf = {}).OpenSSL = { - execute: function (a, b, c, d) { - d || (d = s.random(8)); - a = w.create({ keySize: b + c }).compute(a, d); - c = s.create(a.words.slice(b), 4 * c); - a.sigBytes = 4 * b; - return n.create({ key: a, iv: c, salt: d }); - }, - }), - c = (d.PasswordBasedCipher = a.extend({ - cfg: a.cfg.extend({ kdf: p }), - encrypt: function (b, c, d, l) { - l = this.cfg.extend(l); - d = l.kdf.execute(d, b.keySize, b.ivSize); - l.iv = d.iv; - b = a.encrypt.call(this, b, c, d.key, l); - b.mixIn(d); - return b; - }, - decrypt: function (b, c, d, l) { - l = this.cfg.extend(l); - c = this._parse(c, l.format); - d = l.kdf.execute(d, b.keySize, b.ivSize, c.salt); - l.iv = d.iv; - return a.decrypt.call(this, b, c, d.key, l); - }, - })); - })(); - -// AES -(function () { - for ( - var u = CryptoJS, - p = u.lib.BlockCipher, - d = u.algo, - l = [], - s = [], - t = [], - r = [], - w = [], - v = [], - b = [], - x = [], - q = [], - n = [], - a = [], - c = 0; - 256 > c; - c++ - ) - a[c] = 128 > c ? c << 1 : (c << 1) ^ 283; - for (var e = 0, j = 0, c = 0; 256 > c; c++) { - var k = j ^ (j << 1) ^ (j << 2) ^ (j << 3) ^ (j << 4), - k = (k >>> 8) ^ (k & 255) ^ 99; - l[e] = k; - s[k] = e; - var z = a[e], - F = a[z], - G = a[F], - y = (257 * a[k]) ^ (16843008 * k); - t[e] = (y << 24) | (y >>> 8); - r[e] = (y << 16) | (y >>> 16); - w[e] = (y << 8) | (y >>> 24); - v[e] = y; - y = (16843009 * G) ^ (65537 * F) ^ (257 * z) ^ (16843008 * e); - b[k] = (y << 24) | (y >>> 8); - x[k] = (y << 16) | (y >>> 16); - q[k] = (y << 8) | (y >>> 24); - n[k] = y; - e ? ((e = z ^ a[a[a[G ^ z]]]), (j ^= a[a[j]])) : (e = j = 1); - } - var H = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54], - d = (d.AES = p.extend({ - _doReset: function () { - for ( - var a = this._key, - c = a.words, - d = a.sigBytes / 4, - a = 4 * ((this._nRounds = d + 6) + 1), - e = (this._keySchedule = []), - j = 0; - j < a; - j++ - ) - if (j < d) e[j] = c[j]; - else { - var k = e[j - 1]; - j % d - ? 6 < d && - 4 == j % d && - (k = (l[k >>> 24] << 24) | (l[(k >>> 16) & 255] << 16) | (l[(k >>> 8) & 255] << 8) | l[k & 255]) - : ((k = (k << 8) | (k >>> 24)), - (k = (l[k >>> 24] << 24) | (l[(k >>> 16) & 255] << 16) | (l[(k >>> 8) & 255] << 8) | l[k & 255]), - (k ^= H[(j / d) | 0] << 24)); - e[j] = e[j - d] ^ k; - } - c = this._invKeySchedule = []; - for (d = 0; d < a; d++) - (j = a - d), - (k = d % 4 ? e[j] : e[j - 4]), - (c[d] = - 4 > d || 4 >= j ? k : b[l[k >>> 24]] ^ x[l[(k >>> 16) & 255]] ^ q[l[(k >>> 8) & 255]] ^ n[l[k & 255]]); - }, - encryptBlock: function (a, b) { - this._doCryptBlock(a, b, this._keySchedule, t, r, w, v, l); - }, - decryptBlock: function (a, c) { - var d = a[c + 1]; - a[c + 1] = a[c + 3]; - a[c + 3] = d; - this._doCryptBlock(a, c, this._invKeySchedule, b, x, q, n, s); - d = a[c + 1]; - a[c + 1] = a[c + 3]; - a[c + 3] = d; - }, - _doCryptBlock: function (a, b, c, d, e, j, l, f) { - for ( - var m = this._nRounds, - g = a[b] ^ c[0], - h = a[b + 1] ^ c[1], - k = a[b + 2] ^ c[2], - n = a[b + 3] ^ c[3], - p = 4, - r = 1; - r < m; - r++ - ) - var q = d[g >>> 24] ^ e[(h >>> 16) & 255] ^ j[(k >>> 8) & 255] ^ l[n & 255] ^ c[p++], - s = d[h >>> 24] ^ e[(k >>> 16) & 255] ^ j[(n >>> 8) & 255] ^ l[g & 255] ^ c[p++], - t = d[k >>> 24] ^ e[(n >>> 16) & 255] ^ j[(g >>> 8) & 255] ^ l[h & 255] ^ c[p++], - n = d[n >>> 24] ^ e[(g >>> 16) & 255] ^ j[(h >>> 8) & 255] ^ l[k & 255] ^ c[p++], - g = q, - h = s, - k = t; - q = ((f[g >>> 24] << 24) | (f[(h >>> 16) & 255] << 16) | (f[(k >>> 8) & 255] << 8) | f[n & 255]) ^ c[p++]; - s = ((f[h >>> 24] << 24) | (f[(k >>> 16) & 255] << 16) | (f[(n >>> 8) & 255] << 8) | f[g & 255]) ^ c[p++]; - t = ((f[k >>> 24] << 24) | (f[(n >>> 16) & 255] << 16) | (f[(g >>> 8) & 255] << 8) | f[h & 255]) ^ c[p++]; - n = ((f[n >>> 24] << 24) | (f[(g >>> 16) & 255] << 16) | (f[(h >>> 8) & 255] << 8) | f[k & 255]) ^ c[p++]; - a[b] = q; - a[b + 1] = s; - a[b + 2] = t; - a[b + 3] = n; - }, - keySize: 8, - })); - u.AES = p._createHelper(d); -})(); - -// Mode ECB -CryptoJS.mode.ECB = (function () { - var ECB = CryptoJS.lib.BlockCipherMode.extend(); - - ECB.Encryptor = ECB.extend({ - processBlock: function (words, offset) { - this._cipher.encryptBlock(words, offset); - }, - }); - - ECB.Decryptor = ECB.extend({ - processBlock: function (words, offset) { - this._cipher.decryptBlock(words, offset); - }, - }); - - return ECB; -})(); - -module.exports = CryptoJS; diff --git a/src/core/components/cryptography/index.ts b/src/core/components/cryptography/index.ts index 5d2ae929c..42717c055 100644 --- a/src/core/components/cryptography/index.ts +++ b/src/core/components/cryptography/index.ts @@ -1,390 +1,20 @@ /** - * Legacy cryptography module. + * Legacy cryptography module (`@noble`-backed: Web, React Native). * * @internal */ import { CryptorConfiguration } from '../../interfaces/crypto-module'; -import { LoggerManager } from '../logger-manager'; -import { isSensitiveLogKey } from '../../utils'; -import { Payload } from '../../types/api'; -import { decode } from '../base64_codec'; -import CryptoJS from './hmac-sha256'; +import { noblePrimitives } from './noble-primitives'; +import { LegacyCrypto } from './legacy-crypto'; /** - * Convert bytes array to words array. - * - * @param b - Bytes array (buffer) which should be converted. - * - * @returns Word sized array. - * - * @internal - */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -function bufferToWordArray(b: string | any[] | Uint8ClampedArray) { - const wa: number[] = []; - let i; - for (i = 0; i < b.length; i += 1) { - wa[(i / 4) | 0] |= b[i] << (24 - 8 * i); - } - - // @ts-expect-error Bundled library without types. - return CryptoJS.lib.WordArray.create(wa, b.length); -} - -/** - * Legacy cryptor configuration options. + * Legacy cryptography module for data encryption / decryption. * * @internal */ -type CryptoConfiguration = { - encryptKey?: boolean; - keyEncoding?: 'hex' | 'utf8' | 'base64' | 'binary'; - keyLength?: 128 | 256; - mode?: 'ecb' | 'cbc'; -}; - -/** - * Legacy cryptography module for files and signature. - * - * @internal - */ -export default class { - /** - * Crypto initialization vector. - */ - private iv = '0123456789012345'; - - /** - * List os allowed cipher key encodings. - */ - private allowedKeyEncodings = ['hex', 'utf8', 'base64', 'binary']; - - /** - * Allowed cipher key lengths. - */ - private allowedKeyLengths = [128, 256]; - - /** - * Allowed crypto modes. - */ - private allowedModes = ['ecb', 'cbc']; - - /** - * Default cryptor configuration options. - */ - private readonly defaultOptions: Required; - - /** - * Registered loggers' manager. - */ - private _logger?: LoggerManager; - - constructor(private readonly configuration: CryptorConfiguration) { - this.logger = configuration.logger; - - this.defaultOptions = { - encryptKey: true, - keyEncoding: 'utf8', - keyLength: 256, - mode: 'cbc', - }; - } - - /** - * Update registered loggers' manager. - * - * @param [logger] - Logger, which crypto should use. - */ - set logger(logger: LoggerManager | undefined) { - this._logger = logger; - - if (this.logger) { - this.logger.debug('Crypto', () => ({ - messageType: 'object', - message: this.configuration as unknown as Record, - details: 'Create with configuration:', - ignoredKeys(key: string, obj: Record) { - return typeof obj[key] === 'function' || key === 'logger' || isSensitiveLogKey(key); - }, - })); - } - } - - /** - * Get loggers' manager. - * - * @returns Loggers' manager (if set). - */ - get logger() { - return this._logger; - } - - /** - * Generate HMAC-SHA256 hash from input data. - * - * @param data - Data from which hash should be generated. - * - * @returns HMAC-SHA256 hash from provided `data`. - */ - public HMACSHA256(data: string): string { - // @ts-expect-error Bundled library without types. - const hash = CryptoJS.HmacSHA256(data, this.configuration.secretKey); - // @ts-expect-error Bundled library without types. - return hash.toString(CryptoJS.enc.Base64); - } - - /** - * Generate SHA256 hash from input data. - * - * @param data - Data from which hash should be generated. - * - * @returns SHA256 hash from provided `data`. - */ - public SHA256(data: string): string { - // @ts-expect-error Bundled library without types. - return CryptoJS.SHA256(data).toString(CryptoJS.enc.Hex); - } - - /** - * Encrypt provided data. - * - * @param data - Source data which should be encrypted. - * @param [customCipherKey] - Custom cipher key (different from defined on client level). - * @param [options] - Specific crypto configuration options. - * - * @returns Encrypted `data`. - */ - public encrypt(data: string | Payload, customCipherKey?: string, options?: CryptoConfiguration) { - if (this.configuration.customEncrypt) { - if (this.logger) - this.logger.warn('Crypto', "'customEncrypt' is deprecated. Consult docs for better alternative."); - - return this.configuration.customEncrypt(data); - } - - return this.pnEncrypt(data as string, customCipherKey, options); - } - - /** - * Decrypt provided data. - * - * @param data - Encrypted data which should be decrypted. - * @param [customCipherKey] - Custom cipher key (different from defined on client level). - * @param [options] - Specific crypto configuration options. - * - * @returns Decrypted `data`. - */ - public decrypt(data: string, customCipherKey?: string, options?: CryptoConfiguration) { - if (this.configuration.customDecrypt) { - if (this.logger) - this.logger.warn('Crypto', "'customDecrypt' is deprecated. Consult docs for better alternative."); - - return this.configuration.customDecrypt(data); - } - - return this.pnDecrypt(data, customCipherKey, options); - } - - /** - * Encrypt provided data. - * - * @param data - Source data which should be encrypted. - * @param [customCipherKey] - Custom cipher key (different from defined on client level). - * @param [options] - Specific crypto configuration options. - * - * @returns Encrypted `data` as string. - */ - private pnEncrypt(data: string, customCipherKey?: string, options?: CryptoConfiguration): string { - const decidedCipherKey = customCipherKey ?? this.configuration.cipherKey; - if (!decidedCipherKey) return data; - - if (this.logger) { - this.logger.debug('Crypto', () => ({ - messageType: 'object', - message: { data, ...(options ?? {}) }, - details: 'Encrypt with parameters:', - ignoredKeys: isSensitiveLogKey, - })); - } - - options = this.parseOptions(options); - const mode = this.getMode(options); - const cipherKey = this.getPaddedKey(decidedCipherKey, options); - - if (this.configuration.useRandomIVs) { - const waIv = this.getRandomIV(); - // @ts-expect-error Bundled library without types. - const waPayload = CryptoJS.AES.encrypt(data, cipherKey, { iv: waIv, mode }).ciphertext; - - // @ts-expect-error Bundled library without types. - return waIv.clone().concat(waPayload.clone()).toString(CryptoJS.enc.Base64); - } - - const iv = this.getIV(options); - // @ts-expect-error Bundled library without types. - const encryptedHexArray = CryptoJS.AES.encrypt(data, cipherKey, { iv, mode }).ciphertext; - // @ts-expect-error Bundled library without types. - const base64Encrypted = encryptedHexArray.toString(CryptoJS.enc.Base64); - - return base64Encrypted || data; - } - - /** - * Decrypt provided data. - * - * @param data - Encrypted data which should be decrypted. - * @param [customCipherKey] - Custom cipher key (different from defined on client level). - * @param [options] - Specific crypto configuration options. - * - * @returns Decrypted `data`. - */ - private pnDecrypt(data: string, customCipherKey?: string, options?: CryptoConfiguration): Payload | null { - const decidedCipherKey = customCipherKey ?? this.configuration.cipherKey; - if (!decidedCipherKey) return data; - - if (this.logger) { - this.logger.debug('Crypto', () => ({ - messageType: 'object', - message: { data, ...(options ?? {}) }, - details: 'Decrypt with parameters:', - ignoredKeys: isSensitiveLogKey, - })); - } - - options = this.parseOptions(options); - const mode = this.getMode(options); - const cipherKey = this.getPaddedKey(decidedCipherKey, options); - - if (this.configuration.useRandomIVs) { - const ciphertext = new Uint8ClampedArray(decode(data)); - - const iv = bufferToWordArray(ciphertext.slice(0, 16)); - const payload = bufferToWordArray(ciphertext.slice(16)); - - try { - // @ts-expect-error Bundled library without types. - const plainJSON = CryptoJS.AES.decrypt({ ciphertext: payload }, cipherKey, { iv, mode }).toString( - // @ts-expect-error Bundled library without types. - CryptoJS.enc.Utf8, - ); - return JSON.parse(plainJSON); - } catch (e) { - if (this.logger) this.logger.error('Crypto', () => ({ messageType: 'error', message: e })); - - return null; - } - } else { - const iv = this.getIV(options); - try { - // @ts-expect-error Bundled library without types. - const ciphertext = CryptoJS.enc.Base64.parse(data); - // @ts-expect-error Bundled library without types. - const plainJSON = CryptoJS.AES.decrypt({ ciphertext }, cipherKey, { iv, mode }).toString(CryptoJS.enc.Utf8); - return JSON.parse(plainJSON); - } catch (e) { - if (this.logger) this.logger.error('Crypto', () => ({ messageType: 'error', message: e })); - - return null; - } - } - } - - /** - * Pre-process provided custom crypto configuration. - * - * @param incomingOptions - Configuration which should be pre-processed before use. - * - * @returns Normalized crypto configuration options. - */ - private parseOptions(incomingOptions?: CryptoConfiguration): Required { - if (!incomingOptions) return this.defaultOptions; - - // Defaults - const options = { - encryptKey: incomingOptions.encryptKey ?? this.defaultOptions.encryptKey, - keyEncoding: incomingOptions.keyEncoding ?? this.defaultOptions.keyEncoding, - keyLength: incomingOptions.keyLength ?? this.defaultOptions.keyLength, - mode: incomingOptions.mode ?? this.defaultOptions.mode, - }; - - // Validation - if (this.allowedKeyEncodings.indexOf(options.keyEncoding!.toLowerCase()) === -1) - options.keyEncoding = this.defaultOptions.keyEncoding; - if (this.allowedKeyLengths.indexOf(options.keyLength!) === -1) options.keyLength = this.defaultOptions.keyLength; - if (this.allowedModes.indexOf(options.mode!.toLowerCase()) === -1) options.mode = this.defaultOptions.mode; - - return options; - } - - /** - * Decode provided cipher key. - * - * @param key - Key in `encoding` provided by `options`. - * @param options - Crypto configuration options with cipher key details. - * - * @returns Array buffer with decoded key. - */ - private decodeKey(key: string, options: CryptoConfiguration) { - // @ts-expect-error Bundled library without types. - if (options.keyEncoding === 'base64') return CryptoJS.enc.Base64.parse(key); - // @ts-expect-error Bundled library without types. - if (options.keyEncoding === 'hex') return CryptoJS.enc.Hex.parse(key); - - return key; - } - - /** - * Add padding to the cipher key. - * - * @param key - Key which should be padded. - * @param options - Crypto configuration options with cipher key details. - * - * @returns Properly padded cipher key. - */ - private getPaddedKey(key: string, options: CryptoConfiguration) { - key = this.decodeKey(key, options); - - // @ts-expect-error Bundled library without types. - if (options.encryptKey) return CryptoJS.enc.Utf8.parse(this.SHA256(key).slice(0, 32)); - - return key; - } - - /** - * Cipher mode. - * - * @param options - Crypto configuration with information about cipher mode. - * - * @returns Crypto cipher mode. - */ - private getMode(options: CryptoConfiguration) { - // @ts-expect-error Bundled library without types. - if (options.mode === 'ecb') return CryptoJS.mode.ECB; - - // @ts-expect-error Bundled library without types. - return CryptoJS.mode.CBC; - } - - /** - * Cipher initialization vector. - * - * @param options - Crypto configuration with information about cipher mode. - * - * @returns Initialization vector. - */ - private getIV(options: CryptoConfiguration) { - // @ts-expect-error Bundled library without types. - return options.mode === 'cbc' ? CryptoJS.enc.Utf8.parse(this.iv) : null; - } - - /** - * Random initialization vector. - * - * @returns Generated random initialization vector. - */ - private getRandomIV() { - // @ts-expect-error Bundled library without types. - return CryptoJS.lib.WordArray.random(16); +export default class Crypto extends LegacyCrypto { + constructor(configuration: CryptorConfiguration) { + super(configuration, noblePrimitives); } } diff --git a/src/core/components/cryptography/legacy-crypto.ts b/src/core/components/cryptography/legacy-crypto.ts new file mode 100644 index 000000000..b1abeaf08 --- /dev/null +++ b/src/core/components/cryptography/legacy-crypto.ts @@ -0,0 +1,386 @@ +/** + * Legacy cryptography module. + * + * Platform-agnostic implementation which relies on platform-provided crypto primitives. + * + * @internal + */ + +import { + AesMode, + bytesToHex, + concatBytes, + CryptoPrimitives, + decodeUtf8, + encodeUtf8, + hexToBytes, + toArrayBuffer, +} from './primitives'; +import { CryptorConfiguration } from '../../interfaces/crypto-module'; +import { LoggerManager } from '../logger-manager'; +import { isSensitiveLogKey } from '../../utils'; +import { decode, encode } from '../base64_codec'; +import { Payload } from '../../types/api'; + +/** + * Whether insecure random initialization vector fallback warning has been printed. + * + * @internal + */ +let insecureRandomWarningShown = false; + +/** + * Legacy cryptor configuration options. + * + * @internal + */ +type CryptoConfiguration = { + encryptKey?: boolean; + keyEncoding?: 'hex' | 'utf8' | 'base64' | 'binary'; + keyLength?: 128 | 256; + mode?: 'ecb' | 'cbc'; +}; + +/** + * Legacy cryptography module for files and signature. + * + * @internal + */ +export class LegacyCrypto { + /** + * Crypto initialization vector. + */ + private iv = '0123456789012345'; + + /** + * List os allowed cipher key encodings. + */ + private allowedKeyEncodings = ['hex', 'utf8', 'base64', 'binary']; + + /** + * Allowed cipher key lengths. + */ + private allowedKeyLengths = [128, 256]; + + /** + * Allowed crypto modes. + */ + private allowedModes = ['ecb', 'cbc']; + + /** + * Default cryptor configuration options. + */ + private readonly defaultOptions: Required; + + /** + * Registered loggers' manager. + */ + private _logger?: LoggerManager; + + constructor( + private readonly configuration: CryptorConfiguration, + private readonly primitives: CryptoPrimitives, + ) { + this.logger = configuration.logger; + + this.defaultOptions = { + encryptKey: true, + keyEncoding: 'utf8', + keyLength: 256, + mode: 'cbc', + }; + } + + /** + * Update registered loggers' manager. + * + * @param [logger] - Logger, which crypto should use. + */ + set logger(logger: LoggerManager | undefined) { + this._logger = logger; + + if (this.logger) { + this.logger.debug('Crypto', () => ({ + messageType: 'object', + message: this.configuration as unknown as Record, + details: 'Create with configuration:', + ignoredKeys(key: string, obj: Record) { + return typeof obj[key] === 'function' || key === 'logger' || isSensitiveLogKey(key); + }, + })); + } + } + + /** + * Get loggers' manager. + * + * @returns Loggers' manager (if set). + */ + get logger() { + return this._logger; + } + + /** + * Generate HMAC-SHA256 hash from input data. + * + * @param data - Data from which hash should be generated. + * + * @returns HMAC-SHA256 hash from provided `data`. + */ + public HMACSHA256(data: string): string { + const hash = this.primitives.hmacSha256(encodeUtf8(this.configuration.secretKey ?? ''), encodeUtf8(data)); + return encode(toArrayBuffer(hash)); + } + + /** + * Generate SHA256 hash from input data. + * + * @param data - Data from which hash should be generated. + * + * @returns SHA256 hash from provided `data`. + */ + public SHA256(data: string): string { + return bytesToHex(this.primitives.sha256(encodeUtf8(data))); + } + + /** + * Encrypt provided data. + * + * @param data - Source data which should be encrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Encrypted `data`. + */ + public encrypt(data: string | Payload, customCipherKey?: string, options?: CryptoConfiguration) { + if (this.configuration.customEncrypt) { + if (this.logger) + this.logger.warn('Crypto', "'customEncrypt' is deprecated. Consult docs for better alternative."); + + return this.configuration.customEncrypt(data); + } + + return this.pnEncrypt(data as string, customCipherKey, options); + } + + /** + * Decrypt provided data. + * + * @param data - Encrypted data which should be decrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Decrypted `data`. + */ + public decrypt(data: string, customCipherKey?: string, options?: CryptoConfiguration) { + if (this.configuration.customDecrypt) { + if (this.logger) + this.logger.warn('Crypto', "'customDecrypt' is deprecated. Consult docs for better alternative."); + + return this.configuration.customDecrypt(data); + } + + return this.pnDecrypt(data, customCipherKey, options); + } + + /** + * Encrypt provided data. + * + * @param data - Source data which should be encrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Encrypted `data` as string. + */ + private pnEncrypt(data: string, customCipherKey?: string, options?: CryptoConfiguration): string { + const decidedCipherKey = customCipherKey ?? this.configuration.cipherKey; + if (!decidedCipherKey) return data; + + if (this.logger) { + this.logger.debug('Crypto', () => ({ + messageType: 'object', + message: { data, ...(options ?? {}) }, + details: 'Encrypt with parameters:', + ignoredKeys: isSensitiveLogKey, + })); + } + + if (typeof data !== 'string') throw new Error('Encryption error: data should be a string'); + + options = this.parseOptions(options); + const mode = this.getMode(options); + const cipherKey = this.getPaddedKey(decidedCipherKey, options); + const plaintext = encodeUtf8(data); + + if (this.configuration.useRandomIVs) { + const iv = this.getRandomIV(); + const payload = this.primitives.aesEncrypt(mode, cipherKey, iv, plaintext); + + return encode(toArrayBuffer(concatBytes(iv, payload))); + } + + const encrypted = this.primitives.aesEncrypt(mode, cipherKey, this.getIV(options), plaintext); + const base64Encrypted = encode(toArrayBuffer(encrypted)); + + return base64Encrypted || data; + } + + /** + * Decrypt provided data. + * + * @param data - Encrypted data which should be decrypted. + * @param [customCipherKey] - Custom cipher key (different from defined on client level). + * @param [options] - Specific crypto configuration options. + * + * @returns Decrypted `data`. + */ + private pnDecrypt(data: string, customCipherKey?: string, options?: CryptoConfiguration): Payload | null { + const decidedCipherKey = customCipherKey ?? this.configuration.cipherKey; + if (!decidedCipherKey) return data; + + if (this.logger) { + this.logger.debug('Crypto', () => ({ + messageType: 'object', + message: { data, ...(options ?? {}) }, + details: 'Decrypt with parameters:', + ignoredKeys: isSensitiveLogKey, + })); + } + + options = this.parseOptions(options); + const mode = this.getMode(options); + const cipherKey = this.getPaddedKey(decidedCipherKey, options); + + if (this.configuration.useRandomIVs) { + const ciphertext = new Uint8Array(decode(data)); + + const iv = ciphertext.slice(0, 16); + const payload = ciphertext.slice(16); + + try { + const plainJSON = decodeUtf8(this.primitives.aesDecrypt(mode, cipherKey, iv, payload)); + return JSON.parse(plainJSON); + } catch (e) { + if (this.logger) this.logger.error('Crypto', () => ({ messageType: 'error', message: e })); + + return null; + } + } else { + const iv = this.getIV(options); + try { + const ciphertext = new Uint8Array(decode(data)); + const plainJSON = decodeUtf8(this.primitives.aesDecrypt(mode, cipherKey, iv, ciphertext)); + return JSON.parse(plainJSON); + } catch (e) { + if (this.logger) this.logger.error('Crypto', () => ({ messageType: 'error', message: e })); + + return null; + } + } + } + + /** + * Pre-process provided custom crypto configuration. + * + * @param incomingOptions - Configuration which should be pre-processed before use. + * + * @returns Normalized crypto configuration options. + */ + private parseOptions(incomingOptions?: CryptoConfiguration): Required { + if (!incomingOptions) return this.defaultOptions; + + // Defaults + const options = { + encryptKey: incomingOptions.encryptKey ?? this.defaultOptions.encryptKey, + keyEncoding: incomingOptions.keyEncoding ?? this.defaultOptions.keyEncoding, + keyLength: incomingOptions.keyLength ?? this.defaultOptions.keyLength, + mode: incomingOptions.mode ?? this.defaultOptions.mode, + }; + + // Validation + if (this.allowedKeyEncodings.indexOf(options.keyEncoding!.toLowerCase()) === -1) + options.keyEncoding = this.defaultOptions.keyEncoding; + if (this.allowedKeyLengths.indexOf(options.keyLength!) === -1) options.keyLength = this.defaultOptions.keyLength; + if (this.allowedModes.indexOf(options.mode!.toLowerCase()) === -1) options.mode = this.defaultOptions.mode; + + return options; + } + + /** + * Decode provided cipher key. + * + * @param key - Key in `encoding` provided by `options`. + * @param options - Crypto configuration options with cipher key details. + * + * @returns Bytes array with decoded key. + */ + private decodeKey(key: string, options: CryptoConfiguration): Uint8Array { + if (options.keyEncoding === 'base64') return new Uint8Array(decode(key)); + if (options.keyEncoding === 'hex') return hexToBytes(key); + + return encodeUtf8(key); + } + + /** + * Add padding to the cipher key. + * + * @param key - Key which should be padded. + * @param options - Crypto configuration options with cipher key details. + * + * @returns Properly padded cipher key. + */ + private getPaddedKey(key: string, options: CryptoConfiguration): Uint8Array { + const decodedKey = this.decodeKey(key, options); + + if (options.encryptKey) return encodeUtf8(bytesToHex(this.primitives.sha256(decodedKey)).slice(0, 32)); + + return decodedKey; + } + + /** + * Cipher mode. + * + * @param options - Crypto configuration with information about cipher mode. + * + * @returns Crypto cipher mode. + */ + private getMode(options: CryptoConfiguration): AesMode { + return options.mode === 'ecb' ? 'ecb' : 'cbc'; + } + + /** + * Cipher initialization vector. + * + * @param options - Crypto configuration with information about cipher mode. + * + * @returns Initialization vector. + */ + private getIV(options: CryptoConfiguration): Uint8Array | null { + return options.mode === 'cbc' ? encodeUtf8(this.iv) : null; + } + + /** + * Random initialization vector. + * + * Falls back to the insecure `Math.random()` source (previous behavior) when the platform doesn't provide + * `crypto.getRandomValues` (for example, React Native without polyfill). + * + * @returns Generated random initialization vector. + */ + private getRandomIV(): Uint8Array { + try { + return this.primitives.randomBytes(16); + } catch (_) { + if (!insecureRandomWarningShown && this.logger) { + insecureRandomWarningShown = true; + this.logger.warn( + 'Crypto', + "'crypto.getRandomValues' is unavailable; falling back to insecure Math.random() IV. " + + "Install 'react-native-get-random-values'.", + ); + } + + return Uint8Array.from({ length: 16 }, () => Math.floor(Math.random() * 256)); + } + } +} diff --git a/src/core/components/cryptography/noble-primitives.ts b/src/core/components/cryptography/noble-primitives.ts new file mode 100644 index 000000000..db578a35f --- /dev/null +++ b/src/core/components/cryptography/noble-primitives.ts @@ -0,0 +1,47 @@ +/** + * Cryptography primitives backed by `@noble` (Web, React Native). + * + * @internal + */ + +import { cbc } from '@noble/ciphers/aes.js'; +import { randomBytes } from '@noble/ciphers/utils.js'; +import { sha256 } from '@noble/hashes/sha2.js'; + +import { AesMode, CryptoPrimitives, unpadLegacy } from './primitives'; + +/** + * Prepare AES-CBC cipher instance. + * + * **Note:** AES-ECB isn't reachable through public API and intentionally not bundled. + * + * @param mode - AES block cipher mode. + * @param key - AES key. + * @param iv - Initialization vector. + * + * @returns AES-CBC cipher. + * + * @internal + */ +const aesCipher = (mode: AesMode, key: Uint8Array, iv: Uint8Array | null, decrypt = false) => { + if (mode === 'ecb') throw new Error('AES-ECB is not supported'); + // Padding removed leniently by `unpadLegacy` on decryption (CryptoJS-compatible). + return cbc(key, iv!, decrypt ? { disablePadding: true } : undefined); +}; + +/** + * `@noble`-based cryptography primitives. + * + * **Note:** Request signature (HMAC-SHA256) is Node.js-only and intentionally not bundled. + * + * @internal + */ +export const noblePrimitives: CryptoPrimitives = { + sha256: (data) => sha256(data), + hmacSha256: () => { + throw new Error('HMAC-SHA256 is not supported on this platform'); + }, + aesEncrypt: (mode, key, iv, data) => aesCipher(mode, key, iv).encrypt(data), + aesDecrypt: (mode, key, iv, data) => unpadLegacy(aesCipher(mode, key, iv, true).decrypt(data)), + randomBytes: (length) => randomBytes(length), +}; diff --git a/src/core/components/cryptography/node-primitives.ts b/src/core/components/cryptography/node-primitives.ts new file mode 100644 index 000000000..9e0bbb18c --- /dev/null +++ b/src/core/components/cryptography/node-primitives.ts @@ -0,0 +1,43 @@ +/** + * Cryptography primitives backed by `node:crypto` (Node.js). + * + * @internal + */ + +import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from 'crypto'; +import { Buffer } from 'buffer'; + +import { AesMode, CryptoPrimitives, unpadLegacy } from './primitives'; + +/** + * OpenSSL cipher name for provided AES mode and key. + * + * @param mode - AES block cipher mode. + * @param key - AES key. + * + * @returns Cipher algorithm name. + * + * @internal + */ +const algorithm = (mode: AesMode, key: Uint8Array) => `aes-${key.length * 8}-${mode}`; + +/** + * `node:crypto`-based cryptography primitives. + * + * @internal + */ +export const nodePrimitives: CryptoPrimitives = { + sha256: (data) => createHash('sha256').update(data).digest(), + hmacSha256: (key, data) => createHmac('sha256', key).update(data).digest(), + aesEncrypt: (mode, key, iv, data) => { + const cipher = createCipheriv(algorithm(mode, key), key, mode === 'ecb' ? null : iv); + return Buffer.concat([cipher.update(data), cipher.final()]); + }, + aesDecrypt: (mode, key, iv, data) => { + const decipher = createDecipheriv(algorithm(mode, key), key, mode === 'ecb' ? null : iv); + // Padding removed leniently by `unpadLegacy` (CryptoJS-compatible). + decipher.setAutoPadding(false); + return unpadLegacy(Buffer.concat([decipher.update(data), decipher.final()])); + }, + randomBytes: (length) => randomBytes(length), +}; diff --git a/src/core/components/cryptography/node.ts b/src/core/components/cryptography/node.ts new file mode 100644 index 000000000..9f402fc09 --- /dev/null +++ b/src/core/components/cryptography/node.ts @@ -0,0 +1,20 @@ +/** + * Legacy cryptography module (`node:crypto`-backed: Node.js). + * + * @internal + */ + +import { CryptorConfiguration } from '../../interfaces/crypto-module'; +import { nodePrimitives } from './node-primitives'; +import { LegacyCrypto } from './legacy-crypto'; + +/** + * Legacy cryptography module for data encryption / decryption and request signature. + * + * @internal + */ +export default class Crypto extends LegacyCrypto { + constructor(configuration: CryptorConfiguration) { + super(configuration, nodePrimitives); + } +} diff --git a/src/core/components/cryptography/primitives.ts b/src/core/components/cryptography/primitives.ts new file mode 100644 index 000000000..1c6e9b4c6 --- /dev/null +++ b/src/core/components/cryptography/primitives.ts @@ -0,0 +1,252 @@ +/** + * Platform-agnostic cryptography primitives contract and byte helpers. + * + * @internal + */ + +/** + * AES block cipher mode. + * + * @internal + */ +export type AesMode = 'cbc' | 'ecb'; + +/** + * Platform-provided cryptography primitives. + * + * @internal + */ +export type CryptoPrimitives = { + /** + * Compute SHA-256 digest. + * + * @param data - Data from which digest should be computed. + * + * @returns SHA-256 digest bytes. + */ + sha256(data: Uint8Array): Uint8Array; + + /** + * Compute HMAC-SHA256. + * + * @param key - HMAC key. + * @param data - Data which should be signed. + * + * @returns HMAC-SHA256 bytes. + */ + hmacSha256(key: Uint8Array, data: Uint8Array): Uint8Array; + + /** + * Encrypt data with AES (PKCS#7 padding). + * + * @param mode - AES block cipher mode. + * @param key - AES key (16, 24 or 32 bytes). + * @param iv - Initialization vector (ignored for `ecb`). + * @param data - Data which should be encrypted. + * + * @returns Encrypted data. + */ + aesEncrypt(mode: AesMode, key: Uint8Array, iv: Uint8Array | null, data: Uint8Array): Uint8Array; + + /** + * Decrypt data with AES. + * + * Padding removed leniently (CryptoJS-compatible, see {@link unpadLegacy}). + * + * @param mode - AES block cipher mode. + * @param key - AES key (16, 24 or 32 bytes). + * @param iv - Initialization vector (ignored for `ecb`). + * @param data - Data which should be decrypted. + * + * @returns Decrypted data with padding removed. + * + * @throws Error if data can't be decrypted (for example, data length isn't a multiple of the block size). + */ + aesDecrypt(mode: AesMode, key: Uint8Array, iv: Uint8Array | null, data: Uint8Array): Uint8Array; + + /** + * Generate cryptographically secure random bytes. + * + * @param length - Number of bytes which should be generated. + * + * @returns Random bytes. + * + * @throws Error if platform doesn't provide secure random source. + */ + randomBytes(length: number): Uint8Array; +}; + +/** + * Encode string to UTF-8 bytes. + * + * **Note:** Strings with lone surrogates are rejected (as CryptoJS `Utf8.parse` did through `encodeURIComponent`) + * instead of being silently replaced with `U+FFFD` by `TextEncoder`. + * + * @param string - Source string. + * + * @returns UTF-8 bytes. + * + * @throws URIError if `string` contains lone surrogates. + * + * @internal + */ +export const encodeUtf8 = (string: string): Uint8Array => { + for (let i = 0; i < string.length; i++) { + const code = string.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff) { + const next = i + 1 < string.length ? string.charCodeAt(i + 1) : 0; + if (next < 0xdc00 || next > 0xdfff) throw new URIError('URI malformed'); + i++; + } else if (code >= 0xdc00 && code <= 0xdfff) throw new URIError('URI malformed'); + } + + return new TextEncoder().encode(string); +}; + +/** + * Check whether bytes are well-formed UTF-8 (Unicode Table 3-7). + * + * Rejects the same sequences as `decodeURIComponent` (used by CryptoJS `Utf8.stringify`): invalid lead and + * continuation bytes, truncated, overlong, surrogate (`U+D800`–`U+DFFF`) and out of range (> `U+10FFFF`) sequences. + * + * **Note:** Bytes are validated (rather than decoded `U+FFFD` characters) because `U+FFFD` can be legitimate input. + * + * @param bytes - Bytes which should be validated. + * + * @returns `true` if `bytes` are well-formed UTF-8. + * + * @internal + */ +export const isWellFormedUtf8 = (bytes: Uint8Array): boolean => { + const length = bytes.length; + let i = 0; + + while (i < length) { + const lead = bytes[i]; + if (lead <= 0x7f) { + i++; + continue; + } + + let count: number; + let min = 0x80; + let max = 0xbf; + if (lead >= 0xc2 && lead <= 0xdf) count = 1; + else if (lead >= 0xe0 && lead <= 0xef) { + count = 2; + if (lead === 0xe0) min = 0xa0; + else if (lead === 0xed) max = 0x9f; + } else if (lead >= 0xf0 && lead <= 0xf4) { + count = 3; + if (lead === 0xf0) min = 0x90; + else if (lead === 0xf4) max = 0x8f; + } else return false; + + // Truncated sequence. + if (i + count >= length) return false; + if (bytes[i + 1] < min || bytes[i + 1] > max) return false; + for (let j = 2; j <= count; j++) if (bytes[i + j] < 0x80 || bytes[i + j] > 0xbf) return false; + + i += count + 1; + } + + return true; +}; + +/** + * Decode UTF-8 bytes to string. + * + * Preserves CryptoJS `Utf8.stringify` contract: + * - malformed UTF-8 is rejected (React Native `TextDecoder` polyfill doesn't support `fatal` option, so bytes + * validated with {@link isWellFormedUtf8}); + * - leading BOM is preserved (native `TextDecoder` strips it by default, the polyfill keeps it). + * + * @param bytes - UTF-8 bytes. + * + * @returns Decoded string. + * + * @throws Error if `bytes` aren't well-formed UTF-8. + * + * @internal + */ +export const decodeUtf8 = (bytes: Uint8Array): string => { + if (!isWellFormedUtf8(bytes)) throw new Error('Malformed UTF-8 data'); + + const string = new TextDecoder().decode(bytes); + const hasBOM = bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf; + + return hasBOM && string.charCodeAt(0) !== 0xfeff ? `${string}` : string; +}; + +/** + * Remove block cipher padding leniently. + * + * Mirrors CryptoJS `Pkcs7.unpad`: strips the number of bytes stored in the last byte without validating padding + * bytes (so data padded with ANSI X.923 or ISO 10126 schemes still decrypts as before). + * + * @param bytes - Decrypted bytes with padding. + * + * @returns Bytes without padding (empty if padding length exceeds data length). + * + * @internal + */ +export const unpadLegacy = (bytes: Uint8Array): Uint8Array => { + const padding = bytes.length ? bytes[bytes.length - 1] : 0; + return padding > bytes.length ? new Uint8Array(0) : bytes.subarray(0, bytes.length - padding); +}; + +/** + * Convert bytes to lowercase hex string. + * + * @param bytes - Source bytes. + * + * @returns Hex string. + * + * @internal + */ +export const bytesToHex = (bytes: Uint8Array): string => + Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); + +/** + * Convert hex string to bytes. + * + * @param hex - Hex string. + * + * @returns Decoded bytes. + * + * @internal + */ +export const hexToBytes = (hex: string): Uint8Array => + Uint8Array.from(hex.match(/.{1,2}/g) ?? [], (byte) => parseInt(byte, 16)); + +/** + * Concatenate two bytes arrays. + * + * @param a - First bytes array. + * @param b - Second bytes array. + * + * @returns Concatenated bytes. + * + * @internal + */ +export const concatBytes = (a: Uint8Array, b: Uint8Array): Uint8Array => { + const result = new Uint8Array(a.length + b.length); + result.set(a); + result.set(b, a.length); + return result; +}; + +/** + * Copy bytes into standalone `ArrayBuffer`. + * + * **Important:** Primitives may return views into larger buffers (noble subarrays, Node.js `Buffer` pool), so the + * underlying `.buffer` must never be used directly. + * + * @param bytes - Source bytes (possibly a view). + * + * @returns `ArrayBuffer` with exactly `bytes` content. + * + * @internal + */ +export const toArrayBuffer = (bytes: Uint8Array): ArrayBuffer => + bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer; diff --git a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts index 7fc3720f5..30625c9c4 100644 --- a/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts +++ b/src/crypto/modules/NodeCryptoModule/legacyCryptor.ts @@ -7,7 +7,7 @@ import PubNubFile, { PubNubFileParameters } from '../../../file/modules/node'; import { CryptorConfiguration } from '../../../core/interfaces/crypto-module'; import { LoggerManager } from '../../../core/components/logger-manager'; -import Crypto from '../../../core/components/cryptography/index'; +import Crypto from '../../../core/components/cryptography/node'; import { PubNubFileConstructor } from '../../../core/types/file'; import { encode } from '../../../core/components/base64_codec'; import { PubNubError } from '../../../errors/pubnub-error'; diff --git a/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts b/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts index ebd38a743..15e1d0b61 100644 --- a/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts +++ b/src/crypto/modules/WebCryptoModule/aesCbcCryptor.ts @@ -2,8 +2,15 @@ * AES-CBC cryptor module. */ -import cryptoJS from '../../../core/components/cryptography/hmac-sha256'; -import { decode } from '../../../core/components/base64_codec'; +import { cbc } from '@noble/ciphers/aes.js'; +import { sha256 } from '@noble/hashes/sha2.js'; + +import { + encodeUtf8, + isWellFormedUtf8, + toArrayBuffer, + unpadLegacy, +} from '../../../core/components/cryptography/primitives'; import { ICryptor, EncryptedDataType } from './ICryptor'; /** @@ -32,15 +39,14 @@ export default class AesCbcCryptor implements ICryptor { */ cipherKey: string; - /* eslint-disable @typescript-eslint/no-explicit-any */ - encryptedKey: any; - /* eslint-disable @typescript-eslint/no-explicit-any */ - CryptoJS: any; + /** + * SHA-256 digest of the cipher key (AES-256 key). + */ + encryptedKey: Uint8Array; constructor({ cipherKey }: { cipherKey: string }) { this.cipherKey = cipherKey; - this.CryptoJS = cryptoJS; - this.encryptedKey = this.CryptoJS.SHA256(cipherKey); + this.encryptedKey = sha256(encodeUtf8(cipherKey)); } // -------------------------------------------------------- @@ -52,16 +58,9 @@ export default class AesCbcCryptor implements ICryptor { const stringData = typeof data === 'string' ? data : AesCbcCryptor.decoder.decode(data); if (stringData.length === 0) throw new Error('encryption error. empty content'); const abIv = this.getIv(); + const plaintext = typeof data === 'string' ? encodeUtf8(data) : new Uint8Array(data); - return { - metadata: abIv, - data: decode( - this.CryptoJS.AES.encrypt(data, this.encryptedKey, { - iv: this.bufferToWordArray(abIv), - mode: this.CryptoJS.mode.CBC, - }).ciphertext.toString(this.CryptoJS.enc.Base64), - ), - }; + return { metadata: abIv, data: toArrayBuffer(cbc(this.encryptedKey, abIv).encrypt(plaintext)) }; } async encryptFileData(data: ArrayBuffer): Promise { @@ -83,15 +82,14 @@ export default class AesCbcCryptor implements ICryptor { if (typeof encryptedData.data === 'string') throw new Error('Decryption error: data for decryption should be ArrayBuffed.'); - const iv = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.metadata!)); - const data = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.data)); + const iv = new Uint8Array(encryptedData.metadata!); + const data = new Uint8Array(encryptedData.data); - return AesCbcCryptor.encoder.encode( - this.CryptoJS.AES.decrypt({ ciphertext: data }, this.encryptedKey, { - iv, - mode: this.CryptoJS.mode.CBC, - }).toString(this.CryptoJS.enc.Utf8), - ).buffer; + // Padding removed leniently and decrypted data must be well-formed UTF-8 (CryptoJS-compatible). + const plaintext = unpadLegacy(cbc(this.encryptedKey, iv, { disablePadding: true }).decrypt(data)); + if (!isWellFormedUtf8(plaintext)) throw new Error('Malformed UTF-8 data'); + + return toArrayBuffer(plaintext); } async decryptFileData(encryptedData: EncryptedDataType): Promise { @@ -142,24 +140,6 @@ export default class AesCbcCryptor implements ICryptor { return crypto.subtle.importKey('raw', abHash, this.algo, true, ['encrypt', 'decrypt']); } - /** - * Convert bytes array to words array. - * - * @param b - Bytes array (buffer) which should be converted. - * - * @returns Word sized array. - */ - private bufferToWordArray(b: string | any[] | Uint8Array | Uint8ClampedArray) { - const wa: number[] = []; - let i; - - for (i = 0; i < b.length; i += 1) { - wa[(i / 4) | 0] |= b[i] << (24 - 8 * i); - } - - return this.CryptoJS.lib.WordArray.create(wa, b.length); - } - /** * Serialize cryptor information to string. * diff --git a/src/node/index.ts b/src/node/index.ts index 44c1bfe6f..6ae063e1d 100755 --- a/src/node/index.ts +++ b/src/node/index.ts @@ -18,7 +18,7 @@ import { PubNubMiddleware } from '../transport/middleware'; import { PubNubFileConstructor } from '../core/types/file'; import { decode } from '../core/components/base64_codec'; import NodeCryptography from '../crypto/modules/node'; -import Crypto from '../core/components/cryptography'; +import Crypto from '../core/components/cryptography/node'; import { PubNubError } from '../errors/pubnub-error'; import { PubNubCore } from '../core/pubnub-common'; import Cbor from '../cbor/common'; diff --git a/test/unit/common.test.ts b/test/unit/common.test.ts index 63bd5f567..cf8142ed0 100644 --- a/test/unit/common.test.ts +++ b/test/unit/common.test.ts @@ -3,7 +3,7 @@ import lilUUID from 'lil-uuid'; import assert from 'assert'; -import CryptoJS from '../../src/core/components/cryptography/hmac-sha256'; +import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto'; import { Payload } from '../../src/core/types/api'; import PubNub from '../../src/node/index'; @@ -146,17 +146,17 @@ describe('#core / mounting point', () => { }); it('supports custom encryption/decryption', () => { + const customKey = createHash('sha256').update('customKey').digest(); let customEncrypt = (data: Payload) => { - // @ts-expect-error Bundled library without types. - let cipher = CryptoJS.AES.encrypt(JSON.stringify(data), 'customKey'); - return cipher.toString(); + const iv = randomBytes(16); + const cipher = createCipheriv('aes-256-cbc', customKey, iv); + return Buffer.concat([iv, cipher.update(JSON.stringify(data)), cipher.final()]).toString('base64'); }; let customDecrypt = (data: Payload) => { - // @ts-expect-error Bundled library without types. - let bytes = CryptoJS.AES.decrypt(data, 'customKey'); - // @ts-expect-error Bundled library without types. - return JSON.parse(bytes.toString(CryptoJS.enc.Utf8)); + const bytes = Buffer.from(data as string, 'base64'); + const decipher = createDecipheriv('aes-256-cbc', customKey, bytes.subarray(0, 16)); + return JSON.parse(Buffer.concat([decipher.update(bytes.subarray(16)), decipher.final()]).toString('utf8')); }; let pn = new PubNub({ diff --git a/test/unit/legacy_crypto_compat.test.ts b/test/unit/legacy_crypto_compat.test.ts new file mode 100644 index 000000000..4f44a902f --- /dev/null +++ b/test/unit/legacy_crypto_compat.test.ts @@ -0,0 +1,93 @@ +import assert from 'assert'; +import { createCipheriv, createHash, randomBytes } from 'crypto'; + +import WebAesCbcCryptor from '../../src/crypto/modules/WebCryptoModule/aesCbcCryptor'; +import NobleCrypto from '../../src/core/components/cryptography/index'; +import NodeCrypto from '../../src/core/components/cryptography/node'; + +/** + * Expected results below were captured from the previously bundled CryptoJS 3.1.2 implementation, so the noble / + * node:crypto replacements must not turn data rejected before into successful (altered) payloads, or vice versa. + */ + +const CIPHER_KEY = 'k'; +const STATIC_IV = Buffer.from('0123456789012345'); +const LEGACY_KEY = Buffer.from(createHash('sha256').update(CIPHER_KEY).digest('hex').slice(0, 32)); +const ACRH_KEY = createHash('sha256').update(CIPHER_KEY).digest(); + +const json = (prefix: string, bytes: number[], suffix = '"}') => + Buffer.concat([Buffer.from(prefix), Buffer.from(bytes), Buffer.from(suffix)]); + +function pad(data: Buffer, scheme: 'pkcs7' | 'x923' | 'iso10126') { + const length = 16 - (data.length % 16); + if (scheme === 'pkcs7') return Buffer.concat([data, Buffer.alloc(length, length)]); + const filler = scheme === 'x923' ? Buffer.alloc(length - 1, 0) : randomBytes(length - 1); + return Buffer.concat([data, filler, Buffer.from([length])]); +} + +function encrypt(key: Buffer, iv: Buffer, data: Buffer, scheme: 'pkcs7' | 'x923' | 'iso10126' = 'pkcs7') { + const cipher = createCipheriv('aes-256-cbc', key, iv); + cipher.setAutoPadding(false); + return Buffer.concat([cipher.update(pad(data, scheme)), cipher.final()]); +} + +const legacyImplementations = { + 'noble (web / React Native)': (cipherKey = CIPHER_KEY) => new NobleCrypto({ cipherKey, useRandomIVs: false }), + 'node:crypto (Node.js)': (cipherKey = CIPHER_KEY) => new NodeCrypto({ cipherKey, useRandomIVs: false }), +}; + +const REPLACEMENT_CHARACTER = String.fromCharCode(0xfffd); +const BOM = String.fromCharCode(0xfeff); + +describe('legacy crypto CryptoJS compatibility', () => { + it('rejects malformed UTF-8 and leading BOM after decryption, keeps legitimate U+FFFD', () => { + // [label, plaintext bytes, legacy `decrypt` result, whether AES-CBC cryptor `decrypt` throws] + const cases: [string, Buffer, unknown, boolean][] = [ + ['invalid byte', json('{"a":"', [0xff]), null, true], + ['overlong sequence', json('{"a":"', [0xc0, 0xaf]), null, true], + ['encoded surrogate', json('{"a":"', [0xed, 0xa0, 0x80]), null, true], + ['truncated sequence', json('{"a":"', [0xe4, 0xb8]), null, true], + ['code point above U+10FFFF', json('{"a":"', [0xf4, 0x90, 0x80, 0x80]), null, true], + ['leading BOM', json('', [0xef, 0xbb, 0xbf], '{"a":1}'), null, false], + ['legitimate U+FFFD', json('{"a":"', [0xef, 0xbf, 0xbd]), { a: REPLACEMENT_CHARACTER }, false], + ['BOM inside string', json('{"a":"', [0xef, 0xbb, 0xbf]), { a: BOM }, false], + ]; + + for (const [name, create] of Object.entries(legacyImplementations)) { + const crypto = create(); + for (const [label, plaintext, expected] of cases) { + const ciphertext = encrypt(LEGACY_KEY, STATIC_IV, plaintext).toString('base64'); + assert.deepStrictEqual(crypto.decrypt(ciphertext), expected, `${name}: ${label}`); + } + } + + // Web AES-CBC cryptor throws on malformed UTF-8 (as CryptoJS did) and returns the exact bytes otherwise. + const cryptor = new WebAesCbcCryptor({ cipherKey: CIPHER_KEY }); + for (const [label, plaintext, , throws] of cases) { + const iv = randomBytes(16); + const data = encrypt(ACRH_KEY, iv, plaintext); + const decrypt = () => cryptor.decrypt({ metadata: new Uint8Array(iv).buffer, data: new Uint8Array(data).buffer }); + if (throws) assert.throws(decrypt, /Malformed UTF-8 data/, `AesCbcCryptor: ${label}`); + else assert.deepStrictEqual(Buffer.from(decrypt()), plaintext, `AesCbcCryptor: ${label}`); + } + }); + + it('accepts non-PKCS#7 padding on decryption and rejects lone surrogates on encryption', () => { + for (const [name, create] of Object.entries(legacyImplementations)) { + const crypto = create(); + for (const scheme of ['x923', 'iso10126'] as const) { + const ciphertext = encrypt(LEGACY_KEY, STATIC_IV, Buffer.from('{"a":1}'), scheme).toString('base64'); + assert.deepStrictEqual(crypto.decrypt(ciphertext), { a: 1 }, `${name}: ${scheme} padding`); + } + + assert.throws(() => crypto.encrypt('{"a":"\uD800"}'), URIError, `${name}: lone surrogate in data`); + assert.throws(() => create('\uDC00k').encrypt('{}'), URIError, `${name}: lone surrogate in cipher key`); + + // Well-formed input still produces the known static-IV vector. + assert.strictEqual(crypto.encrypt(JSON.stringify({ hi: 'there' }), 'customKey'), 'TejX6F2JNqH/gIiGHWN4Cw=='); + } + + assert.throws(() => new WebAesCbcCryptor({ cipherKey: 'k' }).encrypt('{"a":"\uD800"}'), URIError); + assert.throws(() => new WebAesCbcCryptor({ cipherKey: '\uDC00k' }), URIError); + }); +});