@afterrealism/dendri-client 2.3.7 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -21
- package/README.md +61 -59
- package/dist/{chunk-MJW5M75V.js → chunk-MBMSG4EC.js} +200 -14
- package/dist/chunk-MBMSG4EC.js.map +1 -0
- package/dist/dendri.browser.global.js +166 -8
- package/dist/dendri.browser.global.js.map +1 -1
- package/dist/dendri.cjs +199 -12
- package/dist/dendri.cjs.map +1 -1
- package/dist/dendri.d.cts +2 -2
- package/dist/dendri.d.ts +2 -2
- package/dist/dendri.js +3 -3
- package/dist/dendri.js.map +1 -1
- package/dist/dendri.min.global.js +13 -13
- package/dist/dendri.min.global.js.map +1 -1
- package/dist/serializer.msgpack.cjs +3 -3
- package/dist/serializer.msgpack.cjs.map +1 -1
- package/dist/serializer.msgpack.d.cts +17 -4
- package/dist/serializer.msgpack.d.ts +17 -4
- package/dist/serializer.msgpack.js +2 -2
- package/dist/serializer.msgpack.js.map +1 -1
- package/dist/{store-RTivRmUW.d.cts → store-DVE0ih44.d.cts} +24 -5
- package/dist/{store-RTivRmUW.d.ts → store-DVE0ih44.d.ts} +24 -5
- package/dist/store.cjs +189 -11
- package/dist/store.cjs.map +1 -1
- package/dist/store.d.cts +1 -1
- package/dist/store.d.ts +1 -1
- package/dist/store.js +1 -1
- package/package.json +7 -2
- package/dist/chunk-MJW5M75V.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/utils/int.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/utils/utf8.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/ExtData.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/DecodeError.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/timestamp.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/ExtensionCodec.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/utils/typedArrays.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/Encoder.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/utils/prettyByte.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/CachedKeyDecoder.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/Decoder.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/decode.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/utils/stream.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/decodeAsync.ts","../src/logger.ts","../src/dendriError.ts","../src/baseconnection.ts","../src/negotiator.ts","../src/utils/randomToken.ts","../src/dataconnection/DataConnection.ts","../src/dataconnection/StreamConnection/StreamConnection.ts","../src/dataconnection/StreamConnection/MsgPack.ts"],"sourcesContent":["'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","// Integer Utility\n\nexport const UINT32_MAX = 0xffff_ffff;\n\n// DataView extension to handle int64 / uint64,\n// where the actual range is 53-bits integer (a.k.a. safe integer)\n\nexport function setUint64(view: DataView, offset: number, value: number): void {\n const high = value / 0x1_0000_0000;\n const low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\n\nexport function setInt64(view: DataView, offset: number, value: number): void {\n const high = Math.floor(value / 0x1_0000_0000);\n const low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\n\nexport function getInt64(view: DataView, offset: number): number {\n const high = view.getInt32(offset);\n const low = view.getUint32(offset + 4);\n return high * 0x1_0000_0000 + low;\n}\n\nexport function getUint64(view: DataView, offset: number): number {\n const high = view.getUint32(offset);\n const low = view.getUint32(offset + 4);\n return high * 0x1_0000_0000 + low;\n}\n","/* eslint-disable @typescript-eslint/no-unnecessary-condition */\nimport { UINT32_MAX } from \"./int\";\n\nconst TEXT_ENCODING_AVAILABLE =\n (typeof process === \"undefined\" || process?.env?.[\"TEXT_ENCODING\"] !== \"never\") &&\n typeof TextEncoder !== \"undefined\" &&\n typeof TextDecoder !== \"undefined\";\n\nexport function utf8Count(str: string): number {\n const strLength = str.length;\n\n let byteLength = 0;\n let pos = 0;\n while (pos < strLength) {\n let value = str.charCodeAt(pos++);\n\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n byteLength++;\n continue;\n } else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n byteLength += 2;\n } else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n const extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n byteLength += 3;\n } else {\n // 4-byte\n byteLength += 4;\n }\n }\n }\n return byteLength;\n}\n\nexport function utf8EncodeJs(str: string, output: Uint8Array, outputOffset: number): void {\n const strLength = str.length;\n let offset = outputOffset;\n let pos = 0;\n while (pos < strLength) {\n let value = str.charCodeAt(pos++);\n\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n output[offset++] = value;\n continue;\n } else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n output[offset++] = ((value >> 6) & 0x1f) | 0xc0;\n } else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n const extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n output[offset++] = ((value >> 12) & 0x0f) | 0xe0;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n } else {\n // 4-byte\n output[offset++] = ((value >> 18) & 0x07) | 0xf0;\n output[offset++] = ((value >> 12) & 0x3f) | 0x80;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n }\n }\n\n output[offset++] = (value & 0x3f) | 0x80;\n }\n}\n\nconst sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;\nexport const TEXT_ENCODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE\n ? UINT32_MAX\n : typeof process !== \"undefined\" && process?.env?.[\"TEXT_ENCODING\"] !== \"force\"\n ? 200\n : 0;\n\nfunction utf8EncodeTEencode(str: string, output: Uint8Array, outputOffset: number): void {\n output.set(sharedTextEncoder!.encode(str), outputOffset);\n}\n\nfunction utf8EncodeTEencodeInto(str: string, output: Uint8Array, outputOffset: number): void {\n sharedTextEncoder!.encodeInto(str, output.subarray(outputOffset));\n}\n\nexport const utf8EncodeTE = sharedTextEncoder?.encodeInto ? utf8EncodeTEencodeInto : utf8EncodeTEencode;\n\nconst CHUNK_SIZE = 0x1_000;\n\nexport function utf8DecodeJs(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n let offset = inputOffset;\n const end = offset + byteLength;\n\n const units: Array<number> = [];\n let result = \"\";\n while (offset < end) {\n const byte1 = bytes[offset++]!;\n if ((byte1 & 0x80) === 0) {\n // 1 byte\n units.push(byte1);\n } else if ((byte1 & 0xe0) === 0xc0) {\n // 2 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n units.push(((byte1 & 0x1f) << 6) | byte2);\n } else if ((byte1 & 0xf0) === 0xe0) {\n // 3 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n const byte3 = bytes[offset++]! & 0x3f;\n units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);\n } else if ((byte1 & 0xf8) === 0xf0) {\n // 4 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n const byte3 = bytes[offset++]! & 0x3f;\n const byte4 = bytes[offset++]! & 0x3f;\n let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\n if (unit > 0xffff) {\n unit -= 0x10000;\n units.push(((unit >>> 10) & 0x3ff) | 0xd800);\n unit = 0xdc00 | (unit & 0x3ff);\n }\n units.push(unit);\n } else {\n units.push(byte1);\n }\n\n if (units.length >= CHUNK_SIZE) {\n result += String.fromCharCode(...units);\n units.length = 0;\n }\n }\n\n if (units.length > 0) {\n result += String.fromCharCode(...units);\n }\n\n return result;\n}\n\nconst sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;\nexport const TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE\n ? UINT32_MAX\n : typeof process !== \"undefined\" && process?.env?.[\"TEXT_DECODER\"] !== \"force\"\n ? 200\n : 0;\n\nexport function utf8DecodeTD(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n const stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);\n return sharedTextDecoder!.decode(stringBytes);\n}\n","/**\n * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.\n */\nexport class ExtData {\n constructor(readonly type: number, readonly data: Uint8Array) {}\n}\n","export class DecodeError extends Error {\n constructor(message: string) {\n super(message);\n\n // fix the prototype chain in a cross-platform way\n const proto: typeof DecodeError.prototype = Object.create(DecodeError.prototype);\n Object.setPrototypeOf(this, proto);\n\n Object.defineProperty(this, \"name\", {\n configurable: true,\n enumerable: false,\n value: DecodeError.name,\n });\n }\n}\n","// https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type\nimport { DecodeError } from \"./DecodeError\";\nimport { getInt64, setInt64 } from \"./utils/int\";\n\nexport const EXT_TIMESTAMP = -1;\n\nexport type TimeSpec = {\n sec: number;\n nsec: number;\n};\n\nconst TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int\nconst TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int\n\nexport function encodeTimeSpecToTimestamp({ sec, nsec }: TimeSpec): Uint8Array {\n if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {\n // Here sec >= 0 && nsec >= 0\n if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {\n // timestamp 32 = { sec32 (unsigned) }\n const rv = new Uint8Array(4);\n const view = new DataView(rv.buffer);\n view.setUint32(0, sec);\n return rv;\n } else {\n // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }\n const secHigh = sec / 0x100000000;\n const secLow = sec & 0xffffffff;\n const rv = new Uint8Array(8);\n const view = new DataView(rv.buffer);\n // nsec30 | secHigh2\n view.setUint32(0, (nsec << 2) | (secHigh & 0x3));\n // secLow32\n view.setUint32(4, secLow);\n return rv;\n }\n } else {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n const rv = new Uint8Array(12);\n const view = new DataView(rv.buffer);\n view.setUint32(0, nsec);\n setInt64(view, 4, sec);\n return rv;\n }\n}\n\nexport function encodeDateToTimeSpec(date: Date): TimeSpec {\n const msec = date.getTime();\n const sec = Math.floor(msec / 1e3);\n const nsec = (msec - sec * 1e3) * 1e6;\n\n // Normalizes { sec, nsec } to ensure nsec is unsigned.\n const nsecInSec = Math.floor(nsec / 1e9);\n return {\n sec: sec + nsecInSec,\n nsec: nsec - nsecInSec * 1e9,\n };\n}\n\nexport function encodeTimestampExtension(object: unknown): Uint8Array | null {\n if (object instanceof Date) {\n const timeSpec = encodeDateToTimeSpec(object);\n return encodeTimeSpecToTimestamp(timeSpec);\n } else {\n return null;\n }\n}\n\nexport function decodeTimestampToTimeSpec(data: Uint8Array): TimeSpec {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n // data may be 32, 64, or 96 bits\n switch (data.byteLength) {\n case 4: {\n // timestamp 32 = { sec32 }\n const sec = view.getUint32(0);\n const nsec = 0;\n return { sec, nsec };\n }\n case 8: {\n // timestamp 64 = { nsec30, sec34 }\n const nsec30AndSecHigh2 = view.getUint32(0);\n const secLow32 = view.getUint32(4);\n const sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;\n const nsec = nsec30AndSecHigh2 >>> 2;\n return { sec, nsec };\n }\n case 12: {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n\n const sec = getInt64(view, 4);\n const nsec = view.getUint32(0);\n return { sec, nsec };\n }\n default:\n throw new DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);\n }\n}\n\nexport function decodeTimestampExtension(data: Uint8Array): Date {\n const timeSpec = decodeTimestampToTimeSpec(data);\n return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);\n}\n\nexport const timestampExtension = {\n type: EXT_TIMESTAMP,\n encode: encodeTimestampExtension,\n decode: decodeTimestampExtension,\n};\n","// ExtensionCodec to handle MessagePack extensions\n\nimport { ExtData } from \"./ExtData\";\nimport { timestampExtension } from \"./timestamp\";\n\nexport type ExtensionDecoderType<ContextType> = (\n data: Uint8Array,\n extensionType: number,\n context: ContextType,\n) => unknown;\n\nexport type ExtensionEncoderType<ContextType> = (input: unknown, context: ContextType) => Uint8Array | null;\n\n// immutable interface to ExtensionCodec\nexport type ExtensionCodecType<ContextType> = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __brand?: ContextType;\n tryToEncode(object: unknown, context: ContextType): ExtData | null;\n decode(data: Uint8Array, extType: number, context: ContextType): unknown;\n};\n\nexport class ExtensionCodec<ContextType = undefined> implements ExtensionCodecType<ContextType> {\n public static readonly defaultCodec: ExtensionCodecType<undefined> = new ExtensionCodec();\n\n // ensures ExtensionCodecType<X> matches ExtensionCodec<X>\n // this will make type errors a lot more clear\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __brand?: ContextType;\n\n // built-in extensions\n private readonly builtInEncoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n private readonly builtInDecoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n // custom extensions\n private readonly encoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n private readonly decoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n public constructor() {\n this.register(timestampExtension);\n }\n\n public register({\n type,\n encode,\n decode,\n }: {\n type: number;\n encode: ExtensionEncoderType<ContextType>;\n decode: ExtensionDecoderType<ContextType>;\n }): void {\n if (type >= 0) {\n // custom extensions\n this.encoders[type] = encode;\n this.decoders[type] = decode;\n } else {\n // built-in extensions\n const index = 1 + type;\n this.builtInEncoders[index] = encode;\n this.builtInDecoders[index] = decode;\n }\n }\n\n public tryToEncode(object: unknown, context: ContextType): ExtData | null {\n // built-in extensions\n for (let i = 0; i < this.builtInEncoders.length; i++) {\n const encodeExt = this.builtInEncoders[i];\n if (encodeExt != null) {\n const data = encodeExt(object, context);\n if (data != null) {\n const type = -1 - i;\n return new ExtData(type, data);\n }\n }\n }\n\n // custom extensions\n for (let i = 0; i < this.encoders.length; i++) {\n const encodeExt = this.encoders[i];\n if (encodeExt != null) {\n const data = encodeExt(object, context);\n if (data != null) {\n const type = i;\n return new ExtData(type, data);\n }\n }\n }\n\n if (object instanceof ExtData) {\n // to keep ExtData as is\n return object;\n }\n return null;\n }\n\n public decode(data: Uint8Array, type: number, context: ContextType): unknown {\n const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];\n if (decodeExt) {\n return decodeExt(data, type, context);\n } else {\n // decode() does not fail, returns ExtData instead.\n return new ExtData(type, data);\n }\n }\n}\n","export function ensureUint8Array(buffer: ArrayLike<number> | Uint8Array | ArrayBufferView | ArrayBuffer): Uint8Array {\n if (buffer instanceof Uint8Array) {\n return buffer;\n } else if (ArrayBuffer.isView(buffer)) {\n return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n } else if (buffer instanceof ArrayBuffer) {\n return new Uint8Array(buffer);\n } else {\n // ArrayLike<number>\n return Uint8Array.from(buffer);\n }\n}\n\nexport function createDataView(buffer: ArrayLike<number> | ArrayBufferView | ArrayBuffer): DataView {\n if (buffer instanceof ArrayBuffer) {\n return new DataView(buffer);\n }\n\n const bufferView = ensureUint8Array(buffer);\n return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);\n}\n","import { utf8EncodeJs, utf8Count, TEXT_ENCODER_THRESHOLD, utf8EncodeTE } from \"./utils/utf8\";\nimport { ExtensionCodec, ExtensionCodecType } from \"./ExtensionCodec\";\nimport { setInt64, setUint64 } from \"./utils/int\";\nimport { ensureUint8Array } from \"./utils/typedArrays\";\nimport type { ExtData } from \"./ExtData\";\n\nexport const DEFAULT_MAX_DEPTH = 100;\nexport const DEFAULT_INITIAL_BUFFER_SIZE = 2048;\n\nexport class Encoder<ContextType = undefined> {\n private pos = 0;\n private view = new DataView(new ArrayBuffer(this.initialBufferSize));\n private bytes = new Uint8Array(this.view.buffer);\n\n public constructor(\n private readonly extensionCodec: ExtensionCodecType<ContextType> = ExtensionCodec.defaultCodec as any,\n private readonly context: ContextType = undefined as any,\n private readonly maxDepth = DEFAULT_MAX_DEPTH,\n private readonly initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE,\n private readonly sortKeys = false,\n private readonly forceFloat32 = false,\n private readonly ignoreUndefined = false,\n private readonly forceIntegerToFloat = false,\n ) {}\n\n private reinitializeState() {\n this.pos = 0;\n }\n\n /**\n * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.\n *\n * @returns Encodes the object and returns a shared reference the encoder's internal buffer.\n */\n public encodeSharedRef(object: unknown): Uint8Array {\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.subarray(0, this.pos);\n }\n\n /**\n * @returns Encodes the object and returns a copy of the encoder's internal buffer.\n */\n public encode(object: unknown): Uint8Array {\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.slice(0, this.pos);\n }\n\n private doEncode(object: unknown, depth: number): void {\n if (depth > this.maxDepth) {\n throw new Error(`Too deep objects in depth ${depth}`);\n }\n\n if (object == null) {\n this.encodeNil();\n } else if (typeof object === \"boolean\") {\n this.encodeBoolean(object);\n } else if (typeof object === \"number\") {\n this.encodeNumber(object);\n } else if (typeof object === \"string\") {\n this.encodeString(object);\n } else {\n this.encodeObject(object, depth);\n }\n }\n\n private ensureBufferSizeToWrite(sizeToWrite: number) {\n const requiredSize = this.pos + sizeToWrite;\n\n if (this.view.byteLength < requiredSize) {\n this.resizeBuffer(requiredSize * 2);\n }\n }\n\n private resizeBuffer(newSize: number) {\n const newBuffer = new ArrayBuffer(newSize);\n const newBytes = new Uint8Array(newBuffer);\n const newView = new DataView(newBuffer);\n\n newBytes.set(this.bytes);\n\n this.view = newView;\n this.bytes = newBytes;\n }\n\n private encodeNil() {\n this.writeU8(0xc0);\n }\n\n private encodeBoolean(object: boolean) {\n if (object === false) {\n this.writeU8(0xc2);\n } else {\n this.writeU8(0xc3);\n }\n }\n private encodeNumber(object: number) {\n if (Number.isSafeInteger(object) && !this.forceIntegerToFloat) {\n if (object >= 0) {\n if (object < 0x80) {\n // positive fixint\n this.writeU8(object);\n } else if (object < 0x100) {\n // uint 8\n this.writeU8(0xcc);\n this.writeU8(object);\n } else if (object < 0x10000) {\n // uint 16\n this.writeU8(0xcd);\n this.writeU16(object);\n } else if (object < 0x100000000) {\n // uint 32\n this.writeU8(0xce);\n this.writeU32(object);\n } else {\n // uint 64\n this.writeU8(0xcf);\n this.writeU64(object);\n }\n } else {\n if (object >= -0x20) {\n // negative fixint\n this.writeU8(0xe0 | (object + 0x20));\n } else if (object >= -0x80) {\n // int 8\n this.writeU8(0xd0);\n this.writeI8(object);\n } else if (object >= -0x8000) {\n // int 16\n this.writeU8(0xd1);\n this.writeI16(object);\n } else if (object >= -0x80000000) {\n // int 32\n this.writeU8(0xd2);\n this.writeI32(object);\n } else {\n // int 64\n this.writeU8(0xd3);\n this.writeI64(object);\n }\n }\n } else {\n // non-integer numbers\n if (this.forceFloat32) {\n // float 32\n this.writeU8(0xca);\n this.writeF32(object);\n } else {\n // float 64\n this.writeU8(0xcb);\n this.writeF64(object);\n }\n }\n }\n\n private writeStringHeader(byteLength: number) {\n if (byteLength < 32) {\n // fixstr\n this.writeU8(0xa0 + byteLength);\n } else if (byteLength < 0x100) {\n // str 8\n this.writeU8(0xd9);\n this.writeU8(byteLength);\n } else if (byteLength < 0x10000) {\n // str 16\n this.writeU8(0xda);\n this.writeU16(byteLength);\n } else if (byteLength < 0x100000000) {\n // str 32\n this.writeU8(0xdb);\n this.writeU32(byteLength);\n } else {\n throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);\n }\n }\n\n private encodeString(object: string) {\n const maxHeaderSize = 1 + 4;\n const strLength = object.length;\n\n if (strLength > TEXT_ENCODER_THRESHOLD) {\n const byteLength = utf8Count(object);\n this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n this.writeStringHeader(byteLength);\n utf8EncodeTE(object, this.bytes, this.pos);\n this.pos += byteLength;\n } else {\n const byteLength = utf8Count(object);\n this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n this.writeStringHeader(byteLength);\n utf8EncodeJs(object, this.bytes, this.pos);\n this.pos += byteLength;\n }\n }\n\n private encodeObject(object: unknown, depth: number) {\n // try to encode objects with custom codec first of non-primitives\n const ext = this.extensionCodec.tryToEncode(object, this.context);\n if (ext != null) {\n this.encodeExtension(ext);\n } else if (Array.isArray(object)) {\n this.encodeArray(object, depth);\n } else if (ArrayBuffer.isView(object)) {\n this.encodeBinary(object);\n } else if (typeof object === \"object\") {\n this.encodeMap(object as Record<string, unknown>, depth);\n } else {\n // symbol, function and other special object come here unless extensionCodec handles them.\n throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);\n }\n }\n\n private encodeBinary(object: ArrayBufferView) {\n const size = object.byteLength;\n if (size < 0x100) {\n // bin 8\n this.writeU8(0xc4);\n this.writeU8(size);\n } else if (size < 0x10000) {\n // bin 16\n this.writeU8(0xc5);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // bin 32\n this.writeU8(0xc6);\n this.writeU32(size);\n } else {\n throw new Error(`Too large binary: ${size}`);\n }\n const bytes = ensureUint8Array(object);\n this.writeU8a(bytes);\n }\n\n private encodeArray(object: Array<unknown>, depth: number) {\n const size = object.length;\n if (size < 16) {\n // fixarray\n this.writeU8(0x90 + size);\n } else if (size < 0x10000) {\n // array 16\n this.writeU8(0xdc);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // array 32\n this.writeU8(0xdd);\n this.writeU32(size);\n } else {\n throw new Error(`Too large array: ${size}`);\n }\n for (const item of object) {\n this.doEncode(item, depth + 1);\n }\n }\n\n private countWithoutUndefined(object: Record<string, unknown>, keys: ReadonlyArray<string>): number {\n let count = 0;\n\n for (const key of keys) {\n if (object[key] !== undefined) {\n count++;\n }\n }\n\n return count;\n }\n\n private encodeMap(object: Record<string, unknown>, depth: number) {\n const keys = Object.keys(object);\n if (this.sortKeys) {\n keys.sort();\n }\n\n const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;\n\n if (size < 16) {\n // fixmap\n this.writeU8(0x80 + size);\n } else if (size < 0x10000) {\n // map 16\n this.writeU8(0xde);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // map 32\n this.writeU8(0xdf);\n this.writeU32(size);\n } else {\n throw new Error(`Too large map object: ${size}`);\n }\n\n for (const key of keys) {\n const value = object[key];\n\n if (!(this.ignoreUndefined && value === undefined)) {\n this.encodeString(key);\n this.doEncode(value, depth + 1);\n }\n }\n }\n\n private encodeExtension(ext: ExtData) {\n const size = ext.data.length;\n if (size === 1) {\n // fixext 1\n this.writeU8(0xd4);\n } else if (size === 2) {\n // fixext 2\n this.writeU8(0xd5);\n } else if (size === 4) {\n // fixext 4\n this.writeU8(0xd6);\n } else if (size === 8) {\n // fixext 8\n this.writeU8(0xd7);\n } else if (size === 16) {\n // fixext 16\n this.writeU8(0xd8);\n } else if (size < 0x100) {\n // ext 8\n this.writeU8(0xc7);\n this.writeU8(size);\n } else if (size < 0x10000) {\n // ext 16\n this.writeU8(0xc8);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // ext 32\n this.writeU8(0xc9);\n this.writeU32(size);\n } else {\n throw new Error(`Too large extension object: ${size}`);\n }\n this.writeI8(ext.type);\n this.writeU8a(ext.data);\n }\n\n private writeU8(value: number) {\n this.ensureBufferSizeToWrite(1);\n\n this.view.setUint8(this.pos, value);\n this.pos++;\n }\n\n private writeU8a(values: ArrayLike<number>) {\n const size = values.length;\n this.ensureBufferSizeToWrite(size);\n\n this.bytes.set(values, this.pos);\n this.pos += size;\n }\n\n private writeI8(value: number) {\n this.ensureBufferSizeToWrite(1);\n\n this.view.setInt8(this.pos, value);\n this.pos++;\n }\n\n private writeU16(value: number) {\n this.ensureBufferSizeToWrite(2);\n\n this.view.setUint16(this.pos, value);\n this.pos += 2;\n }\n\n private writeI16(value: number) {\n this.ensureBufferSizeToWrite(2);\n\n this.view.setInt16(this.pos, value);\n this.pos += 2;\n }\n\n private writeU32(value: number) {\n this.ensureBufferSizeToWrite(4);\n\n this.view.setUint32(this.pos, value);\n this.pos += 4;\n }\n\n private writeI32(value: number) {\n this.ensureBufferSizeToWrite(4);\n\n this.view.setInt32(this.pos, value);\n this.pos += 4;\n }\n\n private writeF32(value: number) {\n this.ensureBufferSizeToWrite(4);\n this.view.setFloat32(this.pos, value);\n this.pos += 4;\n }\n\n private writeF64(value: number) {\n this.ensureBufferSizeToWrite(8);\n this.view.setFloat64(this.pos, value);\n this.pos += 8;\n }\n\n private writeU64(value: number) {\n this.ensureBufferSizeToWrite(8);\n\n setUint64(this.view, this.pos, value);\n this.pos += 8;\n }\n\n private writeI64(value: number) {\n this.ensureBufferSizeToWrite(8);\n\n setInt64(this.view, this.pos, value);\n this.pos += 8;\n }\n}\n","export function prettyByte(byte: number): string {\n return `${byte < 0 ? \"-\" : \"\"}0x${Math.abs(byte).toString(16).padStart(2, \"0\")}`;\n}\n","import { utf8DecodeJs } from \"./utils/utf8\";\n\nconst DEFAULT_MAX_KEY_LENGTH = 16;\nconst DEFAULT_MAX_LENGTH_PER_KEY = 16;\n\nexport interface KeyDecoder {\n canBeCached(byteLength: number): boolean;\n decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string;\n}\ninterface KeyCacheRecord {\n readonly bytes: Uint8Array;\n readonly str: string;\n}\n\nexport class CachedKeyDecoder implements KeyDecoder {\n hit = 0;\n miss = 0;\n private readonly caches: Array<Array<KeyCacheRecord>>;\n\n constructor(readonly maxKeyLength = DEFAULT_MAX_KEY_LENGTH, readonly maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {\n // avoid `new Array(N)`, which makes a sparse array,\n // because a sparse array is typically slower than a non-sparse array.\n this.caches = [];\n for (let i = 0; i < this.maxKeyLength; i++) {\n this.caches.push([]);\n }\n }\n\n public canBeCached(byteLength: number): boolean {\n return byteLength > 0 && byteLength <= this.maxKeyLength;\n }\n\n private find(bytes: Uint8Array, inputOffset: number, byteLength: number): string | null {\n const records = this.caches[byteLength - 1]!;\n\n FIND_CHUNK: for (const record of records) {\n const recordBytes = record.bytes;\n\n for (let j = 0; j < byteLength; j++) {\n if (recordBytes[j] !== bytes[inputOffset + j]) {\n continue FIND_CHUNK;\n }\n }\n return record.str;\n }\n return null;\n }\n\n private store(bytes: Uint8Array, value: string) {\n const records = this.caches[bytes.length - 1]!;\n const record: KeyCacheRecord = { bytes, str: value };\n\n if (records.length >= this.maxLengthPerKey) {\n // `records` are full!\n // Set `record` to an arbitrary position.\n records[(Math.random() * records.length) | 0] = record;\n } else {\n records.push(record);\n }\n }\n\n public decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n const cachedValue = this.find(bytes, inputOffset, byteLength);\n if (cachedValue != null) {\n this.hit++;\n return cachedValue;\n }\n this.miss++;\n\n const str = utf8DecodeJs(bytes, inputOffset, byteLength);\n // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.\n const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);\n this.store(slicedCopyOfBytes, str);\n return str;\n }\n}\n","import { prettyByte } from \"./utils/prettyByte\";\nimport { ExtensionCodec, ExtensionCodecType } from \"./ExtensionCodec\";\nimport { getInt64, getUint64, UINT32_MAX } from \"./utils/int\";\nimport { utf8DecodeJs, TEXT_DECODER_THRESHOLD, utf8DecodeTD } from \"./utils/utf8\";\nimport { createDataView, ensureUint8Array } from \"./utils/typedArrays\";\nimport { CachedKeyDecoder, KeyDecoder } from \"./CachedKeyDecoder\";\nimport { DecodeError } from \"./DecodeError\";\n\nconst enum State {\n ARRAY,\n MAP_KEY,\n MAP_VALUE,\n}\n\ntype MapKeyType = string | number;\n\nconst isValidMapKeyType = (key: unknown): key is MapKeyType => {\n const keyType = typeof key;\n\n return keyType === \"string\" || keyType === \"number\";\n};\n\ntype StackMapState = {\n type: State.MAP_KEY | State.MAP_VALUE;\n size: number;\n key: MapKeyType | null;\n readCount: number;\n map: Record<string, unknown>;\n};\n\ntype StackArrayState = {\n type: State.ARRAY;\n size: number;\n array: Array<unknown>;\n position: number;\n};\n\ntype StackState = StackArrayState | StackMapState;\n\nconst HEAD_BYTE_REQUIRED = -1;\n\nconst EMPTY_VIEW = new DataView(new ArrayBuffer(0));\nconst EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);\n\n// IE11: Hack to support IE11.\n// IE11: Drop this hack and just use RangeError when IE11 is obsolete.\nexport const DataViewIndexOutOfBoundsError: typeof Error = (() => {\n try {\n // IE11: The spec says it should throw RangeError,\n // IE11: but in IE11 it throws TypeError.\n EMPTY_VIEW.getInt8(0);\n } catch (e: any) {\n return e.constructor;\n }\n throw new Error(\"never reached\");\n})();\n\nconst MORE_DATA = new DataViewIndexOutOfBoundsError(\"Insufficient data\");\n\nconst sharedCachedKeyDecoder = new CachedKeyDecoder();\n\nexport class Decoder<ContextType = undefined> {\n private totalPos = 0;\n private pos = 0;\n\n private view = EMPTY_VIEW;\n private bytes = EMPTY_BYTES;\n private headByte = HEAD_BYTE_REQUIRED;\n private readonly stack: Array<StackState> = [];\n\n public constructor(\n private readonly extensionCodec: ExtensionCodecType<ContextType> = ExtensionCodec.defaultCodec as any,\n private readonly context: ContextType = undefined as any,\n private readonly maxStrLength = UINT32_MAX,\n private readonly maxBinLength = UINT32_MAX,\n private readonly maxArrayLength = UINT32_MAX,\n private readonly maxMapLength = UINT32_MAX,\n private readonly maxExtLength = UINT32_MAX,\n private readonly keyDecoder: KeyDecoder | null = sharedCachedKeyDecoder,\n ) {}\n\n private reinitializeState() {\n this.totalPos = 0;\n this.headByte = HEAD_BYTE_REQUIRED;\n this.stack.length = 0;\n\n // view, bytes, and pos will be re-initialized in setBuffer()\n }\n\n private setBuffer(buffer: ArrayLike<number> | BufferSource): void {\n this.bytes = ensureUint8Array(buffer);\n this.view = createDataView(this.bytes);\n this.pos = 0;\n }\n\n private appendBuffer(buffer: ArrayLike<number> | BufferSource) {\n if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {\n this.setBuffer(buffer);\n } else {\n const remainingData = this.bytes.subarray(this.pos);\n const newData = ensureUint8Array(buffer);\n\n // concat remainingData + newData\n const newBuffer = new Uint8Array(remainingData.length + newData.length);\n newBuffer.set(remainingData);\n newBuffer.set(newData, remainingData.length);\n this.setBuffer(newBuffer);\n }\n }\n\n private hasRemaining(size: number) {\n return this.view.byteLength - this.pos >= size;\n }\n\n private createExtraByteError(posToShow: number): Error {\n const { view, pos } = this;\n return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`);\n }\n\n /**\n * @throws {@link DecodeError}\n * @throws {@link RangeError}\n */\n public decode(buffer: ArrayLike<number> | BufferSource): unknown {\n this.reinitializeState();\n this.setBuffer(buffer);\n\n const object = this.doDecodeSync();\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.pos);\n }\n return object;\n }\n\n public *decodeMulti(buffer: ArrayLike<number> | BufferSource): Generator<unknown, void, unknown> {\n this.reinitializeState();\n this.setBuffer(buffer);\n\n while (this.hasRemaining(1)) {\n yield this.doDecodeSync();\n }\n }\n\n public async decodeAsync(stream: AsyncIterable<ArrayLike<number> | BufferSource>): Promise<unknown> {\n let decoded = false;\n let object: unknown;\n for await (const buffer of stream) {\n if (decoded) {\n throw this.createExtraByteError(this.totalPos);\n }\n\n this.appendBuffer(buffer);\n\n try {\n object = this.doDecodeSync();\n decoded = true;\n } catch (e) {\n if (!(e instanceof DataViewIndexOutOfBoundsError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n }\n\n if (decoded) {\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.totalPos);\n }\n return object;\n }\n\n const { headByte, pos, totalPos } = this;\n throw new RangeError(\n `Insufficient data in parsing ${prettyByte(headByte)} at ${totalPos} (${pos} in the current buffer)`,\n );\n }\n\n public decodeArrayStream(\n stream: AsyncIterable<ArrayLike<number> | BufferSource>,\n ): AsyncGenerator<unknown, void, unknown> {\n return this.decodeMultiAsync(stream, true);\n }\n\n public decodeStream(stream: AsyncIterable<ArrayLike<number> | BufferSource>): AsyncGenerator<unknown, void, unknown> {\n return this.decodeMultiAsync(stream, false);\n }\n\n private async *decodeMultiAsync(stream: AsyncIterable<ArrayLike<number> | BufferSource>, isArray: boolean) {\n let isArrayHeaderRequired = isArray;\n let arrayItemsLeft = -1;\n\n for await (const buffer of stream) {\n if (isArray && arrayItemsLeft === 0) {\n throw this.createExtraByteError(this.totalPos);\n }\n\n this.appendBuffer(buffer);\n\n if (isArrayHeaderRequired) {\n arrayItemsLeft = this.readArraySize();\n isArrayHeaderRequired = false;\n this.complete();\n }\n\n try {\n while (true) {\n yield this.doDecodeSync();\n if (--arrayItemsLeft === 0) {\n break;\n }\n }\n } catch (e) {\n if (!(e instanceof DataViewIndexOutOfBoundsError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n }\n }\n\n private doDecodeSync(): unknown {\n DECODE: while (true) {\n const headByte = this.readHeadByte();\n let object: unknown;\n\n if (headByte >= 0xe0) {\n // negative fixint (111x xxxx) 0xe0 - 0xff\n object = headByte - 0x100;\n } else if (headByte < 0xc0) {\n if (headByte < 0x80) {\n // positive fixint (0xxx xxxx) 0x00 - 0x7f\n object = headByte;\n } else if (headByte < 0x90) {\n // fixmap (1000 xxxx) 0x80 - 0x8f\n const size = headByte - 0x80;\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte < 0xa0) {\n // fixarray (1001 xxxx) 0x90 - 0x9f\n const size = headByte - 0x90;\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else {\n // fixstr (101x xxxx) 0xa0 - 0xbf\n const byteLength = headByte - 0xa0;\n object = this.decodeUtf8String(byteLength, 0);\n }\n } else if (headByte === 0xc0) {\n // nil\n object = null;\n } else if (headByte === 0xc2) {\n // false\n object = false;\n } else if (headByte === 0xc3) {\n // true\n object = true;\n } else if (headByte === 0xca) {\n // float 32\n object = this.readF32();\n } else if (headByte === 0xcb) {\n // float 64\n object = this.readF64();\n } else if (headByte === 0xcc) {\n // uint 8\n object = this.readU8();\n } else if (headByte === 0xcd) {\n // uint 16\n object = this.readU16();\n } else if (headByte === 0xce) {\n // uint 32\n object = this.readU32();\n } else if (headByte === 0xcf) {\n // uint 64\n object = this.readU64();\n } else if (headByte === 0xd0) {\n // int 8\n object = this.readI8();\n } else if (headByte === 0xd1) {\n // int 16\n object = this.readI16();\n } else if (headByte === 0xd2) {\n // int 32\n object = this.readI32();\n } else if (headByte === 0xd3) {\n // int 64\n object = this.readI64();\n } else if (headByte === 0xd9) {\n // str 8\n const byteLength = this.lookU8();\n object = this.decodeUtf8String(byteLength, 1);\n } else if (headByte === 0xda) {\n // str 16\n const byteLength = this.lookU16();\n object = this.decodeUtf8String(byteLength, 2);\n } else if (headByte === 0xdb) {\n // str 32\n const byteLength = this.lookU32();\n object = this.decodeUtf8String(byteLength, 4);\n } else if (headByte === 0xdc) {\n // array 16\n const size = this.readU16();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else if (headByte === 0xdd) {\n // array 32\n const size = this.readU32();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else if (headByte === 0xde) {\n // map 16\n const size = this.readU16();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte === 0xdf) {\n // map 32\n const size = this.readU32();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte === 0xc4) {\n // bin 8\n const size = this.lookU8();\n object = this.decodeBinary(size, 1);\n } else if (headByte === 0xc5) {\n // bin 16\n const size = this.lookU16();\n object = this.decodeBinary(size, 2);\n } else if (headByte === 0xc6) {\n // bin 32\n const size = this.lookU32();\n object = this.decodeBinary(size, 4);\n } else if (headByte === 0xd4) {\n // fixext 1\n object = this.decodeExtension(1, 0);\n } else if (headByte === 0xd5) {\n // fixext 2\n object = this.decodeExtension(2, 0);\n } else if (headByte === 0xd6) {\n // fixext 4\n object = this.decodeExtension(4, 0);\n } else if (headByte === 0xd7) {\n // fixext 8\n object = this.decodeExtension(8, 0);\n } else if (headByte === 0xd8) {\n // fixext 16\n object = this.decodeExtension(16, 0);\n } else if (headByte === 0xc7) {\n // ext 8\n const size = this.lookU8();\n object = this.decodeExtension(size, 1);\n } else if (headByte === 0xc8) {\n // ext 16\n const size = this.lookU16();\n object = this.decodeExtension(size, 2);\n } else if (headByte === 0xc9) {\n // ext 32\n const size = this.lookU32();\n object = this.decodeExtension(size, 4);\n } else {\n throw new DecodeError(`Unrecognized type byte: ${prettyByte(headByte)}`);\n }\n\n this.complete();\n\n const stack = this.stack;\n while (stack.length > 0) {\n // arrays and maps\n const state = stack[stack.length - 1]!;\n if (state.type === State.ARRAY) {\n state.array[state.position] = object;\n state.position++;\n if (state.position === state.size) {\n stack.pop();\n object = state.array;\n } else {\n continue DECODE;\n }\n } else if (state.type === State.MAP_KEY) {\n if (!isValidMapKeyType(object)) {\n throw new DecodeError(\"The type of key must be string or number but \" + typeof object);\n }\n if (object === \"__proto__\") {\n throw new DecodeError(\"The key __proto__ is not allowed\");\n }\n\n state.key = object;\n state.type = State.MAP_VALUE;\n continue DECODE;\n } else {\n // it must be `state.type === State.MAP_VALUE` here\n\n state.map[state.key!] = object;\n state.readCount++;\n\n if (state.readCount === state.size) {\n stack.pop();\n object = state.map;\n } else {\n state.key = null;\n state.type = State.MAP_KEY;\n continue DECODE;\n }\n }\n }\n\n return object;\n }\n }\n\n private readHeadByte(): number {\n if (this.headByte === HEAD_BYTE_REQUIRED) {\n this.headByte = this.readU8();\n // console.log(\"headByte\", prettyByte(this.headByte));\n }\n\n return this.headByte;\n }\n\n private complete(): void {\n this.headByte = HEAD_BYTE_REQUIRED;\n }\n\n private readArraySize(): number {\n const headByte = this.readHeadByte();\n\n switch (headByte) {\n case 0xdc:\n return this.readU16();\n case 0xdd:\n return this.readU32();\n default: {\n if (headByte < 0xa0) {\n return headByte - 0x90;\n } else {\n throw new DecodeError(`Unrecognized array type byte: ${prettyByte(headByte)}`);\n }\n }\n }\n }\n\n private pushMapState(size: number) {\n if (size > this.maxMapLength) {\n throw new DecodeError(`Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`);\n }\n\n this.stack.push({\n type: State.MAP_KEY,\n size,\n key: null,\n readCount: 0,\n map: {},\n });\n }\n\n private pushArrayState(size: number) {\n if (size > this.maxArrayLength) {\n throw new DecodeError(`Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`);\n }\n\n this.stack.push({\n type: State.ARRAY,\n size,\n array: new Array<unknown>(size),\n position: 0,\n });\n }\n\n private decodeUtf8String(byteLength: number, headerOffset: number): string {\n if (byteLength > this.maxStrLength) {\n throw new DecodeError(\n `Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`,\n );\n }\n\n if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {\n throw MORE_DATA;\n }\n\n const offset = this.pos + headerOffset;\n let object: string;\n if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) {\n object = this.keyDecoder.decode(this.bytes, offset, byteLength);\n } else if (byteLength > TEXT_DECODER_THRESHOLD) {\n object = utf8DecodeTD(this.bytes, offset, byteLength);\n } else {\n object = utf8DecodeJs(this.bytes, offset, byteLength);\n }\n this.pos += headerOffset + byteLength;\n return object;\n }\n\n private stateIsMapKey(): boolean {\n if (this.stack.length > 0) {\n const state = this.stack[this.stack.length - 1]!;\n return state.type === State.MAP_KEY;\n }\n return false;\n }\n\n private decodeBinary(byteLength: number, headOffset: number): Uint8Array {\n if (byteLength > this.maxBinLength) {\n throw new DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`);\n }\n\n if (!this.hasRemaining(byteLength + headOffset)) {\n throw MORE_DATA;\n }\n\n const offset = this.pos + headOffset;\n const object = this.bytes.subarray(offset, offset + byteLength);\n this.pos += headOffset + byteLength;\n return object;\n }\n\n private decodeExtension(size: number, headOffset: number): unknown {\n if (size > this.maxExtLength) {\n throw new DecodeError(`Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`);\n }\n\n const extType = this.view.getInt8(this.pos + headOffset);\n const data = this.decodeBinary(size, headOffset + 1 /* extType */);\n return this.extensionCodec.decode(data, extType, this.context);\n }\n\n private lookU8() {\n return this.view.getUint8(this.pos);\n }\n\n private lookU16() {\n return this.view.getUint16(this.pos);\n }\n\n private lookU32() {\n return this.view.getUint32(this.pos);\n }\n\n private readU8(): number {\n const value = this.view.getUint8(this.pos);\n this.pos++;\n return value;\n }\n\n private readI8(): number {\n const value = this.view.getInt8(this.pos);\n this.pos++;\n return value;\n }\n\n private readU16(): number {\n const value = this.view.getUint16(this.pos);\n this.pos += 2;\n return value;\n }\n\n private readI16(): number {\n const value = this.view.getInt16(this.pos);\n this.pos += 2;\n return value;\n }\n\n private readU32(): number {\n const value = this.view.getUint32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readI32(): number {\n const value = this.view.getInt32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readU64(): number {\n const value = getUint64(this.view, this.pos);\n this.pos += 8;\n return value;\n }\n\n private readI64(): number {\n const value = getInt64(this.view, this.pos);\n this.pos += 8;\n return value;\n }\n\n private readF32() {\n const value = this.view.getFloat32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readF64() {\n const value = this.view.getFloat64(this.pos);\n this.pos += 8;\n return value;\n }\n}\n","import { Decoder } from \"./Decoder\";\nimport type { ExtensionCodecType } from \"./ExtensionCodec\";\nimport type { ContextOf, SplitUndefined } from \"./context\";\n\nexport type DecodeOptions<ContextType = undefined> = Readonly<\n Partial<{\n extensionCodec: ExtensionCodecType<ContextType>;\n\n /**\n * Maximum string length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxStrLength: number;\n /**\n * Maximum binary length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxBinLength: number;\n /**\n * Maximum array length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxArrayLength: number;\n /**\n * Maximum map length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxMapLength: number;\n /**\n * Maximum extension length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxExtLength: number;\n }>\n> &\n ContextOf<ContextType>;\n\nexport const defaultDecodeOptions: DecodeOptions = {};\n\n/**\n * It decodes a single MessagePack object in a buffer.\n *\n * This is a synchronous decoding function.\n * See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decode<ContextType = undefined>(\n buffer: ArrayLike<number> | BufferSource,\n options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): unknown {\n const decoder = new Decoder(\n options.extensionCodec,\n (options as typeof options & { context: any }).context,\n options.maxStrLength,\n options.maxBinLength,\n options.maxArrayLength,\n options.maxMapLength,\n options.maxExtLength,\n );\n return decoder.decode(buffer);\n}\n\n/**\n * It decodes multiple MessagePack objects in a buffer.\n * This is corresponding to {@link decodeMultiStream()}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMulti<ContextType = undefined>(\n buffer: ArrayLike<number> | BufferSource,\n options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): Generator<unknown, void, unknown> {\n const decoder = new Decoder(\n options.extensionCodec,\n (options as typeof options & { context: any }).context,\n options.maxStrLength,\n options.maxBinLength,\n options.maxArrayLength,\n options.maxMapLength,\n options.maxExtLength,\n );\n return decoder.decodeMulti(buffer);\n}\n","// utility for whatwg streams\n\n// The living standard of whatwg streams says\n// ReadableStream is also AsyncIterable, but\n// as of June 2019, no browser implements it.\n// See https://streams.spec.whatwg.org/ for details\nexport type ReadableStreamLike<T> = AsyncIterable<T> | ReadableStream<T>;\n\nexport function isAsyncIterable<T>(object: ReadableStreamLike<T>): object is AsyncIterable<T> {\n return (object as any)[Symbol.asyncIterator] != null;\n}\n\nfunction assertNonNull<T>(value: T | null | undefined): asserts value is T {\n if (value == null) {\n throw new Error(\"Assertion Failure: value must not be null nor undefined\");\n }\n}\n\nexport async function* asyncIterableFromStream<T>(stream: ReadableStream<T>): AsyncIterable<T> {\n const reader = stream.getReader();\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n assertNonNull(value);\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nexport function ensureAsyncIterable<T>(streamLike: ReadableStreamLike<T>): AsyncIterable<T> {\n if (isAsyncIterable(streamLike)) {\n return streamLike;\n } else {\n return asyncIterableFromStream(streamLike);\n }\n}\n","import { Decoder } from \"./Decoder\";\nimport { ensureAsyncIterable } from \"./utils/stream\";\nimport { defaultDecodeOptions } from \"./decode\";\nimport type { ReadableStreamLike } from \"./utils/stream\";\nimport type { DecodeOptions } from \"./decode\";\nimport type { SplitUndefined } from \"./context\";\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\n export async function decodeAsync<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): Promise<unknown> {\n const stream = ensureAsyncIterable(streamLike);\n\n const decoder = new Decoder(\n options.extensionCodec,\n (options as typeof options & { context: any }).context,\n options.maxStrLength,\n options.maxBinLength,\n options.maxArrayLength,\n options.maxMapLength,\n options.maxExtLength,\n );\n return decoder.decodeAsync(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\n export function decodeArrayStream<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): AsyncGenerator<unknown, void, unknown> {\n const stream = ensureAsyncIterable(streamLike);\n\n const decoder = new Decoder(\n options.extensionCodec,\n (options as typeof options & { context: any }).context,\n options.maxStrLength,\n options.maxBinLength,\n options.maxArrayLength,\n options.maxMapLength,\n options.maxExtLength,\n );\n\n return decoder.decodeArrayStream(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMultiStream<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): AsyncGenerator<unknown, void, unknown> {\n const stream = ensureAsyncIterable(streamLike);\n\n const decoder = new Decoder(\n options.extensionCodec,\n (options as typeof options & { context: any }).context,\n options.maxStrLength,\n options.maxBinLength,\n options.maxArrayLength,\n options.maxMapLength,\n options.maxExtLength,\n );\n\n return decoder.decodeStream(stream);\n}\n\n/**\n * @deprecated Use {@link decodeMultiStream()} instead.\n */\nexport function decodeStream<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): AsyncGenerator<unknown, void, unknown> {\n return decodeMultiStream(streamLike, options);\n}\n","const LOG_PREFIX = \"Dendri: \";\n\n/*\nPrints log messages depending on the debug level passed in. Defaults to 0.\n0 Prints no logs.\n1 Prints only errors.\n2 Prints errors and warnings.\n3 Prints all logs.\n*/\nexport enum LogLevel {\n\t/**\n\t * Prints no logs.\n\t */\n\tDisabled,\n\t/**\n\t * Prints only errors.\n\t */\n\tErrors,\n\t/**\n\t * Prints errors and warnings.\n\t */\n\tWarnings,\n\t/**\n\t * Prints all logs.\n\t */\n\tAll,\n}\n\nclass Logger {\n\tprivate _logLevel = LogLevel.Disabled;\n\n\tget logLevel(): LogLevel {\n\t\treturn this._logLevel;\n\t}\n\n\tset logLevel(logLevel: LogLevel) {\n\t\tthis._logLevel = logLevel;\n\t}\n\n\tlog(...args: any[]) {\n\t\tif (this._logLevel >= LogLevel.All) {\n\t\t\tthis._print(LogLevel.All, ...args);\n\t\t}\n\t}\n\n\twarn(...args: any[]) {\n\t\tif (this._logLevel >= LogLevel.Warnings) {\n\t\t\tthis._print(LogLevel.Warnings, ...args);\n\t\t}\n\t}\n\n\terror(...args: any[]) {\n\t\tif (this._logLevel >= LogLevel.Errors) {\n\t\t\tthis._print(LogLevel.Errors, ...args);\n\t\t}\n\t}\n\n\tsetLogFunction(fn: (logLevel: LogLevel, ..._: any[]) => void): void {\n\t\tthis._print = fn;\n\t}\n\n\tprivate _print(logLevel: LogLevel, ...rest: any[]): void {\n\t\tconst copy = [LOG_PREFIX, ...rest];\n\n\t\tfor (const i in copy) {\n\t\t\tif (copy[i] instanceof Error) {\n\t\t\t\tcopy[i] = `(${copy[i].name}) ${copy[i].message}`;\n\t\t\t}\n\t\t}\n\n\t\tif (logLevel >= LogLevel.All) {\n\t\t\tconsole.log(...copy);\n\t\t} else if (logLevel >= LogLevel.Warnings) {\n\t\t\tconsole.warn(\"WARNING\", ...copy);\n\t\t} else if (logLevel >= LogLevel.Errors) {\n\t\t\tconsole.error(\"ERROR\", ...copy);\n\t\t}\n\t}\n}\n\nexport default new Logger();\n","import { EventEmitter } from \"eventemitter3\";\nimport logger from \"./logger\";\n\nexport interface EventsWithError<ErrorType extends string> {\n\terror: (error: DendriError<`${ErrorType}`>) => void;\n}\n\nexport class EventEmitterWithError<\n\tErrorType extends string,\n\tEvents extends EventsWithError<ErrorType>,\n> extends EventEmitter<Events, never> {\n\t/**\n\t * Emits a typed error message.\n\t *\n\t * @internal\n\t */\n\temitError(type: ErrorType, err: string | Error, retryable = false): void {\n\t\tlogger.error(\"Error:\", err);\n\n\t\tconst error = new DendriError<`${ErrorType}`>(`${type}`, err);\n\t\terror.retryable = retryable;\n\n\t\t// @ts-expect-error\n\t\tthis.emit(\"error\", error);\n\t}\n}\n/**\n * A DendriError is emitted whenever an error occurs.\n * It always has a `.type`, which can be used to identify the error.\n */\nexport class DendriError<T extends string> extends Error {\n\tpublic type: T;\n\n\t/** Whether the operation that caused this error can be retried. */\n\tpublic retryable: boolean;\n\n\t/** Structured context about the error. */\n\tpublic details?: Record<string, unknown>;\n\n\t/**\n\t * @internal\n\t */\n\tconstructor(type: T, err: Error | string) {\n\t\tif (typeof err === \"string\") {\n\t\t\tsuper(err);\n\t\t} else {\n\t\t\tsuper(err.message);\n\t\t\tthis.stack = err.stack;\n\t\t}\n\n\t\tthis.type = type;\n\t\tthis.retryable = false;\n\t}\n\n\t/** Set the retryable flag (fluent API). */\n\tsetRetryable(retryable: boolean): this {\n\t\tthis.retryable = retryable;\n\t\treturn this;\n\t}\n\n\t/** Set structured details (fluent API). */\n\tsetDetails(details: Record<string, unknown>): this {\n\t\tthis.details = details;\n\t\treturn this;\n\t}\n}\n","import type { ValidEventTypes } from \"eventemitter3\";\nimport type { Dendri } from \"./dendri\";\nimport { type DendriError, EventEmitterWithError, type EventsWithError } from \"./dendriError\";\nimport type { BaseConnectionErrorType, ConnectionType } from \"./enums\";\nimport type { ServerMessage } from \"./servermessage\";\n\nexport interface BaseConnectionEvents<ErrorType extends string = BaseConnectionErrorType>\n\textends EventsWithError<ErrorType> {\n\t/**\n\t * Emitted when either you or the remote peer closes the connection.\n\t *\n\t * ```ts\n\t * connection.on('close', () => { ... });\n\t * ```\n\t */\n\tclose: () => void;\n\t/**\n\t * ```ts\n\t * connection.on('error', (error) => { ... });\n\t * ```\n\t */\n\terror: (error: DendriError<`${ErrorType}`>) => void;\n\ticeStateChanged: (state: RTCIceConnectionState) => void;\n}\n\nexport abstract class BaseConnection<\n\tSubClassEvents extends ValidEventTypes,\n\tErrorType extends string = never,\n> extends EventEmitterWithError<\n\tErrorType | BaseConnectionErrorType,\n\tSubClassEvents & BaseConnectionEvents<BaseConnectionErrorType | ErrorType>\n> {\n\tprotected _open = false;\n\n\t/**\n\t * Any type of metadata associated with the connection,\n\t * passed in by whoever initiated the connection.\n\t */\n\treadonly metadata: any;\n\tconnectionId!: string;\n\n\tpeerConnection!: RTCPeerConnection | null;\n\tdataChannel: RTCDataChannel | null = null;\n\n\tabstract get type(): ConnectionType;\n\n\t/**\n\t * The optional label passed in or assigned by Dendri when the connection was initiated.\n\t */\n\tlabel!: string;\n\n\t/**\n\t * Whether the media connection is active (e.g. your call has been answered).\n\t * You can check this if you want to set a maximum wait time for a one-sided call.\n\t */\n\tget open() {\n\t\treturn this._open;\n\t}\n\n\tprotected constructor(\n\t\t/**\n\t\t * The ID of the peer on the other end of this connection.\n\t\t */\n\t\treadonly peer: string,\n\t\tpublic provider: Dendri | null,\n\t\treadonly options: any,\n\t) {\n\t\tsuper();\n\n\t\tthis.metadata = options.metadata;\n\t}\n\n\tabstract close(): void;\n\n\t/**\n\t * @internal\n\t */\n\tabstract handleMessage(message: ServerMessage): void;\n\n\t/**\n\t * Called by the Negotiator when the DataChannel is ready.\n\t * @internal\n\t * */\n\tabstract _initializeDataChannel(dc: RTCDataChannel): void;\n}\n","import type { ValidEventTypes } from \"eventemitter3\";\nimport type { BaseConnection, BaseConnectionEvents } from \"./baseconnection\";\nimport type { DataConnection } from \"./dataconnection/DataConnection\";\nimport {\n\tBaseConnectionErrorType,\n\tConnectionType,\n\tDendriErrorType,\n\tServerMessageType,\n} from \"./enums\";\nimport logger from \"./logger\";\nimport type { MediaConnection } from \"./mediaconnection\";\n\n/**\n * Manages all negotiations between Peers.\n */\nexport class Negotiator<\n\tEvents extends ValidEventTypes,\n\tT extends BaseConnection<Events | BaseConnectionEvents>,\n> {\n\tprivate _pendingCandidates: RTCIceCandidate[] = [];\n\n\tconstructor(readonly connection: T) {}\n\n\t/** Returns a PeerConnection object set up correctly (for data, media). */\n\tstartConnection(options: any) {\n\t\tconst peerConnection = this._startPeerConnection();\n\n\t\t// Set the connection's PC.\n\t\tthis.connection.peerConnection = peerConnection;\n\n\t\tif (this.connection.type === ConnectionType.Media && options._stream) {\n\t\t\tthis._addTracksToConnection(options._stream, peerConnection);\n\t\t\tthis._setCodecPreferences(peerConnection);\n\t\t}\n\n\t\t// What do we need to do now?\n\t\tif (options.originator) {\n\t\t\tconst dataConnection = this.connection;\n\n\t\t\tconst config: RTCDataChannelInit = { ordered: !!options.reliable };\n\n\t\t\tconst dataChannel = peerConnection.createDataChannel(dataConnection.label, config);\n\t\t\tdataConnection._initializeDataChannel(dataChannel);\n\n\t\t\tvoid this._makeOffer();\n\t\t} else {\n\t\t\tvoid this.handleSDP(\"OFFER\", options.sdp);\n\t\t}\n\t}\n\n\t/** Start a PC. */\n\tprivate _startPeerConnection(): RTCPeerConnection {\n\t\tlogger.log(\"Creating RTCPeerConnection.\");\n\n\t\tconst peerConnection = new RTCPeerConnection(this.connection.provider?.options.config);\n\n\t\tthis._setupListeners(peerConnection);\n\n\t\treturn peerConnection;\n\t}\n\n\t/** Set up various WebRTC listeners. */\n\tprivate _setupListeners(peerConnection: RTCPeerConnection) {\n\t\tconst peerId = this.connection.peer;\n\t\tconst connectionId = this.connection.connectionId;\n\t\tconst connectionType = this.connection.type;\n\t\tconst provider = this.connection.provider!;\n\n\t\t// ICE CANDIDATES.\n\t\tlogger.log(\"Listening for ICE candidates.\");\n\n\t\tpeerConnection.onicecandidate = (evt) => {\n\t\t\tif (!evt.candidate?.candidate) return;\n\n\t\t\tlogger.log(`Received ICE candidates for ${peerId}:`, evt.candidate);\n\n\t\t\tprovider.socket.send({\n\t\t\t\ttype: ServerMessageType.Candidate,\n\t\t\t\tpayload: {\n\t\t\t\t\tcandidate: evt.candidate,\n\t\t\t\t\ttype: connectionType,\n\t\t\t\t\tconnectionId: connectionId,\n\t\t\t\t},\n\t\t\t\tdst: peerId,\n\t\t\t});\n\t\t};\n\n\t\tpeerConnection.oniceconnectionstatechange = () => {\n\t\t\tswitch (peerConnection.iceConnectionState) {\n\t\t\t\tcase \"failed\":\n\t\t\t\t\tlogger.log(`iceConnectionState is failed, closing connections to ${peerId}`);\n\t\t\t\t\tthis.connection.emitError(\n\t\t\t\t\t\tBaseConnectionErrorType.NegotiationFailed,\n\t\t\t\t\t\t`Negotiation of connection to ${peerId} failed.`,\n\t\t\t\t\t);\n\t\t\t\t\tthis.connection.close();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"closed\":\n\t\t\t\t\tlogger.log(`iceConnectionState is closed, closing connections to ${peerId}`);\n\t\t\t\t\tthis.connection.emitError(\n\t\t\t\t\t\tBaseConnectionErrorType.ConnectionClosed,\n\t\t\t\t\t\t`Connection to ${peerId} closed.`,\n\t\t\t\t\t);\n\t\t\t\t\tthis.connection.close();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"disconnected\":\n\t\t\t\t\tlogger.log(`iceConnectionState changed to disconnected on the connection with ${peerId}`);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"completed\":\n\t\t\t\t\tpeerConnection.onicecandidate = () => {};\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tthis.connection.emit(\"iceStateChanged\", peerConnection.iceConnectionState);\n\t\t};\n\n\t\t// DATACONNECTION.\n\t\tlogger.log(\"Listening for data channel\");\n\t\t// Fired between offer and answer, so options should already be saved\n\t\t// in the options hash.\n\t\tpeerConnection.ondatachannel = (evt) => {\n\t\t\tlogger.log(\"Received data channel\");\n\n\t\t\tconst dataChannel = evt.channel;\n\t\t\tconst connection = provider.getConnection(peerId, connectionId);\n\n\t\t\tif (!connection) {\n\t\t\t\tlogger.warn(`Received data channel for non-existent connection ${connectionId}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconnection._initializeDataChannel(dataChannel);\n\t\t};\n\n\t\t// MEDIACONNECTION.\n\t\tlogger.log(\"Listening for remote stream\");\n\n\t\tpeerConnection.ontrack = (evt) => {\n\t\t\tlogger.log(\"Received remote stream\");\n\n\t\t\tconst stream = evt.streams[0];\n\t\t\tconst connection = provider.getConnection(peerId, connectionId);\n\n\t\t\tif (!connection) {\n\t\t\t\tlogger.warn(`Received remote stream for non-existent connection ${connectionId}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (connection.type === ConnectionType.Media) {\n\t\t\t\tconst mediaConnection = <MediaConnection>connection;\n\n\t\t\t\tthis._addStreamToMediaConnection(stream, mediaConnection);\n\t\t\t}\n\t\t};\n\t}\n\n\tcleanup(): void {\n\t\tlogger.log(`Cleaning up PeerConnection to ${this.connection.peer}`);\n\n\t\tconst peerConnection = this.connection.peerConnection;\n\n\t\tif (!peerConnection) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.connection.peerConnection = null;\n\t\tthis._pendingCandidates = [];\n\n\t\t//unsubscribe from all PeerConnection's events\n\t\tpeerConnection.onicecandidate =\n\t\t\tpeerConnection.oniceconnectionstatechange =\n\t\t\tpeerConnection.ondatachannel =\n\t\t\tpeerConnection.ontrack =\n\t\t\t\t() => {};\n\n\t\tconst peerConnectionNotClosed = peerConnection.signalingState !== \"closed\";\n\t\tlet dataChannelNotClosed = false;\n\n\t\tconst dataChannel = this.connection.dataChannel;\n\n\t\tif (dataChannel) {\n\t\t\tdataChannelNotClosed = !!dataChannel.readyState && dataChannel.readyState !== \"closed\";\n\t\t\tif (dataChannelNotClosed) {\n\t\t\t\tdataChannel.close();\n\t\t\t}\n\t\t}\n\n\t\tif (peerConnectionNotClosed || dataChannelNotClosed) {\n\t\t\tpeerConnection.close();\n\t\t}\n\t}\n\n\tprivate async _makeOffer(): Promise<void> {\n\t\tconst peerConnection = this.connection.peerConnection!;\n\t\tconst provider = this.connection.provider!;\n\n\t\ttry {\n\t\t\tconst offer = await peerConnection.createOffer(this.connection.options.constraints);\n\n\t\t\tif (!this.connection.peerConnection) {\n\t\t\t\tlogger.log(\"PeerConnection closed during createOffer\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogger.log(\"Created offer.\");\n\n\t\t\tif (\n\t\t\t\tthis.connection.options.sdpTransform &&\n\t\t\t\ttypeof this.connection.options.sdpTransform === \"function\"\n\t\t\t) {\n\t\t\t\toffer.sdp = this.connection.options.sdpTransform(offer.sdp) || offer.sdp;\n\t\t\t}\n\n\t\t\t// Apply H.264 SDP fallback for video (Safari compatibility)\n\t\t\tif (this.connection.type === ConnectionType.Media && offer.sdp) {\n\t\t\t\toffer.sdp = this._applyH264SdpFallback(offer.sdp, peerConnection);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait peerConnection.setLocalDescription(offer);\n\n\t\t\t\tif (!this.connection.peerConnection) {\n\t\t\t\t\tlogger.log(\"PeerConnection closed during setLocalDescription\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlogger.log(\"Set localDescription:\", offer, `for:${this.connection.peer}`);\n\n\t\t\t\tlet payload: any = {\n\t\t\t\t\tsdp: offer,\n\t\t\t\t\ttype: this.connection.type,\n\t\t\t\t\tconnectionId: this.connection.connectionId,\n\t\t\t\t\tmetadata: this.connection.metadata,\n\t\t\t\t};\n\n\t\t\t\tif (this.connection.type === ConnectionType.Data) {\n\t\t\t\t\tconst dataConnection = <DataConnection>(<unknown>this.connection);\n\n\t\t\t\t\tpayload = {\n\t\t\t\t\t\t...payload,\n\t\t\t\t\t\tlabel: dataConnection.label,\n\t\t\t\t\t\treliable: dataConnection.reliable,\n\t\t\t\t\t\tserialization: dataConnection.serialization,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tprovider.socket.send({\n\t\t\t\t\ttype: ServerMessageType.Offer,\n\t\t\t\t\tpayload,\n\t\t\t\t\tdst: this.connection.peer,\n\t\t\t\t});\n\t\t\t} catch (err: unknown) {\n\t\t\t\t// TODO: investigate why _makeOffer is being called from the answer\n\t\t\t\tif (\n\t\t\t\t\terr !==\n\t\t\t\t\t\"OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer\"\n\t\t\t\t) {\n\t\t\t\t\tprovider.emitError(DendriErrorType.WebRTC, err instanceof Error ? err : String(err));\n\t\t\t\t\tlogger.log(\"Failed to setLocalDescription, \", err);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err_1: unknown) {\n\t\t\tprovider.emitError(DendriErrorType.WebRTC, err_1 instanceof Error ? err_1 : String(err_1));\n\t\t\tlogger.log(\"Failed to createOffer, \", err_1);\n\t\t}\n\t}\n\n\tprivate async _makeAnswer(): Promise<void> {\n\t\tconst peerConnection = this.connection.peerConnection!;\n\t\tconst provider = this.connection.provider!;\n\n\t\ttry {\n\t\t\tconst answer = await peerConnection.createAnswer();\n\n\t\t\tif (!this.connection.peerConnection) {\n\t\t\t\tlogger.log(\"PeerConnection closed during createAnswer\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogger.log(\"Created answer.\");\n\n\t\t\tif (\n\t\t\t\tthis.connection.options.sdpTransform &&\n\t\t\t\ttypeof this.connection.options.sdpTransform === \"function\"\n\t\t\t) {\n\t\t\t\tanswer.sdp = this.connection.options.sdpTransform(answer.sdp) || answer.sdp;\n\t\t\t}\n\n\t\t\t// Apply H.264 SDP fallback for video (Safari compatibility)\n\t\t\tif (this.connection.type === ConnectionType.Media && answer.sdp) {\n\t\t\t\tanswer.sdp = this._applyH264SdpFallback(answer.sdp, peerConnection);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait peerConnection.setLocalDescription(answer);\n\n\t\t\t\tif (!this.connection.peerConnection) {\n\t\t\t\t\tlogger.log(\"PeerConnection closed during setLocalDescription\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlogger.log(`Set localDescription:`, answer, `for:${this.connection.peer}`);\n\n\t\t\t\tprovider.socket.send({\n\t\t\t\t\ttype: ServerMessageType.Answer,\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tsdp: answer,\n\t\t\t\t\t\ttype: this.connection.type,\n\t\t\t\t\t\tconnectionId: this.connection.connectionId,\n\t\t\t\t\t},\n\t\t\t\t\tdst: this.connection.peer,\n\t\t\t\t});\n\t\t\t} catch (err: unknown) {\n\t\t\t\tprovider.emitError(DendriErrorType.WebRTC, err instanceof Error ? err : String(err));\n\t\t\t\tlogger.log(\"Failed to setLocalDescription, \", err);\n\t\t\t}\n\t\t} catch (err_1: unknown) {\n\t\t\tprovider.emitError(DendriErrorType.WebRTC, err_1 instanceof Error ? err_1 : String(err_1));\n\t\t\tlogger.log(\"Failed to create answer, \", err_1);\n\t\t}\n\t}\n\n\t/** Handle an SDP. */\n\tasync handleSDP(type: string, sdp: any): Promise<void> {\n\t\tconst peerConnection = this.connection.peerConnection!;\n\t\tconst provider = this.connection.provider!;\n\n\t\tlogger.log(\"Setting remote description\", sdp);\n\n\t\ttry {\n\t\t\tawait peerConnection.setRemoteDescription(sdp);\n\n\t\t\tif (!this.connection.peerConnection) {\n\t\t\t\tlogger.log(\"PeerConnection closed during setRemoteDescription\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogger.log(`Set remoteDescription:${type} for:${this.connection.peer}`);\n\n\t\t\t// Flush any ICE candidates that arrived before remote description was set\n\t\t\tif (this._pendingCandidates.length > 0) {\n\t\t\t\tlogger.log(`Flushing ${this._pendingCandidates.length} pending ICE candidates`);\n\t\t\t\tconst candidates = this._pendingCandidates;\n\t\t\t\tthis._pendingCandidates = [];\n\t\t\t\tfor (const candidate of candidates) {\n\t\t\t\t\tawait this.handleCandidate(candidate);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (type === \"OFFER\") {\n\t\t\t\tawait this._makeAnswer();\n\t\t\t}\n\t\t} catch (err: unknown) {\n\t\t\tprovider.emitError(DendriErrorType.WebRTC, err instanceof Error ? err : String(err));\n\t\t\tlogger.log(\"Failed to setRemoteDescription, \", err);\n\t\t}\n\t}\n\n\t/** Handle a candidate. */\n\tasync handleCandidate(ice: RTCIceCandidate) {\n\t\tlogger.log(`handleCandidate:`, ice);\n\n\t\tconst peerConnection = this.connection.peerConnection;\n\n\t\tif (!peerConnection) {\n\t\t\tlogger.warn(`PeerConnection not set for ${this.connection.peer}, cannot add ICE candidate`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Queue candidates that arrive before remote description is set\n\t\tif (!peerConnection.remoteDescription) {\n\t\t\tlogger.log(`Queueing ICE candidate (no remote description yet)`);\n\t\t\tthis._pendingCandidates.push(ice);\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tawait peerConnection.addIceCandidate(ice);\n\t\t\tlogger.log(`Added ICE candidate for:${this.connection.peer}`);\n\t\t} catch (err: unknown) {\n\t\t\tthis.connection.provider?.emitError(\n\t\t\t\tDendriErrorType.WebRTC,\n\t\t\t\terr instanceof Error ? err : String(err),\n\t\t\t);\n\t\t\tlogger.log(\"Failed to handleCandidate, \", err);\n\t\t}\n\t}\n\n\t/**\n\t * Set codec preferences on all video transceivers to prioritize H.264.\n\t * Safari only supports H.264 for video, so this ensures cross-browser\n\t * compatibility when one peer is Safari and the other is Chrome/Firefox.\n\t */\n\tprivate _setCodecPreferences(pc: RTCPeerConnection): void {\n\t\tif (!pc.getTransceivers) return;\n\n\t\tfor (const transceiver of pc.getTransceivers()) {\n\t\t\tif (transceiver.sender?.track?.kind === \"video\") {\n\t\t\t\tconst codecs =\n\t\t\t\t\ttypeof RTCRtpReceiver !== \"undefined\"\n\t\t\t\t\t\t? RTCRtpReceiver.getCapabilities?.(\"video\")?.codecs\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (!codecs) continue;\n\n\t\t\t\tconst h264 = codecs.filter((c) => c.mimeType === \"video/H264\");\n\t\t\t\tconst others = codecs.filter((c) => c.mimeType !== \"video/H264\");\n\n\t\t\t\tif (h264.length > 0 && typeof transceiver.setCodecPreferences === \"function\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttransceiver.setCodecPreferences([...h264, ...others]);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// setCodecPreferences may throw if codecs are invalid\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * SDP fallback for browsers without setCodecPreferences support.\n\t * Reorders H.264 payload types to the front of the m=video line so that\n\t * H.264 is preferred during negotiation.\n\t */\n\t_preferH264InSdp(sdp: string): string {\n\t\tconst lines = sdp.split(\"\\r\\n\");\n\t\tconst result: string[] = [];\n\n\t\t// Collect H.264 payload types from a=rtpmap lines\n\t\tconst h264Payloads: string[] = [];\n\t\tfor (const line of lines) {\n\t\t\tif (line.includes(\"a=rtpmap:\") && line.toLowerCase().includes(\"h264\")) {\n\t\t\t\tconst match = line.match(/a=rtpmap:(\\d+)/);\n\t\t\t\tif (match) h264Payloads.push(match[1]);\n\t\t\t}\n\t\t}\n\n\t\tfor (const line of lines) {\n\t\t\tif (line.startsWith(\"m=video\") && h264Payloads.length > 0) {\n\t\t\t\tconst parts = line.split(\" \");\n\t\t\t\tconst prefix = parts.slice(0, 3).join(\" \");\n\t\t\t\tconst payloads = parts.slice(3);\n\t\t\t\tconst reordered = [...h264Payloads, ...payloads.filter((p) => !h264Payloads.includes(p))];\n\t\t\t\tresult.push(`${prefix} ${reordered.join(\" \")}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tresult.push(line);\n\t\t}\n\n\t\treturn result.join(\"\\r\\n\");\n\t}\n\n\t/**\n\t * Apply H.264 preference to SDP when setCodecPreferences is not available.\n\t * Returns the original SDP unchanged if setCodecPreferences was already applied.\n\t */\n\tprivate _applyH264SdpFallback(sdp: string, pc: RTCPeerConnection): string {\n\t\t// If setCodecPreferences is supported, the transceiver API already handled it\n\t\tconst hasSetCodecPreferences =\n\t\t\tpc.getTransceivers &&\n\t\t\tpc.getTransceivers().some((t) => typeof t.setCodecPreferences === \"function\");\n\n\t\tif (hasSetCodecPreferences) return sdp;\n\n\t\treturn this._preferH264InSdp(sdp);\n\t}\n\n\tprivate _addTracksToConnection(stream: MediaStream, peerConnection: RTCPeerConnection): void {\n\t\tlogger.log(`add tracks from stream ${stream.id} to peer connection`);\n\n\t\tif (!peerConnection.addTrack) {\n\t\t\tlogger.error(`Your browser doesn't support RTCPeerConnection#addTrack. Ignored.`);\n\t\t\treturn;\n\t\t}\n\n\t\tstream.getTracks().forEach((track) => {\n\t\t\tpeerConnection.addTrack(track, stream);\n\t\t});\n\t}\n\n\tprivate _addStreamToMediaConnection(stream: MediaStream, mediaConnection: MediaConnection): void {\n\t\tlogger.log(`add stream ${stream.id} to media connection ${mediaConnection.connectionId}`);\n\n\t\tmediaConnection.addStream(stream);\n\t}\n}\n","export const randomToken = () => Math.random().toString(36).slice(2);\n","import { BaseConnection, type BaseConnectionEvents } from \"../baseconnection\";\nimport type { Dendri } from \"../dendri\";\nimport type { EventsWithError } from \"../dendriError\";\nimport {\n\ttype BaseConnectionErrorType,\n\tConnectionType,\n\tDataConnectionErrorType,\n\tServerMessageType,\n} from \"../enums\";\nimport logger from \"../logger\";\nimport { Negotiator } from \"../negotiator\";\nimport type { ServerMessage } from \"../servermessage\";\nimport { randomToken } from \"../utils/randomToken\";\n\nexport interface DataConnectionEvents\n\textends EventsWithError<DataConnectionErrorType | BaseConnectionErrorType>,\n\t\tBaseConnectionEvents<DataConnectionErrorType | BaseConnectionErrorType> {\n\t/**\n\t * Emitted when data is received from the remote peer.\n\t */\n\tdata: (data: unknown) => void;\n\t/**\n\t * Emitted when the connection is established and ready-to-use.\n\t */\n\topen: () => void;\n}\n\n/**\n * Wraps a DataChannel between two Peers.\n */\nexport abstract class DataConnection extends BaseConnection<\n\tDataConnectionEvents,\n\tDataConnectionErrorType\n> {\n\tprotected static readonly ID_PREFIX = \"dc_\";\n\tprotected static readonly MAX_BUFFERED_AMOUNT = 8 * 1024 * 1024;\n\n\tprivate _negotiator: Negotiator<DataConnectionEvents, this> | null;\n\tabstract readonly serialization: string;\n\treadonly reliable: boolean;\n\n\tpublic get type() {\n\t\treturn ConnectionType.Data;\n\t}\n\n\tconstructor(peerId: string, provider: Dendri, options: any) {\n\t\tsuper(peerId, provider, options);\n\n\t\tthis.connectionId = this.options.connectionId || DataConnection.ID_PREFIX + randomToken();\n\n\t\tthis.label = this.options.label || this.connectionId;\n\t\tthis.reliable = !!this.options.reliable;\n\n\t\tthis._negotiator = new Negotiator(this);\n\n\t\tthis._negotiator.startConnection(\n\t\t\tthis.options._payload || {\n\t\t\t\toriginator: true,\n\t\t\t\treliable: this.reliable,\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Called by the Negotiator when the DataChannel is ready. */\n\toverride _initializeDataChannel(dc: RTCDataChannel): void {\n\t\tthis.dataChannel = dc;\n\n\t\tthis.dataChannel.onopen = () => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc connection success`);\n\t\t\tthis._open = true;\n\t\t\tthis.emit(\"open\");\n\t\t};\n\n\t\tthis.dataChannel.onclose = () => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc closed for:`, this.peer);\n\t\t\tthis.close();\n\t\t};\n\t}\n\n\t/**\n\t * Exposed functionality for users.\n\t */\n\n\tprivate _flushCloseTimeout: ReturnType<typeof setTimeout> | null = null;\n\n\t/** Allows user to close connection. */\n\tclose(options?: { flush?: boolean }): void {\n\t\tif (options?.flush) {\n\t\t\tthis.send({\n\t\t\t\t__peerData: {\n\t\t\t\t\ttype: \"close\",\n\t\t\t\t},\n\t\t\t});\n\t\t\t// Fallback timeout so close() is guaranteed even if flush hangs\n\t\t\tthis._flushCloseTimeout = setTimeout(() => {\n\t\t\t\tthis._flushCloseTimeout = null;\n\t\t\t\tthis.close();\n\t\t\t}, 5000);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._flushCloseTimeout) {\n\t\t\tclearTimeout(this._flushCloseTimeout);\n\t\t\tthis._flushCloseTimeout = null;\n\t\t}\n\n\t\tif (this._negotiator) {\n\t\t\tthis._negotiator.cleanup();\n\t\t\tthis._negotiator = null;\n\t\t}\n\n\t\tif (this.provider) {\n\t\t\tthis.provider._removeConnection(this);\n\n\t\t\tthis.provider = null;\n\t\t}\n\n\t\tif (this.dataChannel) {\n\t\t\tthis.dataChannel.onopen = null;\n\t\t\tthis.dataChannel.onmessage = null;\n\t\t\tthis.dataChannel.onclose = null;\n\t\t\tthis.dataChannel = null;\n\t\t}\n\n\t\tif (!this.open) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._open = false;\n\n\t\tsuper.emit(\"close\");\n\t\tthis.removeAllListeners();\n\t}\n\n\tprotected abstract _send(data: any, chunked: boolean): void | Promise<void>;\n\n\t/** Allows user to send data. */\n\tpublic send(data: any, chunked = false) {\n\t\tif (!this.open) {\n\t\t\tthis.emitError(\n\t\t\t\tDataConnectionErrorType.NotOpenYet,\n\t\t\t\t\"Connection is not open. You should listen for the `open` event before sending messages.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\treturn this._send(data, chunked);\n\t}\n\n\tasync handleMessage(message: ServerMessage) {\n\t\tconst payload = message.payload;\n\n\t\tswitch (message.type) {\n\t\t\tcase ServerMessageType.Answer:\n\t\t\t\tif (this._negotiator) {\n\t\t\t\t\tawait this._negotiator.handleSDP(message.type, payload.sdp);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Candidate:\n\t\t\t\tif (this._negotiator) {\n\t\t\t\t\tawait this._negotiator.handleCandidate(payload.candidate);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(\"Unrecognized message type:\", message.type, \"from peer:\", this.peer);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n","import type { Dendri } from \"../../dendri\";\nimport logger from \"../../logger\";\nimport { DataConnection } from \"../DataConnection\";\n\nexport abstract class StreamConnection extends DataConnection {\n\tprivate _CHUNK_SIZE = 1024 * 8 * 4;\n\tprivate _splitStream = new TransformStream<Uint8Array>({\n\t\ttransform: (chunk, controller) => {\n\t\t\tfor (let split = 0; split < chunk.length; split += this._CHUNK_SIZE) {\n\t\t\t\tcontroller.enqueue(chunk.subarray(split, split + this._CHUNK_SIZE));\n\t\t\t}\n\t\t},\n\t});\n\tprivate _rawSendStream = new WritableStream<ArrayBuffer>({\n\t\twrite: async (chunk, controller) => {\n\t\t\t// Only register the backpressure listener when the buffer is actually full\n\t\t\tif (\n\t\t\t\tthis.dataChannel &&\n\t\t\t\tthis.dataChannel.bufferedAmount > DataConnection.MAX_BUFFERED_AMOUNT - chunk.byteLength\n\t\t\t) {\n\t\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\t\tconst onLow = () => {\n\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t};\n\t\t\t\t\tconst onClose = () => {\n\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\treject(new Error(\"DataChannel closed while waiting for buffer drain\"));\n\t\t\t\t\t};\n\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\tthis.dataChannel?.removeEventListener(\"bufferedamountlow\", onLow);\n\t\t\t\t\t\tthis.dataChannel?.removeEventListener(\"close\", onClose);\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.dataChannel?.addEventListener(\"bufferedamountlow\", onLow, {\n\t\t\t\t\t\tonce: true,\n\t\t\t\t\t});\n\t\t\t\t\tthis.dataChannel?.addEventListener(\"close\", onClose, {\n\t\t\t\t\t\tonce: true,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!this.dataChannel || this.dataChannel.readyState !== \"open\") {\n\t\t\t\tcontroller.error(new Error(\"DataChannel is not open\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tthis.dataChannel.send(chunk);\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error(`DC#:${this.connectionId} Error when sending:`, e);\n\t\t\t\tcontroller.error(e);\n\t\t\t\tthis.close();\n\t\t\t}\n\t\t},\n\t});\n\tprotected writer = this._splitStream.writable.getWriter();\n\n\tprivate _readStreamMessageHandler: ((e: MessageEvent) => void) | null = null;\n\tprivate _readStreamController: ReadableStreamDefaultController<ArrayBuffer> | null = null;\n\n\tprotected _rawReadStream = new ReadableStream<ArrayBuffer>({\n\t\tstart: (controller) => {\n\t\t\tthis._readStreamController = controller;\n\t\t\tthis.once(\"open\", () => {\n\t\t\t\tif (!this.dataChannel) return;\n\t\t\t\tthis._readStreamMessageHandler = (e: MessageEvent) => {\n\t\t\t\t\tcontroller.enqueue(e.data);\n\t\t\t\t};\n\t\t\t\tthis.dataChannel.addEventListener(\"message\", this._readStreamMessageHandler);\n\t\t\t});\n\t\t},\n\t});\n\n\tprotected constructor(peerId: string, provider: Dendri, options: any) {\n\t\tsuper(peerId, provider, { ...options, reliable: true });\n\n\t\tvoid this._splitStream.readable.pipeTo(this._rawSendStream);\n\t}\n\n\tpublic override _initializeDataChannel(dc: RTCDataChannel) {\n\t\tsuper._initializeDataChannel(dc);\n\t\tthis.dataChannel!.binaryType = \"arraybuffer\";\n\t\tthis.dataChannel!.bufferedAmountLowThreshold = DataConnection.MAX_BUFFERED_AMOUNT / 2;\n\t}\n\n\tpublic override close(options?: { flush?: boolean }): void {\n\t\t// Clean up stream resources\n\t\tif (this.dataChannel && this._readStreamMessageHandler) {\n\t\t\tthis.dataChannel.removeEventListener(\"message\", this._readStreamMessageHandler);\n\t\t\tthis._readStreamMessageHandler = null;\n\t\t}\n\n\t\t// Send flush message via super BEFORE aborting the writer\n\t\tsuper.close(options);\n\n\t\ttry {\n\t\t\tthis.writer.abort();\n\t\t} catch (_) {\n\t\t\t// Writer may already be closed\n\t\t}\n\n\t\tif (this._readStreamController) {\n\t\t\ttry {\n\t\t\t\tthis._readStreamController.close();\n\t\t\t} catch (_) {\n\t\t\t\t// Controller may already be closed\n\t\t\t}\n\t\t\tthis._readStreamController = null;\n\t\t}\n\t}\n}\n","import { decodeMultiStream, Encoder } from \"@msgpack/msgpack\";\nimport type { Dendri } from \"../../dendri\";\nimport logger from \"../../logger\";\nimport { StreamConnection } from \"./StreamConnection\";\n\nexport class MsgPack extends StreamConnection {\n\treadonly serialization = \"MsgPack\";\n\tprivate _encoder = new Encoder();\n\n\tconstructor(peerId: string, provider: Dendri, options: any) {\n\t\tsuper(peerId, provider, options);\n\n\t\t(async () => {\n\t\t\tfor await (const msg of decodeMultiStream(this._rawReadStream)) {\n\t\t\t\tconst peerData = (msg as any)?.__peerData;\n\t\t\t\tif (peerData?.type === \"close\") {\n\t\t\t\t\tthis.close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.emit(\"data\", msg);\n\t\t\t}\n\t\t})().catch((err) => {\n\t\t\t// Stream was closed or errored — expected during connection teardown\n\t\t\tif (this.open) {\n\t\t\t\tlogger.error(`DC#${this.connectionId} MsgPack decode error:`, err);\n\t\t\t}\n\t\t});\n\t}\n\n\tprotected override _send(data: unknown) {\n\t\treturn this.writer.write(this._encoder.encode(data));\n\t}\n}\n"],"mappings":"uhBAAA,IAAAA,GAAAC,GAAA,CAAAC,GAAAC,IAAA,cAEA,IAAIC,GAAM,OAAO,UAAU,eACvBC,EAAS,IASb,SAASC,GAAS,CAAC,CASf,OAAO,SACTA,EAAO,UAAY,OAAO,OAAO,IA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E,MAAOE,GAAQ,CAEf,KAAK,MACRC,EAAO,MAAM,MAAM,KAAK,YAAY,yBAA0BD,CAAG,CAEnE,CAAC,CACF,CAEmB,MAAME,EAAe,CACvC,OAAO,KAAK,OAAO,MAAM,KAAK,SAAS,OAAOA,CAAI,CAAC,CACpD,CACD","names":["require_eventemitter3","__commonJSMin","exports","module","has","prefix","Events","EE","fn","context","once","addListener","emitter","event","listener","evt","clearEvent","EventEmitter","names","events","name","handlers","i","l","ee","listeners","a1","a2","a3","a4","a5","len","args","length","j","UINT32_MAX","setUint64","view","offset","value","high","low","setInt64","getInt64","getUint64","TEXT_ENCODING_AVAILABLE","_a","utf8Count","str","strLength","byteLength","pos","value","extra","utf8EncodeJs","output","outputOffset","offset","sharedTextEncoder","TEXT_ENCODER_THRESHOLD","_b","UINT32_MAX","utf8EncodeTEencode","utf8EncodeTEencodeInto","utf8EncodeTE","CHUNK_SIZE","utf8DecodeJs","bytes","inputOffset","end","units","result","byte1","byte2","byte3","byte4","unit","sharedTextDecoder","TEXT_DECODER_THRESHOLD","_c","utf8DecodeTD","stringBytes","ExtData","type","data","DecodeError","_super","__extends","message","_this","proto","EXT_TIMESTAMP","TIMESTAMP32_MAX_SEC","TIMESTAMP64_MAX_SEC","encodeTimeSpecToTimestamp","_a","sec","nsec","rv","view","secHigh","secLow","setInt64","encodeDateToTimeSpec","date","msec","nsecInSec","encodeTimestampExtension","object","timeSpec","decodeTimestampToTimeSpec","data","nsec30AndSecHigh2","secLow32","getInt64","DecodeError","decodeTimestampExtension","timestampExtension","ExtensionCodec","timestampExtension","_a","type","encode","decode","index","object","context","i","encodeExt","data","ExtData","decodeExt","ensureUint8Array","buffer","createDataView","bufferView","DEFAULT_MAX_DEPTH","DEFAULT_INITIAL_BUFFER_SIZE","Encoder","extensionCodec","context","maxDepth","initialBufferSize","sortKeys","forceFloat32","ignoreUndefined","forceIntegerToFloat","ExtensionCodec","object","depth","sizeToWrite","requiredSize","newSize","newBuffer","newBytes","newView","byteLength","maxHeaderSize","strLength","TEXT_ENCODER_THRESHOLD","utf8Count","utf8EncodeTE","utf8EncodeJs","ext","size","bytes","ensureUint8Array","_i","object_1","item","keys","count","keys_1","key","keys_2","value","values","setUint64","setInt64","prettyByte","byte","DEFAULT_MAX_KEY_LENGTH","DEFAULT_MAX_LENGTH_PER_KEY","CachedKeyDecoder","maxKeyLength","maxLengthPerKey","i","byteLength","bytes","inputOffset","records","FIND_CHUNK","_i","records_1","record","recordBytes","j","value","cachedValue","str","utf8DecodeJs","slicedCopyOfBytes","isValidMapKeyType","key","keyType","HEAD_BYTE_REQUIRED","EMPTY_VIEW","EMPTY_BYTES","DataViewIndexOutOfBoundsError","e","MORE_DATA","sharedCachedKeyDecoder","CachedKeyDecoder","Decoder","extensionCodec","context","maxStrLength","maxBinLength","maxArrayLength","maxMapLength","maxExtLength","keyDecoder","ExtensionCodec","UINT32_MAX","buffer","ensureUint8Array","createDataView","remainingData","newData","newBuffer","size","posToShow","_a","view","pos","object","stream","decoded","stream_1","__asyncValues","stream_1_1","_b","headByte","totalPos","prettyByte","isArray","isArrayHeaderRequired","arrayItemsLeft","stream_2","stream_2_1","e_2","DECODE","byteLength","DecodeError","stack","state","headerOffset","offset","TEXT_DECODER_THRESHOLD","utf8DecodeTD","utf8DecodeJs","headOffset","extType","data","value","getUint64","getInt64","defaultDecodeOptions","isAsyncIterable","object","assertNonNull","value","asyncIterableFromStream","stream","reader","__await","_a","_b","done","ensureAsyncIterable","streamLike","decodeMultiStream","streamLike","options","defaultDecodeOptions","stream","ensureAsyncIterable","decoder","Decoder","LOG_PREFIX","Logger","logLevel","args","fn","rest","copy","LOG_PREFIX","i","logger_default","import_eventemitter3","EventEmitterWithError","type","err","retryable","logger_default","error","DendriError","details","BaseConnection","EventEmitterWithError","peer","provider","options","Negotiator","connection","options","peerConnection","dataConnection","config","dataChannel","logger_default","peerId","connectionId","connectionType","provider","evt","stream","mediaConnection","peerConnectionNotClosed","dataChannelNotClosed","offer","payload","err","err_1","answer","type","sdp","candidates","candidate","ice","pc","transceiver","codecs","h264","c","others","lines","result","h264Payloads","line","match","parts","prefix","payloads","reordered","p","t","track","randomToken","DataConnection","_DataConnection","BaseConnection","peerId","provider","options","randomToken","Negotiator","dc","logger_default","data","chunked","message","payload","StreamConnection","DataConnection","chunk","controller","split","resolve","reject","onLow","cleanup","onClose","e","logger_default","peerId","provider","options","dc","MsgPack","StreamConnection","Encoder","peerId","provider","options","msg","decodeMultiStream","err","logger_default","data"]}
|
|
1
|
+
{"version":3,"sources":["../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/utils/int.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/utils/utf8.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/ExtData.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/DecodeError.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/timestamp.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/ExtensionCodec.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/utils/typedArrays.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/Encoder.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/utils/prettyByte.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/CachedKeyDecoder.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/Decoder.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/decode.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/utils/stream.ts","../node_modules/.pnpm/@msgpack+msgpack@2.8.0/node_modules/@msgpack/msgpack/src/decodeAsync.ts","../src/logger.ts","../src/dendriError.ts","../src/baseconnection.ts","../src/negotiator.ts","../src/utils/randomToken.ts","../src/dataconnection/DataConnection.ts","../src/dataconnection/StreamConnection/StreamConnection.ts","../src/dataconnection/StreamConnection/MsgPack.ts"],"sourcesContent":["'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","// Integer Utility\n\nexport const UINT32_MAX = 0xffff_ffff;\n\n// DataView extension to handle int64 / uint64,\n// where the actual range is 53-bits integer (a.k.a. safe integer)\n\nexport function setUint64(view: DataView, offset: number, value: number): void {\n const high = value / 0x1_0000_0000;\n const low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\n\nexport function setInt64(view: DataView, offset: number, value: number): void {\n const high = Math.floor(value / 0x1_0000_0000);\n const low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\n\nexport function getInt64(view: DataView, offset: number): number {\n const high = view.getInt32(offset);\n const low = view.getUint32(offset + 4);\n return high * 0x1_0000_0000 + low;\n}\n\nexport function getUint64(view: DataView, offset: number): number {\n const high = view.getUint32(offset);\n const low = view.getUint32(offset + 4);\n return high * 0x1_0000_0000 + low;\n}\n","/* eslint-disable @typescript-eslint/no-unnecessary-condition */\nimport { UINT32_MAX } from \"./int\";\n\nconst TEXT_ENCODING_AVAILABLE =\n (typeof process === \"undefined\" || process?.env?.[\"TEXT_ENCODING\"] !== \"never\") &&\n typeof TextEncoder !== \"undefined\" &&\n typeof TextDecoder !== \"undefined\";\n\nexport function utf8Count(str: string): number {\n const strLength = str.length;\n\n let byteLength = 0;\n let pos = 0;\n while (pos < strLength) {\n let value = str.charCodeAt(pos++);\n\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n byteLength++;\n continue;\n } else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n byteLength += 2;\n } else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n const extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n byteLength += 3;\n } else {\n // 4-byte\n byteLength += 4;\n }\n }\n }\n return byteLength;\n}\n\nexport function utf8EncodeJs(str: string, output: Uint8Array, outputOffset: number): void {\n const strLength = str.length;\n let offset = outputOffset;\n let pos = 0;\n while (pos < strLength) {\n let value = str.charCodeAt(pos++);\n\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n output[offset++] = value;\n continue;\n } else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n output[offset++] = ((value >> 6) & 0x1f) | 0xc0;\n } else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n const extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n output[offset++] = ((value >> 12) & 0x0f) | 0xe0;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n } else {\n // 4-byte\n output[offset++] = ((value >> 18) & 0x07) | 0xf0;\n output[offset++] = ((value >> 12) & 0x3f) | 0x80;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n }\n }\n\n output[offset++] = (value & 0x3f) | 0x80;\n }\n}\n\nconst sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;\nexport const TEXT_ENCODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE\n ? UINT32_MAX\n : typeof process !== \"undefined\" && process?.env?.[\"TEXT_ENCODING\"] !== \"force\"\n ? 200\n : 0;\n\nfunction utf8EncodeTEencode(str: string, output: Uint8Array, outputOffset: number): void {\n output.set(sharedTextEncoder!.encode(str), outputOffset);\n}\n\nfunction utf8EncodeTEencodeInto(str: string, output: Uint8Array, outputOffset: number): void {\n sharedTextEncoder!.encodeInto(str, output.subarray(outputOffset));\n}\n\nexport const utf8EncodeTE = sharedTextEncoder?.encodeInto ? utf8EncodeTEencodeInto : utf8EncodeTEencode;\n\nconst CHUNK_SIZE = 0x1_000;\n\nexport function utf8DecodeJs(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n let offset = inputOffset;\n const end = offset + byteLength;\n\n const units: Array<number> = [];\n let result = \"\";\n while (offset < end) {\n const byte1 = bytes[offset++]!;\n if ((byte1 & 0x80) === 0) {\n // 1 byte\n units.push(byte1);\n } else if ((byte1 & 0xe0) === 0xc0) {\n // 2 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n units.push(((byte1 & 0x1f) << 6) | byte2);\n } else if ((byte1 & 0xf0) === 0xe0) {\n // 3 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n const byte3 = bytes[offset++]! & 0x3f;\n units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);\n } else if ((byte1 & 0xf8) === 0xf0) {\n // 4 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n const byte3 = bytes[offset++]! & 0x3f;\n const byte4 = bytes[offset++]! & 0x3f;\n let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\n if (unit > 0xffff) {\n unit -= 0x10000;\n units.push(((unit >>> 10) & 0x3ff) | 0xd800);\n unit = 0xdc00 | (unit & 0x3ff);\n }\n units.push(unit);\n } else {\n units.push(byte1);\n }\n\n if (units.length >= CHUNK_SIZE) {\n result += String.fromCharCode(...units);\n units.length = 0;\n }\n }\n\n if (units.length > 0) {\n result += String.fromCharCode(...units);\n }\n\n return result;\n}\n\nconst sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;\nexport const TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE\n ? UINT32_MAX\n : typeof process !== \"undefined\" && process?.env?.[\"TEXT_DECODER\"] !== \"force\"\n ? 200\n : 0;\n\nexport function utf8DecodeTD(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n const stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);\n return sharedTextDecoder!.decode(stringBytes);\n}\n","/**\n * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.\n */\nexport class ExtData {\n constructor(readonly type: number, readonly data: Uint8Array) {}\n}\n","export class DecodeError extends Error {\n constructor(message: string) {\n super(message);\n\n // fix the prototype chain in a cross-platform way\n const proto: typeof DecodeError.prototype = Object.create(DecodeError.prototype);\n Object.setPrototypeOf(this, proto);\n\n Object.defineProperty(this, \"name\", {\n configurable: true,\n enumerable: false,\n value: DecodeError.name,\n });\n }\n}\n","// https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type\nimport { DecodeError } from \"./DecodeError\";\nimport { getInt64, setInt64 } from \"./utils/int\";\n\nexport const EXT_TIMESTAMP = -1;\n\nexport type TimeSpec = {\n sec: number;\n nsec: number;\n};\n\nconst TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int\nconst TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int\n\nexport function encodeTimeSpecToTimestamp({ sec, nsec }: TimeSpec): Uint8Array {\n if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {\n // Here sec >= 0 && nsec >= 0\n if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {\n // timestamp 32 = { sec32 (unsigned) }\n const rv = new Uint8Array(4);\n const view = new DataView(rv.buffer);\n view.setUint32(0, sec);\n return rv;\n } else {\n // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }\n const secHigh = sec / 0x100000000;\n const secLow = sec & 0xffffffff;\n const rv = new Uint8Array(8);\n const view = new DataView(rv.buffer);\n // nsec30 | secHigh2\n view.setUint32(0, (nsec << 2) | (secHigh & 0x3));\n // secLow32\n view.setUint32(4, secLow);\n return rv;\n }\n } else {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n const rv = new Uint8Array(12);\n const view = new DataView(rv.buffer);\n view.setUint32(0, nsec);\n setInt64(view, 4, sec);\n return rv;\n }\n}\n\nexport function encodeDateToTimeSpec(date: Date): TimeSpec {\n const msec = date.getTime();\n const sec = Math.floor(msec / 1e3);\n const nsec = (msec - sec * 1e3) * 1e6;\n\n // Normalizes { sec, nsec } to ensure nsec is unsigned.\n const nsecInSec = Math.floor(nsec / 1e9);\n return {\n sec: sec + nsecInSec,\n nsec: nsec - nsecInSec * 1e9,\n };\n}\n\nexport function encodeTimestampExtension(object: unknown): Uint8Array | null {\n if (object instanceof Date) {\n const timeSpec = encodeDateToTimeSpec(object);\n return encodeTimeSpecToTimestamp(timeSpec);\n } else {\n return null;\n }\n}\n\nexport function decodeTimestampToTimeSpec(data: Uint8Array): TimeSpec {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n // data may be 32, 64, or 96 bits\n switch (data.byteLength) {\n case 4: {\n // timestamp 32 = { sec32 }\n const sec = view.getUint32(0);\n const nsec = 0;\n return { sec, nsec };\n }\n case 8: {\n // timestamp 64 = { nsec30, sec34 }\n const nsec30AndSecHigh2 = view.getUint32(0);\n const secLow32 = view.getUint32(4);\n const sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;\n const nsec = nsec30AndSecHigh2 >>> 2;\n return { sec, nsec };\n }\n case 12: {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n\n const sec = getInt64(view, 4);\n const nsec = view.getUint32(0);\n return { sec, nsec };\n }\n default:\n throw new DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);\n }\n}\n\nexport function decodeTimestampExtension(data: Uint8Array): Date {\n const timeSpec = decodeTimestampToTimeSpec(data);\n return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);\n}\n\nexport const timestampExtension = {\n type: EXT_TIMESTAMP,\n encode: encodeTimestampExtension,\n decode: decodeTimestampExtension,\n};\n","// ExtensionCodec to handle MessagePack extensions\n\nimport { ExtData } from \"./ExtData\";\nimport { timestampExtension } from \"./timestamp\";\n\nexport type ExtensionDecoderType<ContextType> = (\n data: Uint8Array,\n extensionType: number,\n context: ContextType,\n) => unknown;\n\nexport type ExtensionEncoderType<ContextType> = (input: unknown, context: ContextType) => Uint8Array | null;\n\n// immutable interface to ExtensionCodec\nexport type ExtensionCodecType<ContextType> = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __brand?: ContextType;\n tryToEncode(object: unknown, context: ContextType): ExtData | null;\n decode(data: Uint8Array, extType: number, context: ContextType): unknown;\n};\n\nexport class ExtensionCodec<ContextType = undefined> implements ExtensionCodecType<ContextType> {\n public static readonly defaultCodec: ExtensionCodecType<undefined> = new ExtensionCodec();\n\n // ensures ExtensionCodecType<X> matches ExtensionCodec<X>\n // this will make type errors a lot more clear\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __brand?: ContextType;\n\n // built-in extensions\n private readonly builtInEncoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n private readonly builtInDecoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n // custom extensions\n private readonly encoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n private readonly decoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n public constructor() {\n this.register(timestampExtension);\n }\n\n public register({\n type,\n encode,\n decode,\n }: {\n type: number;\n encode: ExtensionEncoderType<ContextType>;\n decode: ExtensionDecoderType<ContextType>;\n }): void {\n if (type >= 0) {\n // custom extensions\n this.encoders[type] = encode;\n this.decoders[type] = decode;\n } else {\n // built-in extensions\n const index = 1 + type;\n this.builtInEncoders[index] = encode;\n this.builtInDecoders[index] = decode;\n }\n }\n\n public tryToEncode(object: unknown, context: ContextType): ExtData | null {\n // built-in extensions\n for (let i = 0; i < this.builtInEncoders.length; i++) {\n const encodeExt = this.builtInEncoders[i];\n if (encodeExt != null) {\n const data = encodeExt(object, context);\n if (data != null) {\n const type = -1 - i;\n return new ExtData(type, data);\n }\n }\n }\n\n // custom extensions\n for (let i = 0; i < this.encoders.length; i++) {\n const encodeExt = this.encoders[i];\n if (encodeExt != null) {\n const data = encodeExt(object, context);\n if (data != null) {\n const type = i;\n return new ExtData(type, data);\n }\n }\n }\n\n if (object instanceof ExtData) {\n // to keep ExtData as is\n return object;\n }\n return null;\n }\n\n public decode(data: Uint8Array, type: number, context: ContextType): unknown {\n const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];\n if (decodeExt) {\n return decodeExt(data, type, context);\n } else {\n // decode() does not fail, returns ExtData instead.\n return new ExtData(type, data);\n }\n }\n}\n","export function ensureUint8Array(buffer: ArrayLike<number> | Uint8Array | ArrayBufferView | ArrayBuffer): Uint8Array {\n if (buffer instanceof Uint8Array) {\n return buffer;\n } else if (ArrayBuffer.isView(buffer)) {\n return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n } else if (buffer instanceof ArrayBuffer) {\n return new Uint8Array(buffer);\n } else {\n // ArrayLike<number>\n return Uint8Array.from(buffer);\n }\n}\n\nexport function createDataView(buffer: ArrayLike<number> | ArrayBufferView | ArrayBuffer): DataView {\n if (buffer instanceof ArrayBuffer) {\n return new DataView(buffer);\n }\n\n const bufferView = ensureUint8Array(buffer);\n return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);\n}\n","import { utf8EncodeJs, utf8Count, TEXT_ENCODER_THRESHOLD, utf8EncodeTE } from \"./utils/utf8\";\nimport { ExtensionCodec, ExtensionCodecType } from \"./ExtensionCodec\";\nimport { setInt64, setUint64 } from \"./utils/int\";\nimport { ensureUint8Array } from \"./utils/typedArrays\";\nimport type { ExtData } from \"./ExtData\";\n\nexport const DEFAULT_MAX_DEPTH = 100;\nexport const DEFAULT_INITIAL_BUFFER_SIZE = 2048;\n\nexport class Encoder<ContextType = undefined> {\n private pos = 0;\n private view = new DataView(new ArrayBuffer(this.initialBufferSize));\n private bytes = new Uint8Array(this.view.buffer);\n\n public constructor(\n private readonly extensionCodec: ExtensionCodecType<ContextType> = ExtensionCodec.defaultCodec as any,\n private readonly context: ContextType = undefined as any,\n private readonly maxDepth = DEFAULT_MAX_DEPTH,\n private readonly initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE,\n private readonly sortKeys = false,\n private readonly forceFloat32 = false,\n private readonly ignoreUndefined = false,\n private readonly forceIntegerToFloat = false,\n ) {}\n\n private reinitializeState() {\n this.pos = 0;\n }\n\n /**\n * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.\n *\n * @returns Encodes the object and returns a shared reference the encoder's internal buffer.\n */\n public encodeSharedRef(object: unknown): Uint8Array {\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.subarray(0, this.pos);\n }\n\n /**\n * @returns Encodes the object and returns a copy of the encoder's internal buffer.\n */\n public encode(object: unknown): Uint8Array {\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.slice(0, this.pos);\n }\n\n private doEncode(object: unknown, depth: number): void {\n if (depth > this.maxDepth) {\n throw new Error(`Too deep objects in depth ${depth}`);\n }\n\n if (object == null) {\n this.encodeNil();\n } else if (typeof object === \"boolean\") {\n this.encodeBoolean(object);\n } else if (typeof object === \"number\") {\n this.encodeNumber(object);\n } else if (typeof object === \"string\") {\n this.encodeString(object);\n } else {\n this.encodeObject(object, depth);\n }\n }\n\n private ensureBufferSizeToWrite(sizeToWrite: number) {\n const requiredSize = this.pos + sizeToWrite;\n\n if (this.view.byteLength < requiredSize) {\n this.resizeBuffer(requiredSize * 2);\n }\n }\n\n private resizeBuffer(newSize: number) {\n const newBuffer = new ArrayBuffer(newSize);\n const newBytes = new Uint8Array(newBuffer);\n const newView = new DataView(newBuffer);\n\n newBytes.set(this.bytes);\n\n this.view = newView;\n this.bytes = newBytes;\n }\n\n private encodeNil() {\n this.writeU8(0xc0);\n }\n\n private encodeBoolean(object: boolean) {\n if (object === false) {\n this.writeU8(0xc2);\n } else {\n this.writeU8(0xc3);\n }\n }\n private encodeNumber(object: number) {\n if (Number.isSafeInteger(object) && !this.forceIntegerToFloat) {\n if (object >= 0) {\n if (object < 0x80) {\n // positive fixint\n this.writeU8(object);\n } else if (object < 0x100) {\n // uint 8\n this.writeU8(0xcc);\n this.writeU8(object);\n } else if (object < 0x10000) {\n // uint 16\n this.writeU8(0xcd);\n this.writeU16(object);\n } else if (object < 0x100000000) {\n // uint 32\n this.writeU8(0xce);\n this.writeU32(object);\n } else {\n // uint 64\n this.writeU8(0xcf);\n this.writeU64(object);\n }\n } else {\n if (object >= -0x20) {\n // negative fixint\n this.writeU8(0xe0 | (object + 0x20));\n } else if (object >= -0x80) {\n // int 8\n this.writeU8(0xd0);\n this.writeI8(object);\n } else if (object >= -0x8000) {\n // int 16\n this.writeU8(0xd1);\n this.writeI16(object);\n } else if (object >= -0x80000000) {\n // int 32\n this.writeU8(0xd2);\n this.writeI32(object);\n } else {\n // int 64\n this.writeU8(0xd3);\n this.writeI64(object);\n }\n }\n } else {\n // non-integer numbers\n if (this.forceFloat32) {\n // float 32\n this.writeU8(0xca);\n this.writeF32(object);\n } else {\n // float 64\n this.writeU8(0xcb);\n this.writeF64(object);\n }\n }\n }\n\n private writeStringHeader(byteLength: number) {\n if (byteLength < 32) {\n // fixstr\n this.writeU8(0xa0 + byteLength);\n } else if (byteLength < 0x100) {\n // str 8\n this.writeU8(0xd9);\n this.writeU8(byteLength);\n } else if (byteLength < 0x10000) {\n // str 16\n this.writeU8(0xda);\n this.writeU16(byteLength);\n } else if (byteLength < 0x100000000) {\n // str 32\n this.writeU8(0xdb);\n this.writeU32(byteLength);\n } else {\n throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);\n }\n }\n\n private encodeString(object: string) {\n const maxHeaderSize = 1 + 4;\n const strLength = object.length;\n\n if (strLength > TEXT_ENCODER_THRESHOLD) {\n const byteLength = utf8Count(object);\n this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n this.writeStringHeader(byteLength);\n utf8EncodeTE(object, this.bytes, this.pos);\n this.pos += byteLength;\n } else {\n const byteLength = utf8Count(object);\n this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n this.writeStringHeader(byteLength);\n utf8EncodeJs(object, this.bytes, this.pos);\n this.pos += byteLength;\n }\n }\n\n private encodeObject(object: unknown, depth: number) {\n // try to encode objects with custom codec first of non-primitives\n const ext = this.extensionCodec.tryToEncode(object, this.context);\n if (ext != null) {\n this.encodeExtension(ext);\n } else if (Array.isArray(object)) {\n this.encodeArray(object, depth);\n } else if (ArrayBuffer.isView(object)) {\n this.encodeBinary(object);\n } else if (typeof object === \"object\") {\n this.encodeMap(object as Record<string, unknown>, depth);\n } else {\n // symbol, function and other special object come here unless extensionCodec handles them.\n throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);\n }\n }\n\n private encodeBinary(object: ArrayBufferView) {\n const size = object.byteLength;\n if (size < 0x100) {\n // bin 8\n this.writeU8(0xc4);\n this.writeU8(size);\n } else if (size < 0x10000) {\n // bin 16\n this.writeU8(0xc5);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // bin 32\n this.writeU8(0xc6);\n this.writeU32(size);\n } else {\n throw new Error(`Too large binary: ${size}`);\n }\n const bytes = ensureUint8Array(object);\n this.writeU8a(bytes);\n }\n\n private encodeArray(object: Array<unknown>, depth: number) {\n const size = object.length;\n if (size < 16) {\n // fixarray\n this.writeU8(0x90 + size);\n } else if (size < 0x10000) {\n // array 16\n this.writeU8(0xdc);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // array 32\n this.writeU8(0xdd);\n this.writeU32(size);\n } else {\n throw new Error(`Too large array: ${size}`);\n }\n for (const item of object) {\n this.doEncode(item, depth + 1);\n }\n }\n\n private countWithoutUndefined(object: Record<string, unknown>, keys: ReadonlyArray<string>): number {\n let count = 0;\n\n for (const key of keys) {\n if (object[key] !== undefined) {\n count++;\n }\n }\n\n return count;\n }\n\n private encodeMap(object: Record<string, unknown>, depth: number) {\n const keys = Object.keys(object);\n if (this.sortKeys) {\n keys.sort();\n }\n\n const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;\n\n if (size < 16) {\n // fixmap\n this.writeU8(0x80 + size);\n } else if (size < 0x10000) {\n // map 16\n this.writeU8(0xde);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // map 32\n this.writeU8(0xdf);\n this.writeU32(size);\n } else {\n throw new Error(`Too large map object: ${size}`);\n }\n\n for (const key of keys) {\n const value = object[key];\n\n if (!(this.ignoreUndefined && value === undefined)) {\n this.encodeString(key);\n this.doEncode(value, depth + 1);\n }\n }\n }\n\n private encodeExtension(ext: ExtData) {\n const size = ext.data.length;\n if (size === 1) {\n // fixext 1\n this.writeU8(0xd4);\n } else if (size === 2) {\n // fixext 2\n this.writeU8(0xd5);\n } else if (size === 4) {\n // fixext 4\n this.writeU8(0xd6);\n } else if (size === 8) {\n // fixext 8\n this.writeU8(0xd7);\n } else if (size === 16) {\n // fixext 16\n this.writeU8(0xd8);\n } else if (size < 0x100) {\n // ext 8\n this.writeU8(0xc7);\n this.writeU8(size);\n } else if (size < 0x10000) {\n // ext 16\n this.writeU8(0xc8);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // ext 32\n this.writeU8(0xc9);\n this.writeU32(size);\n } else {\n throw new Error(`Too large extension object: ${size}`);\n }\n this.writeI8(ext.type);\n this.writeU8a(ext.data);\n }\n\n private writeU8(value: number) {\n this.ensureBufferSizeToWrite(1);\n\n this.view.setUint8(this.pos, value);\n this.pos++;\n }\n\n private writeU8a(values: ArrayLike<number>) {\n const size = values.length;\n this.ensureBufferSizeToWrite(size);\n\n this.bytes.set(values, this.pos);\n this.pos += size;\n }\n\n private writeI8(value: number) {\n this.ensureBufferSizeToWrite(1);\n\n this.view.setInt8(this.pos, value);\n this.pos++;\n }\n\n private writeU16(value: number) {\n this.ensureBufferSizeToWrite(2);\n\n this.view.setUint16(this.pos, value);\n this.pos += 2;\n }\n\n private writeI16(value: number) {\n this.ensureBufferSizeToWrite(2);\n\n this.view.setInt16(this.pos, value);\n this.pos += 2;\n }\n\n private writeU32(value: number) {\n this.ensureBufferSizeToWrite(4);\n\n this.view.setUint32(this.pos, value);\n this.pos += 4;\n }\n\n private writeI32(value: number) {\n this.ensureBufferSizeToWrite(4);\n\n this.view.setInt32(this.pos, value);\n this.pos += 4;\n }\n\n private writeF32(value: number) {\n this.ensureBufferSizeToWrite(4);\n this.view.setFloat32(this.pos, value);\n this.pos += 4;\n }\n\n private writeF64(value: number) {\n this.ensureBufferSizeToWrite(8);\n this.view.setFloat64(this.pos, value);\n this.pos += 8;\n }\n\n private writeU64(value: number) {\n this.ensureBufferSizeToWrite(8);\n\n setUint64(this.view, this.pos, value);\n this.pos += 8;\n }\n\n private writeI64(value: number) {\n this.ensureBufferSizeToWrite(8);\n\n setInt64(this.view, this.pos, value);\n this.pos += 8;\n }\n}\n","export function prettyByte(byte: number): string {\n return `${byte < 0 ? \"-\" : \"\"}0x${Math.abs(byte).toString(16).padStart(2, \"0\")}`;\n}\n","import { utf8DecodeJs } from \"./utils/utf8\";\n\nconst DEFAULT_MAX_KEY_LENGTH = 16;\nconst DEFAULT_MAX_LENGTH_PER_KEY = 16;\n\nexport interface KeyDecoder {\n canBeCached(byteLength: number): boolean;\n decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string;\n}\ninterface KeyCacheRecord {\n readonly bytes: Uint8Array;\n readonly str: string;\n}\n\nexport class CachedKeyDecoder implements KeyDecoder {\n hit = 0;\n miss = 0;\n private readonly caches: Array<Array<KeyCacheRecord>>;\n\n constructor(readonly maxKeyLength = DEFAULT_MAX_KEY_LENGTH, readonly maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {\n // avoid `new Array(N)`, which makes a sparse array,\n // because a sparse array is typically slower than a non-sparse array.\n this.caches = [];\n for (let i = 0; i < this.maxKeyLength; i++) {\n this.caches.push([]);\n }\n }\n\n public canBeCached(byteLength: number): boolean {\n return byteLength > 0 && byteLength <= this.maxKeyLength;\n }\n\n private find(bytes: Uint8Array, inputOffset: number, byteLength: number): string | null {\n const records = this.caches[byteLength - 1]!;\n\n FIND_CHUNK: for (const record of records) {\n const recordBytes = record.bytes;\n\n for (let j = 0; j < byteLength; j++) {\n if (recordBytes[j] !== bytes[inputOffset + j]) {\n continue FIND_CHUNK;\n }\n }\n return record.str;\n }\n return null;\n }\n\n private store(bytes: Uint8Array, value: string) {\n const records = this.caches[bytes.length - 1]!;\n const record: KeyCacheRecord = { bytes, str: value };\n\n if (records.length >= this.maxLengthPerKey) {\n // `records` are full!\n // Set `record` to an arbitrary position.\n records[(Math.random() * records.length) | 0] = record;\n } else {\n records.push(record);\n }\n }\n\n public decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n const cachedValue = this.find(bytes, inputOffset, byteLength);\n if (cachedValue != null) {\n this.hit++;\n return cachedValue;\n }\n this.miss++;\n\n const str = utf8DecodeJs(bytes, inputOffset, byteLength);\n // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.\n const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);\n this.store(slicedCopyOfBytes, str);\n return str;\n }\n}\n","import { prettyByte } from \"./utils/prettyByte\";\nimport { ExtensionCodec, ExtensionCodecType } from \"./ExtensionCodec\";\nimport { getInt64, getUint64, UINT32_MAX } from \"./utils/int\";\nimport { utf8DecodeJs, TEXT_DECODER_THRESHOLD, utf8DecodeTD } from \"./utils/utf8\";\nimport { createDataView, ensureUint8Array } from \"./utils/typedArrays\";\nimport { CachedKeyDecoder, KeyDecoder } from \"./CachedKeyDecoder\";\nimport { DecodeError } from \"./DecodeError\";\n\nconst enum State {\n ARRAY,\n MAP_KEY,\n MAP_VALUE,\n}\n\ntype MapKeyType = string | number;\n\nconst isValidMapKeyType = (key: unknown): key is MapKeyType => {\n const keyType = typeof key;\n\n return keyType === \"string\" || keyType === \"number\";\n};\n\ntype StackMapState = {\n type: State.MAP_KEY | State.MAP_VALUE;\n size: number;\n key: MapKeyType | null;\n readCount: number;\n map: Record<string, unknown>;\n};\n\ntype StackArrayState = {\n type: State.ARRAY;\n size: number;\n array: Array<unknown>;\n position: number;\n};\n\ntype StackState = StackArrayState | StackMapState;\n\nconst HEAD_BYTE_REQUIRED = -1;\n\nconst EMPTY_VIEW = new DataView(new ArrayBuffer(0));\nconst EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);\n\n// IE11: Hack to support IE11.\n// IE11: Drop this hack and just use RangeError when IE11 is obsolete.\nexport const DataViewIndexOutOfBoundsError: typeof Error = (() => {\n try {\n // IE11: The spec says it should throw RangeError,\n // IE11: but in IE11 it throws TypeError.\n EMPTY_VIEW.getInt8(0);\n } catch (e: any) {\n return e.constructor;\n }\n throw new Error(\"never reached\");\n})();\n\nconst MORE_DATA = new DataViewIndexOutOfBoundsError(\"Insufficient data\");\n\nconst sharedCachedKeyDecoder = new CachedKeyDecoder();\n\nexport class Decoder<ContextType = undefined> {\n private totalPos = 0;\n private pos = 0;\n\n private view = EMPTY_VIEW;\n private bytes = EMPTY_BYTES;\n private headByte = HEAD_BYTE_REQUIRED;\n private readonly stack: Array<StackState> = [];\n\n public constructor(\n private readonly extensionCodec: ExtensionCodecType<ContextType> = ExtensionCodec.defaultCodec as any,\n private readonly context: ContextType = undefined as any,\n private readonly maxStrLength = UINT32_MAX,\n private readonly maxBinLength = UINT32_MAX,\n private readonly maxArrayLength = UINT32_MAX,\n private readonly maxMapLength = UINT32_MAX,\n private readonly maxExtLength = UINT32_MAX,\n private readonly keyDecoder: KeyDecoder | null = sharedCachedKeyDecoder,\n ) {}\n\n private reinitializeState() {\n this.totalPos = 0;\n this.headByte = HEAD_BYTE_REQUIRED;\n this.stack.length = 0;\n\n // view, bytes, and pos will be re-initialized in setBuffer()\n }\n\n private setBuffer(buffer: ArrayLike<number> | BufferSource): void {\n this.bytes = ensureUint8Array(buffer);\n this.view = createDataView(this.bytes);\n this.pos = 0;\n }\n\n private appendBuffer(buffer: ArrayLike<number> | BufferSource) {\n if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {\n this.setBuffer(buffer);\n } else {\n const remainingData = this.bytes.subarray(this.pos);\n const newData = ensureUint8Array(buffer);\n\n // concat remainingData + newData\n const newBuffer = new Uint8Array(remainingData.length + newData.length);\n newBuffer.set(remainingData);\n newBuffer.set(newData, remainingData.length);\n this.setBuffer(newBuffer);\n }\n }\n\n private hasRemaining(size: number) {\n return this.view.byteLength - this.pos >= size;\n }\n\n private createExtraByteError(posToShow: number): Error {\n const { view, pos } = this;\n return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`);\n }\n\n /**\n * @throws {@link DecodeError}\n * @throws {@link RangeError}\n */\n public decode(buffer: ArrayLike<number> | BufferSource): unknown {\n this.reinitializeState();\n this.setBuffer(buffer);\n\n const object = this.doDecodeSync();\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.pos);\n }\n return object;\n }\n\n public *decodeMulti(buffer: ArrayLike<number> | BufferSource): Generator<unknown, void, unknown> {\n this.reinitializeState();\n this.setBuffer(buffer);\n\n while (this.hasRemaining(1)) {\n yield this.doDecodeSync();\n }\n }\n\n public async decodeAsync(stream: AsyncIterable<ArrayLike<number> | BufferSource>): Promise<unknown> {\n let decoded = false;\n let object: unknown;\n for await (const buffer of stream) {\n if (decoded) {\n throw this.createExtraByteError(this.totalPos);\n }\n\n this.appendBuffer(buffer);\n\n try {\n object = this.doDecodeSync();\n decoded = true;\n } catch (e) {\n if (!(e instanceof DataViewIndexOutOfBoundsError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n }\n\n if (decoded) {\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.totalPos);\n }\n return object;\n }\n\n const { headByte, pos, totalPos } = this;\n throw new RangeError(\n `Insufficient data in parsing ${prettyByte(headByte)} at ${totalPos} (${pos} in the current buffer)`,\n );\n }\n\n public decodeArrayStream(\n stream: AsyncIterable<ArrayLike<number> | BufferSource>,\n ): AsyncGenerator<unknown, void, unknown> {\n return this.decodeMultiAsync(stream, true);\n }\n\n public decodeStream(stream: AsyncIterable<ArrayLike<number> | BufferSource>): AsyncGenerator<unknown, void, unknown> {\n return this.decodeMultiAsync(stream, false);\n }\n\n private async *decodeMultiAsync(stream: AsyncIterable<ArrayLike<number> | BufferSource>, isArray: boolean) {\n let isArrayHeaderRequired = isArray;\n let arrayItemsLeft = -1;\n\n for await (const buffer of stream) {\n if (isArray && arrayItemsLeft === 0) {\n throw this.createExtraByteError(this.totalPos);\n }\n\n this.appendBuffer(buffer);\n\n if (isArrayHeaderRequired) {\n arrayItemsLeft = this.readArraySize();\n isArrayHeaderRequired = false;\n this.complete();\n }\n\n try {\n while (true) {\n yield this.doDecodeSync();\n if (--arrayItemsLeft === 0) {\n break;\n }\n }\n } catch (e) {\n if (!(e instanceof DataViewIndexOutOfBoundsError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n }\n }\n\n private doDecodeSync(): unknown {\n DECODE: while (true) {\n const headByte = this.readHeadByte();\n let object: unknown;\n\n if (headByte >= 0xe0) {\n // negative fixint (111x xxxx) 0xe0 - 0xff\n object = headByte - 0x100;\n } else if (headByte < 0xc0) {\n if (headByte < 0x80) {\n // positive fixint (0xxx xxxx) 0x00 - 0x7f\n object = headByte;\n } else if (headByte < 0x90) {\n // fixmap (1000 xxxx) 0x80 - 0x8f\n const size = headByte - 0x80;\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte < 0xa0) {\n // fixarray (1001 xxxx) 0x90 - 0x9f\n const size = headByte - 0x90;\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else {\n // fixstr (101x xxxx) 0xa0 - 0xbf\n const byteLength = headByte - 0xa0;\n object = this.decodeUtf8String(byteLength, 0);\n }\n } else if (headByte === 0xc0) {\n // nil\n object = null;\n } else if (headByte === 0xc2) {\n // false\n object = false;\n } else if (headByte === 0xc3) {\n // true\n object = true;\n } else if (headByte === 0xca) {\n // float 32\n object = this.readF32();\n } else if (headByte === 0xcb) {\n // float 64\n object = this.readF64();\n } else if (headByte === 0xcc) {\n // uint 8\n object = this.readU8();\n } else if (headByte === 0xcd) {\n // uint 16\n object = this.readU16();\n } else if (headByte === 0xce) {\n // uint 32\n object = this.readU32();\n } else if (headByte === 0xcf) {\n // uint 64\n object = this.readU64();\n } else if (headByte === 0xd0) {\n // int 8\n object = this.readI8();\n } else if (headByte === 0xd1) {\n // int 16\n object = this.readI16();\n } else if (headByte === 0xd2) {\n // int 32\n object = this.readI32();\n } else if (headByte === 0xd3) {\n // int 64\n object = this.readI64();\n } else if (headByte === 0xd9) {\n // str 8\n const byteLength = this.lookU8();\n object = this.decodeUtf8String(byteLength, 1);\n } else if (headByte === 0xda) {\n // str 16\n const byteLength = this.lookU16();\n object = this.decodeUtf8String(byteLength, 2);\n } else if (headByte === 0xdb) {\n // str 32\n const byteLength = this.lookU32();\n object = this.decodeUtf8String(byteLength, 4);\n } else if (headByte === 0xdc) {\n // array 16\n const size = this.readU16();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else if (headByte === 0xdd) {\n // array 32\n const size = this.readU32();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else if (headByte === 0xde) {\n // map 16\n const size = this.readU16();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte === 0xdf) {\n // map 32\n const size = this.readU32();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte === 0xc4) {\n // bin 8\n const size = this.lookU8();\n object = this.decodeBinary(size, 1);\n } else if (headByte === 0xc5) {\n // bin 16\n const size = this.lookU16();\n object = this.decodeBinary(size, 2);\n } else if (headByte === 0xc6) {\n // bin 32\n const size = this.lookU32();\n object = this.decodeBinary(size, 4);\n } else if (headByte === 0xd4) {\n // fixext 1\n object = this.decodeExtension(1, 0);\n } else if (headByte === 0xd5) {\n // fixext 2\n object = this.decodeExtension(2, 0);\n } else if (headByte === 0xd6) {\n // fixext 4\n object = this.decodeExtension(4, 0);\n } else if (headByte === 0xd7) {\n // fixext 8\n object = this.decodeExtension(8, 0);\n } else if (headByte === 0xd8) {\n // fixext 16\n object = this.decodeExtension(16, 0);\n } else if (headByte === 0xc7) {\n // ext 8\n const size = this.lookU8();\n object = this.decodeExtension(size, 1);\n } else if (headByte === 0xc8) {\n // ext 16\n const size = this.lookU16();\n object = this.decodeExtension(size, 2);\n } else if (headByte === 0xc9) {\n // ext 32\n const size = this.lookU32();\n object = this.decodeExtension(size, 4);\n } else {\n throw new DecodeError(`Unrecognized type byte: ${prettyByte(headByte)}`);\n }\n\n this.complete();\n\n const stack = this.stack;\n while (stack.length > 0) {\n // arrays and maps\n const state = stack[stack.length - 1]!;\n if (state.type === State.ARRAY) {\n state.array[state.position] = object;\n state.position++;\n if (state.position === state.size) {\n stack.pop();\n object = state.array;\n } else {\n continue DECODE;\n }\n } else if (state.type === State.MAP_KEY) {\n if (!isValidMapKeyType(object)) {\n throw new DecodeError(\"The type of key must be string or number but \" + typeof object);\n }\n if (object === \"__proto__\") {\n throw new DecodeError(\"The key __proto__ is not allowed\");\n }\n\n state.key = object;\n state.type = State.MAP_VALUE;\n continue DECODE;\n } else {\n // it must be `state.type === State.MAP_VALUE` here\n\n state.map[state.key!] = object;\n state.readCount++;\n\n if (state.readCount === state.size) {\n stack.pop();\n object = state.map;\n } else {\n state.key = null;\n state.type = State.MAP_KEY;\n continue DECODE;\n }\n }\n }\n\n return object;\n }\n }\n\n private readHeadByte(): number {\n if (this.headByte === HEAD_BYTE_REQUIRED) {\n this.headByte = this.readU8();\n // console.log(\"headByte\", prettyByte(this.headByte));\n }\n\n return this.headByte;\n }\n\n private complete(): void {\n this.headByte = HEAD_BYTE_REQUIRED;\n }\n\n private readArraySize(): number {\n const headByte = this.readHeadByte();\n\n switch (headByte) {\n case 0xdc:\n return this.readU16();\n case 0xdd:\n return this.readU32();\n default: {\n if (headByte < 0xa0) {\n return headByte - 0x90;\n } else {\n throw new DecodeError(`Unrecognized array type byte: ${prettyByte(headByte)}`);\n }\n }\n }\n }\n\n private pushMapState(size: number) {\n if (size > this.maxMapLength) {\n throw new DecodeError(`Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`);\n }\n\n this.stack.push({\n type: State.MAP_KEY,\n size,\n key: null,\n readCount: 0,\n map: {},\n });\n }\n\n private pushArrayState(size: number) {\n if (size > this.maxArrayLength) {\n throw new DecodeError(`Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`);\n }\n\n this.stack.push({\n type: State.ARRAY,\n size,\n array: new Array<unknown>(size),\n position: 0,\n });\n }\n\n private decodeUtf8String(byteLength: number, headerOffset: number): string {\n if (byteLength > this.maxStrLength) {\n throw new DecodeError(\n `Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`,\n );\n }\n\n if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {\n throw MORE_DATA;\n }\n\n const offset = this.pos + headerOffset;\n let object: string;\n if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) {\n object = this.keyDecoder.decode(this.bytes, offset, byteLength);\n } else if (byteLength > TEXT_DECODER_THRESHOLD) {\n object = utf8DecodeTD(this.bytes, offset, byteLength);\n } else {\n object = utf8DecodeJs(this.bytes, offset, byteLength);\n }\n this.pos += headerOffset + byteLength;\n return object;\n }\n\n private stateIsMapKey(): boolean {\n if (this.stack.length > 0) {\n const state = this.stack[this.stack.length - 1]!;\n return state.type === State.MAP_KEY;\n }\n return false;\n }\n\n private decodeBinary(byteLength: number, headOffset: number): Uint8Array {\n if (byteLength > this.maxBinLength) {\n throw new DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`);\n }\n\n if (!this.hasRemaining(byteLength + headOffset)) {\n throw MORE_DATA;\n }\n\n const offset = this.pos + headOffset;\n const object = this.bytes.subarray(offset, offset + byteLength);\n this.pos += headOffset + byteLength;\n return object;\n }\n\n private decodeExtension(size: number, headOffset: number): unknown {\n if (size > this.maxExtLength) {\n throw new DecodeError(`Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`);\n }\n\n const extType = this.view.getInt8(this.pos + headOffset);\n const data = this.decodeBinary(size, headOffset + 1 /* extType */);\n return this.extensionCodec.decode(data, extType, this.context);\n }\n\n private lookU8() {\n return this.view.getUint8(this.pos);\n }\n\n private lookU16() {\n return this.view.getUint16(this.pos);\n }\n\n private lookU32() {\n return this.view.getUint32(this.pos);\n }\n\n private readU8(): number {\n const value = this.view.getUint8(this.pos);\n this.pos++;\n return value;\n }\n\n private readI8(): number {\n const value = this.view.getInt8(this.pos);\n this.pos++;\n return value;\n }\n\n private readU16(): number {\n const value = this.view.getUint16(this.pos);\n this.pos += 2;\n return value;\n }\n\n private readI16(): number {\n const value = this.view.getInt16(this.pos);\n this.pos += 2;\n return value;\n }\n\n private readU32(): number {\n const value = this.view.getUint32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readI32(): number {\n const value = this.view.getInt32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readU64(): number {\n const value = getUint64(this.view, this.pos);\n this.pos += 8;\n return value;\n }\n\n private readI64(): number {\n const value = getInt64(this.view, this.pos);\n this.pos += 8;\n return value;\n }\n\n private readF32() {\n const value = this.view.getFloat32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readF64() {\n const value = this.view.getFloat64(this.pos);\n this.pos += 8;\n return value;\n }\n}\n","import { Decoder } from \"./Decoder\";\nimport type { ExtensionCodecType } from \"./ExtensionCodec\";\nimport type { ContextOf, SplitUndefined } from \"./context\";\n\nexport type DecodeOptions<ContextType = undefined> = Readonly<\n Partial<{\n extensionCodec: ExtensionCodecType<ContextType>;\n\n /**\n * Maximum string length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxStrLength: number;\n /**\n * Maximum binary length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxBinLength: number;\n /**\n * Maximum array length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxArrayLength: number;\n /**\n * Maximum map length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxMapLength: number;\n /**\n * Maximum extension length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxExtLength: number;\n }>\n> &\n ContextOf<ContextType>;\n\nexport const defaultDecodeOptions: DecodeOptions = {};\n\n/**\n * It decodes a single MessagePack object in a buffer.\n *\n * This is a synchronous decoding function.\n * See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decode<ContextType = undefined>(\n buffer: ArrayLike<number> | BufferSource,\n options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): unknown {\n const decoder = new Decoder(\n options.extensionCodec,\n (options as typeof options & { context: any }).context,\n options.maxStrLength,\n options.maxBinLength,\n options.maxArrayLength,\n options.maxMapLength,\n options.maxExtLength,\n );\n return decoder.decode(buffer);\n}\n\n/**\n * It decodes multiple MessagePack objects in a buffer.\n * This is corresponding to {@link decodeMultiStream()}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMulti<ContextType = undefined>(\n buffer: ArrayLike<number> | BufferSource,\n options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): Generator<unknown, void, unknown> {\n const decoder = new Decoder(\n options.extensionCodec,\n (options as typeof options & { context: any }).context,\n options.maxStrLength,\n options.maxBinLength,\n options.maxArrayLength,\n options.maxMapLength,\n options.maxExtLength,\n );\n return decoder.decodeMulti(buffer);\n}\n","// utility for whatwg streams\n\n// The living standard of whatwg streams says\n// ReadableStream is also AsyncIterable, but\n// as of June 2019, no browser implements it.\n// See https://streams.spec.whatwg.org/ for details\nexport type ReadableStreamLike<T> = AsyncIterable<T> | ReadableStream<T>;\n\nexport function isAsyncIterable<T>(object: ReadableStreamLike<T>): object is AsyncIterable<T> {\n return (object as any)[Symbol.asyncIterator] != null;\n}\n\nfunction assertNonNull<T>(value: T | null | undefined): asserts value is T {\n if (value == null) {\n throw new Error(\"Assertion Failure: value must not be null nor undefined\");\n }\n}\n\nexport async function* asyncIterableFromStream<T>(stream: ReadableStream<T>): AsyncIterable<T> {\n const reader = stream.getReader();\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n assertNonNull(value);\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nexport function ensureAsyncIterable<T>(streamLike: ReadableStreamLike<T>): AsyncIterable<T> {\n if (isAsyncIterable(streamLike)) {\n return streamLike;\n } else {\n return asyncIterableFromStream(streamLike);\n }\n}\n","import { Decoder } from \"./Decoder\";\nimport { ensureAsyncIterable } from \"./utils/stream\";\nimport { defaultDecodeOptions } from \"./decode\";\nimport type { ReadableStreamLike } from \"./utils/stream\";\nimport type { DecodeOptions } from \"./decode\";\nimport type { SplitUndefined } from \"./context\";\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\n export async function decodeAsync<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): Promise<unknown> {\n const stream = ensureAsyncIterable(streamLike);\n\n const decoder = new Decoder(\n options.extensionCodec,\n (options as typeof options & { context: any }).context,\n options.maxStrLength,\n options.maxBinLength,\n options.maxArrayLength,\n options.maxMapLength,\n options.maxExtLength,\n );\n return decoder.decodeAsync(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\n export function decodeArrayStream<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): AsyncGenerator<unknown, void, unknown> {\n const stream = ensureAsyncIterable(streamLike);\n\n const decoder = new Decoder(\n options.extensionCodec,\n (options as typeof options & { context: any }).context,\n options.maxStrLength,\n options.maxBinLength,\n options.maxArrayLength,\n options.maxMapLength,\n options.maxExtLength,\n );\n\n return decoder.decodeArrayStream(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMultiStream<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): AsyncGenerator<unknown, void, unknown> {\n const stream = ensureAsyncIterable(streamLike);\n\n const decoder = new Decoder(\n options.extensionCodec,\n (options as typeof options & { context: any }).context,\n options.maxStrLength,\n options.maxBinLength,\n options.maxArrayLength,\n options.maxMapLength,\n options.maxExtLength,\n );\n\n return decoder.decodeStream(stream);\n}\n\n/**\n * @deprecated Use {@link decodeMultiStream()} instead.\n */\nexport function decodeStream<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): AsyncGenerator<unknown, void, unknown> {\n return decodeMultiStream(streamLike, options);\n}\n","const LOG_PREFIX = \"Dendri: \";\n\n/*\nPrints log messages depending on the debug level passed in. Defaults to 0.\n0 Prints no logs.\n1 Prints only errors.\n2 Prints errors and warnings.\n3 Prints all logs.\n*/\nexport enum LogLevel {\n\t/**\n\t * Prints no logs.\n\t */\n\tDisabled,\n\t/**\n\t * Prints only errors.\n\t */\n\tErrors,\n\t/**\n\t * Prints errors and warnings.\n\t */\n\tWarnings,\n\t/**\n\t * Prints all logs.\n\t */\n\tAll,\n}\n\nclass Logger {\n\tprivate _logLevel = LogLevel.Disabled;\n\n\tget logLevel(): LogLevel {\n\t\treturn this._logLevel;\n\t}\n\n\tset logLevel(logLevel: LogLevel) {\n\t\tthis._logLevel = logLevel;\n\t}\n\n\tlog(...args: any[]) {\n\t\tif (this._logLevel >= LogLevel.All) {\n\t\t\tthis._print(LogLevel.All, ...args);\n\t\t}\n\t}\n\n\twarn(...args: any[]) {\n\t\tif (this._logLevel >= LogLevel.Warnings) {\n\t\t\tthis._print(LogLevel.Warnings, ...args);\n\t\t}\n\t}\n\n\terror(...args: any[]) {\n\t\tif (this._logLevel >= LogLevel.Errors) {\n\t\t\tthis._print(LogLevel.Errors, ...args);\n\t\t}\n\t}\n\n\tsetLogFunction(fn: (logLevel: LogLevel, ..._: any[]) => void): void {\n\t\tthis._print = fn;\n\t}\n\n\tprivate _print(logLevel: LogLevel, ...rest: any[]): void {\n\t\tconst copy = [LOG_PREFIX, ...rest];\n\n\t\tfor (const i in copy) {\n\t\t\tif (copy[i] instanceof Error) {\n\t\t\t\tcopy[i] = `(${copy[i].name}) ${copy[i].message}`;\n\t\t\t}\n\t\t}\n\n\t\tif (logLevel >= LogLevel.All) {\n\t\t\tconsole.log(...copy);\n\t\t} else if (logLevel >= LogLevel.Warnings) {\n\t\t\tconsole.warn(\"WARNING\", ...copy);\n\t\t} else if (logLevel >= LogLevel.Errors) {\n\t\t\tconsole.error(\"ERROR\", ...copy);\n\t\t}\n\t}\n}\n\nexport default new Logger();\n","import { EventEmitter } from \"eventemitter3\";\nimport logger from \"./logger\";\n\nexport interface EventsWithError<ErrorType extends string> {\n\terror: (error: DendriError<`${ErrorType}`>) => void;\n}\n\nexport class EventEmitterWithError<\n\tErrorType extends string,\n\tEvents extends EventsWithError<ErrorType>,\n> extends EventEmitter<Events, never> {\n\t/**\n\t * Emits a typed error message.\n\t *\n\t * @internal\n\t */\n\temitError(type: ErrorType, err: string | Error, retryable = false): void {\n\t\tlogger.error(\"Error:\", err);\n\n\t\tconst error = new DendriError<`${ErrorType}`>(`${type}`, err);\n\t\terror.retryable = retryable;\n\n\t\t// @ts-expect-error\n\t\tthis.emit(\"error\", error);\n\t}\n}\n/**\n * A DendriError is emitted whenever an error occurs.\n * It always has a `.type`, which can be used to identify the error.\n */\nexport class DendriError<T extends string> extends Error {\n\tpublic type: T;\n\n\t/** Whether the operation that caused this error can be retried. */\n\tpublic retryable: boolean;\n\n\t/** Structured context about the error. */\n\tpublic details?: Record<string, unknown>;\n\n\t/**\n\t * @internal\n\t */\n\tconstructor(type: T, err: Error | string) {\n\t\tif (typeof err === \"string\") {\n\t\t\tsuper(err);\n\t\t} else {\n\t\t\tsuper(err.message);\n\t\t\tthis.stack = err.stack;\n\t\t}\n\n\t\tthis.type = type;\n\t\tthis.retryable = false;\n\t}\n\n\t/** Set the retryable flag (fluent API). */\n\tsetRetryable(retryable: boolean): this {\n\t\tthis.retryable = retryable;\n\t\treturn this;\n\t}\n\n\t/** Set structured details (fluent API). */\n\tsetDetails(details: Record<string, unknown>): this {\n\t\tthis.details = details;\n\t\treturn this;\n\t}\n}\n","import type { ValidEventTypes } from \"eventemitter3\";\nimport type { Dendri } from \"./dendri\";\nimport { type DendriError, EventEmitterWithError, type EventsWithError } from \"./dendriError\";\nimport type { BaseConnectionErrorType, ConnectionType } from \"./enums\";\nimport type { ServerMessage } from \"./servermessage\";\n\nexport interface BaseConnectionEvents<ErrorType extends string = BaseConnectionErrorType>\n\textends EventsWithError<ErrorType> {\n\t/**\n\t * Emitted when either you or the remote peer closes the connection.\n\t *\n\t * ```ts\n\t * connection.on('close', () => { ... });\n\t * ```\n\t */\n\tclose: () => void;\n\t/**\n\t * ```ts\n\t * connection.on('error', (error) => { ... });\n\t * ```\n\t */\n\terror: (error: DendriError<`${ErrorType}`>) => void;\n\ticeStateChanged: (state: RTCIceConnectionState) => void;\n}\n\nexport abstract class BaseConnection<\n\tSubClassEvents extends ValidEventTypes,\n\tErrorType extends string = never,\n> extends EventEmitterWithError<\n\tErrorType | BaseConnectionErrorType,\n\tSubClassEvents & BaseConnectionEvents<BaseConnectionErrorType | ErrorType>\n> {\n\tprotected _open = false;\n\n\t/**\n\t * Any type of metadata associated with the connection,\n\t * passed in by whoever initiated the connection.\n\t */\n\treadonly metadata: any;\n\tconnectionId!: string;\n\n\tpeerConnection!: RTCPeerConnection | null;\n\tdataChannel: RTCDataChannel | null = null;\n\n\tabstract get type(): ConnectionType;\n\n\t/**\n\t * The optional label passed in or assigned by Dendri when the connection was initiated.\n\t */\n\tlabel!: string;\n\n\t/**\n\t * Whether the media connection is active (e.g. your call has been answered).\n\t * You can check this if you want to set a maximum wait time for a one-sided call.\n\t */\n\tget open() {\n\t\treturn this._open;\n\t}\n\n\tprotected constructor(\n\t\t/**\n\t\t * The ID of the peer on the other end of this connection.\n\t\t */\n\t\treadonly peer: string,\n\t\tpublic provider: Dendri | null,\n\t\treadonly options: any,\n\t) {\n\t\tsuper();\n\n\t\tthis.metadata = options.metadata;\n\t}\n\n\tabstract close(): void;\n\n\t/**\n\t * @internal\n\t */\n\tabstract handleMessage(message: ServerMessage): void;\n\n\t/**\n\t * Called by the Negotiator when the DataChannel is ready.\n\t * @internal\n\t * */\n\tabstract _initializeDataChannel(dc: RTCDataChannel): void;\n}\n","import type { ValidEventTypes } from \"eventemitter3\";\nimport type { BaseConnection, BaseConnectionEvents } from \"./baseconnection\";\nimport type { DataConnection } from \"./dataconnection/DataConnection\";\nimport {\n\tBaseConnectionErrorType,\n\tConnectionType,\n\tDendriErrorType,\n\tServerMessageType,\n} from \"./enums\";\nimport logger from \"./logger\";\nimport type { MediaConnection } from \"./mediaconnection\";\n\n/**\n * Manages all negotiations between Peers.\n */\nexport class Negotiator<\n\tEvents extends ValidEventTypes,\n\tT extends BaseConnection<Events | BaseConnectionEvents>,\n> {\n\tprivate _pendingCandidates: RTCIceCandidate[] = [];\n\tprivate _iceCandidateFilter: ((c: RTCIceCandidateInit) => boolean) | null = null;\n\n\tconstructor(readonly connection: T) {}\n\n\t/** Returns a PeerConnection object set up correctly (for data, media). */\n\tstartConnection(options: any) {\n\t\tconst peerConnection = this._startPeerConnection();\n\n\t\t// Set the connection's PC.\n\t\tthis.connection.peerConnection = peerConnection;\n\n\t\tif (this.connection.type === ConnectionType.Media && options._stream) {\n\t\t\tthis._addTracksToConnection(options._stream, peerConnection);\n\t\t\tthis._setCodecPreferences(peerConnection);\n\t\t}\n\n\t\t// What do we need to do now?\n\t\tif (options.originator) {\n\t\t\tconst dataConnection = this.connection;\n\n\t\t\tconst config: RTCDataChannelInit = { ordered: !!options.reliable };\n\n\t\t\tconst dataChannel = peerConnection.createDataChannel(dataConnection.label, config);\n\t\t\tdataConnection._initializeDataChannel(dataChannel);\n\n\t\t\tvoid this._makeOffer();\n\t\t} else {\n\t\t\tvoid this.handleSDP(\"OFFER\", options.sdp);\n\t\t}\n\t}\n\n\t/** Start a PC. */\n\tprivate _startPeerConnection(): RTCPeerConnection {\n\t\tlogger.log(\"Creating RTCPeerConnection.\");\n\n\t\tconst peerConnection = new RTCPeerConnection(this.connection.provider?.options.config);\n\n\t\t// H3: ICE candidate privacy filtering\n\t\tif (this.connection.provider?.options.ipPolicy === \"public\") {\n\t\t\tconst isPublicCandidate = (c: RTCIceCandidateInit) => {\n\t\t\t\tconst sdp = c.candidate ?? \"\";\n\t\t\t\treturn !sdp.includes(\"typ host\");\n\t\t\t};\n\t\t\tthis._iceCandidateFilter = isPublicCandidate;\n\t\t}\n\n\t\tthis._setupListeners(peerConnection);\n\n\t\treturn peerConnection;\n\t}\n\n\t/** Set up various WebRTC listeners. */\n\tprivate _setupListeners(peerConnection: RTCPeerConnection) {\n\t\tconst peerId = this.connection.peer;\n\t\tconst connectionId = this.connection.connectionId;\n\t\tconst connectionType = this.connection.type;\n\t\tconst provider = this.connection.provider!;\n\n\t\t// ICE CANDIDATES.\n\t\tlogger.log(\"Listening for ICE candidates.\");\n\n\t\tpeerConnection.onicecandidate = (evt) => {\n\t\t\tif (!evt.candidate?.candidate) return;\n\n\t\t\t// H3: Filter host candidates for IP privacy\n\t\t\tif (this._iceCandidateFilter && !this._iceCandidateFilter(evt.candidate)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogger.log(`Received ICE candidates for ${peerId}:`, evt.candidate);\n\n\t\t\tprovider.socket.send({\n\t\t\t\ttype: ServerMessageType.Candidate,\n\t\t\t\tpayload: {\n\t\t\t\t\tcandidate: evt.candidate,\n\t\t\t\t\ttype: connectionType,\n\t\t\t\t\tconnectionId: connectionId,\n\t\t\t\t},\n\t\t\t\tdst: peerId,\n\t\t\t});\n\t\t};\n\n\t\tpeerConnection.oniceconnectionstatechange = () => {\n\t\t\tswitch (peerConnection.iceConnectionState) {\n\t\t\t\tcase \"failed\":\n\t\t\t\t\tlogger.log(`iceConnectionState is failed, closing connections to ${peerId}`);\n\t\t\t\t\tthis.connection.emitError(\n\t\t\t\t\t\tBaseConnectionErrorType.NegotiationFailed,\n\t\t\t\t\t\t`Negotiation of connection to ${peerId} failed.`,\n\t\t\t\t\t);\n\t\t\t\t\tthis.connection.close();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"closed\":\n\t\t\t\t\tlogger.log(`iceConnectionState is closed, closing connections to ${peerId}`);\n\t\t\t\t\tthis.connection.emitError(\n\t\t\t\t\t\tBaseConnectionErrorType.ConnectionClosed,\n\t\t\t\t\t\t`Connection to ${peerId} closed.`,\n\t\t\t\t\t);\n\t\t\t\t\tthis.connection.close();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"disconnected\":\n\t\t\t\t\tlogger.log(`iceConnectionState changed to disconnected on the connection with ${peerId}`);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"completed\":\n\t\t\t\t\tpeerConnection.onicecandidate = () => {};\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tthis.connection.emit(\"iceStateChanged\", peerConnection.iceConnectionState);\n\t\t};\n\n\t\t// DATACONNECTION.\n\t\tlogger.log(\"Listening for data channel\");\n\t\t// Fired between offer and answer, so options should already be saved\n\t\t// in the options hash.\n\t\tpeerConnection.ondatachannel = (evt) => {\n\t\t\tlogger.log(\"Received data channel\");\n\n\t\t\tconst dataChannel = evt.channel;\n\t\t\tconst connection = provider.getConnection(peerId, connectionId);\n\n\t\t\tif (!connection) {\n\t\t\t\tlogger.warn(`Received data channel for non-existent connection ${connectionId}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconnection._initializeDataChannel(dataChannel);\n\t\t};\n\n\t\t// MEDIACONNECTION.\n\t\tlogger.log(\"Listening for remote stream\");\n\n\t\tpeerConnection.ontrack = (evt) => {\n\t\t\tlogger.log(\"Received remote stream\");\n\n\t\t\tconst stream = evt.streams[0];\n\t\t\tconst connection = provider.getConnection(peerId, connectionId);\n\n\t\t\tif (!connection) {\n\t\t\t\tlogger.warn(`Received remote stream for non-existent connection ${connectionId}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (connection.type === ConnectionType.Media) {\n\t\t\t\tconst mediaConnection = <MediaConnection>connection;\n\n\t\t\t\tthis._addStreamToMediaConnection(stream, mediaConnection);\n\t\t\t}\n\t\t};\n\t}\n\n\tcleanup(): void {\n\t\tlogger.log(`Cleaning up PeerConnection to ${this.connection.peer}`);\n\n\t\tconst peerConnection = this.connection.peerConnection;\n\n\t\tif (!peerConnection) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.connection.peerConnection = null;\n\t\tthis._pendingCandidates = [];\n\n\t\t//unsubscribe from all PeerConnection's events\n\t\tpeerConnection.onicecandidate =\n\t\t\tpeerConnection.oniceconnectionstatechange =\n\t\t\tpeerConnection.ondatachannel =\n\t\t\tpeerConnection.ontrack =\n\t\t\t\t() => {};\n\n\t\tconst peerConnectionNotClosed = peerConnection.signalingState !== \"closed\";\n\t\tlet dataChannelNotClosed = false;\n\n\t\tconst dataChannel = this.connection.dataChannel;\n\n\t\tif (dataChannel) {\n\t\t\tdataChannelNotClosed = !!dataChannel.readyState && dataChannel.readyState !== \"closed\";\n\t\t\tif (dataChannelNotClosed) {\n\t\t\t\tdataChannel.close();\n\t\t\t}\n\t\t}\n\n\t\tif (peerConnectionNotClosed || dataChannelNotClosed) {\n\t\t\tpeerConnection.close();\n\t\t}\n\t}\n\n\tprivate async _makeOffer(): Promise<void> {\n\t\tconst peerConnection = this.connection.peerConnection!;\n\t\tconst provider = this.connection.provider!;\n\n\t\ttry {\n\t\t\tconst offer = await peerConnection.createOffer(this.connection.options.constraints);\n\n\t\t\tif (!this.connection.peerConnection) {\n\t\t\t\tlogger.log(\"PeerConnection closed during createOffer\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogger.log(\"Created offer.\");\n\n\t\t\tif (\n\t\t\t\tthis.connection.options.sdpTransform &&\n\t\t\t\ttypeof this.connection.options.sdpTransform === \"function\"\n\t\t\t) {\n\t\t\t\toffer.sdp = this.connection.options.sdpTransform(offer.sdp) || offer.sdp;\n\t\t\t}\n\n\t\t\t// Apply H.264 SDP fallback for video (Safari compatibility)\n\t\t\tif (this.connection.type === ConnectionType.Media && offer.sdp) {\n\t\t\t\toffer.sdp = this._applyH264SdpFallback(offer.sdp, peerConnection);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait peerConnection.setLocalDescription(offer);\n\n\t\t\t\tif (!this.connection.peerConnection) {\n\t\t\t\t\tlogger.log(\"PeerConnection closed during setLocalDescription\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlogger.log(\"Set localDescription:\", offer, `for:${this.connection.peer}`);\n\n\t\t\t\tlet payload: any = {\n\t\t\t\t\tsdp: offer,\n\t\t\t\t\ttype: this.connection.type,\n\t\t\t\t\tconnectionId: this.connection.connectionId,\n\t\t\t\t\tmetadata: this.connection.metadata,\n\t\t\t\t};\n\n\t\t\t\tif (this.connection.type === ConnectionType.Data) {\n\t\t\t\t\tconst dataConnection = <DataConnection>(<unknown>this.connection);\n\n\t\t\t\t\tpayload = {\n\t\t\t\t\t\t...payload,\n\t\t\t\t\t\tlabel: dataConnection.label,\n\t\t\t\t\t\treliable: dataConnection.reliable,\n\t\t\t\t\t\tserialization: dataConnection.serialization,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tprovider.socket.send({\n\t\t\t\t\ttype: ServerMessageType.Offer,\n\t\t\t\t\tpayload,\n\t\t\t\t\tdst: this.connection.peer,\n\t\t\t\t});\n\t\t\t} catch (err: unknown) {\n\t\t\t\t// TODO: investigate why _makeOffer is being called from the answer\n\t\t\t\tif (\n\t\t\t\t\terr !==\n\t\t\t\t\t\"OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer\"\n\t\t\t\t) {\n\t\t\t\t\tprovider.emitError(DendriErrorType.WebRTC, err instanceof Error ? err : String(err));\n\t\t\t\t\tlogger.log(\"Failed to setLocalDescription, \", err);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err_1: unknown) {\n\t\t\tprovider.emitError(DendriErrorType.WebRTC, err_1 instanceof Error ? err_1 : String(err_1));\n\t\t\tlogger.log(\"Failed to createOffer, \", err_1);\n\t\t}\n\t}\n\n\tprivate async _makeAnswer(): Promise<void> {\n\t\tconst peerConnection = this.connection.peerConnection!;\n\t\tconst provider = this.connection.provider!;\n\n\t\ttry {\n\t\t\tconst answer = await peerConnection.createAnswer();\n\n\t\t\tif (!this.connection.peerConnection) {\n\t\t\t\tlogger.log(\"PeerConnection closed during createAnswer\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogger.log(\"Created answer.\");\n\n\t\t\tif (\n\t\t\t\tthis.connection.options.sdpTransform &&\n\t\t\t\ttypeof this.connection.options.sdpTransform === \"function\"\n\t\t\t) {\n\t\t\t\tanswer.sdp = this.connection.options.sdpTransform(answer.sdp) || answer.sdp;\n\t\t\t}\n\n\t\t\t// Apply H.264 SDP fallback for video (Safari compatibility)\n\t\t\tif (this.connection.type === ConnectionType.Media && answer.sdp) {\n\t\t\t\tanswer.sdp = this._applyH264SdpFallback(answer.sdp, peerConnection);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait peerConnection.setLocalDescription(answer);\n\n\t\t\t\tif (!this.connection.peerConnection) {\n\t\t\t\t\tlogger.log(\"PeerConnection closed during setLocalDescription\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlogger.log(`Set localDescription:`, answer, `for:${this.connection.peer}`);\n\n\t\t\t\tprovider.socket.send({\n\t\t\t\t\ttype: ServerMessageType.Answer,\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tsdp: answer,\n\t\t\t\t\t\ttype: this.connection.type,\n\t\t\t\t\t\tconnectionId: this.connection.connectionId,\n\t\t\t\t\t},\n\t\t\t\t\tdst: this.connection.peer,\n\t\t\t\t});\n\t\t\t} catch (err: unknown) {\n\t\t\t\tprovider.emitError(DendriErrorType.WebRTC, err instanceof Error ? err : String(err));\n\t\t\t\tlogger.log(\"Failed to setLocalDescription, \", err);\n\t\t\t}\n\t\t} catch (err_1: unknown) {\n\t\t\tprovider.emitError(DendriErrorType.WebRTC, err_1 instanceof Error ? err_1 : String(err_1));\n\t\t\tlogger.log(\"Failed to create answer, \", err_1);\n\t\t}\n\t}\n\n\t/** Handle an SDP. */\n\tasync handleSDP(type: string, sdp: any): Promise<void> {\n\t\tconst peerConnection = this.connection.peerConnection!;\n\t\tconst provider = this.connection.provider!;\n\n\t\tlogger.log(\"Setting remote description\", sdp);\n\n\t\ttry {\n\t\t\tawait peerConnection.setRemoteDescription(sdp);\n\n\t\t\tif (!this.connection.peerConnection) {\n\t\t\t\tlogger.log(\"PeerConnection closed during setRemoteDescription\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogger.log(`Set remoteDescription:${type} for:${this.connection.peer}`);\n\n\t\t\t// Flush any ICE candidates that arrived before remote description was set\n\t\t\tif (this._pendingCandidates.length > 0) {\n\t\t\t\tlogger.log(`Flushing ${this._pendingCandidates.length} pending ICE candidates`);\n\t\t\t\tconst candidates = this._pendingCandidates;\n\t\t\t\tthis._pendingCandidates = [];\n\t\t\t\tfor (const candidate of candidates) {\n\t\t\t\t\tawait this.handleCandidate(candidate);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (type === \"OFFER\") {\n\t\t\t\tawait this._makeAnswer();\n\t\t\t}\n\t\t} catch (err: unknown) {\n\t\t\tprovider.emitError(DendriErrorType.WebRTC, err instanceof Error ? err : String(err));\n\t\t\tlogger.log(\"Failed to setRemoteDescription, \", err);\n\t\t}\n\t}\n\n\t/** Handle a candidate. */\n\tasync handleCandidate(ice: RTCIceCandidate) {\n\t\tlogger.log(`handleCandidate:`, ice);\n\n\t\tconst peerConnection = this.connection.peerConnection;\n\n\t\tif (!peerConnection) {\n\t\t\tlogger.warn(`PeerConnection not set for ${this.connection.peer}, cannot add ICE candidate`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Queue candidates that arrive before remote description is set\n\t\tif (!peerConnection.remoteDescription) {\n\t\t\tlogger.log(`Queueing ICE candidate (no remote description yet)`);\n\t\t\tthis._pendingCandidates.push(ice);\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tawait peerConnection.addIceCandidate(ice);\n\t\t\tlogger.log(`Added ICE candidate for:${this.connection.peer}`);\n\t\t} catch (err: unknown) {\n\t\t\tthis.connection.provider?.emitError(\n\t\t\t\tDendriErrorType.WebRTC,\n\t\t\t\terr instanceof Error ? err : String(err),\n\t\t\t);\n\t\t\tlogger.log(\"Failed to handleCandidate, \", err);\n\t\t}\n\t}\n\n\t/**\n\t * Set codec preferences on all video transceivers to prioritize H.264.\n\t * Safari only supports H.264 for video, so this ensures cross-browser\n\t * compatibility when one peer is Safari and the other is Chrome/Firefox.\n\t */\n\tprivate _setCodecPreferences(pc: RTCPeerConnection): void {\n\t\tif (!pc.getTransceivers) return;\n\n\t\tfor (const transceiver of pc.getTransceivers()) {\n\t\t\tif (transceiver.sender?.track?.kind === \"video\") {\n\t\t\t\tconst codecs =\n\t\t\t\t\ttypeof RTCRtpReceiver !== \"undefined\"\n\t\t\t\t\t\t? RTCRtpReceiver.getCapabilities?.(\"video\")?.codecs\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (!codecs) continue;\n\n\t\t\t\tconst h264 = codecs.filter((c) => c.mimeType === \"video/H264\");\n\t\t\t\tconst others = codecs.filter((c) => c.mimeType !== \"video/H264\");\n\n\t\t\t\tif (h264.length > 0 && typeof transceiver.setCodecPreferences === \"function\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\ttransceiver.setCodecPreferences([...h264, ...others]);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// setCodecPreferences may throw if codecs are invalid\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * SDP fallback for browsers without setCodecPreferences support.\n\t * Reorders H.264 payload types to the front of the m=video line so that\n\t * H.264 is preferred during negotiation.\n\t */\n\t_preferH264InSdp(sdp: string): string {\n\t\tconst lines = sdp.split(\"\\r\\n\");\n\t\tconst result: string[] = [];\n\n\t\t// Collect H.264 payload types from a=rtpmap lines\n\t\tconst h264Payloads: string[] = [];\n\t\tfor (const line of lines) {\n\t\t\tif (line.includes(\"a=rtpmap:\") && line.toLowerCase().includes(\"h264\")) {\n\t\t\t\tconst match = line.match(/a=rtpmap:(\\d+)/);\n\t\t\t\tif (match) h264Payloads.push(match[1]);\n\t\t\t}\n\t\t}\n\n\t\tfor (const line of lines) {\n\t\t\tif (line.startsWith(\"m=video\") && h264Payloads.length > 0) {\n\t\t\t\tconst parts = line.split(\" \");\n\t\t\t\tconst prefix = parts.slice(0, 3).join(\" \");\n\t\t\t\tconst payloads = parts.slice(3);\n\t\t\t\tconst reordered = [...h264Payloads, ...payloads.filter((p) => !h264Payloads.includes(p))];\n\t\t\t\tresult.push(`${prefix} ${reordered.join(\" \")}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tresult.push(line);\n\t\t}\n\n\t\treturn result.join(\"\\r\\n\");\n\t}\n\n\t/**\n\t * Apply H.264 preference to SDP when setCodecPreferences is not available.\n\t * Returns the original SDP unchanged if setCodecPreferences was already applied.\n\t */\n\tprivate _applyH264SdpFallback(sdp: string, pc: RTCPeerConnection): string {\n\t\t// If setCodecPreferences is supported, the transceiver API already handled it\n\t\tconst hasSetCodecPreferences =\n\t\t\tpc.getTransceivers &&\n\t\t\tpc.getTransceivers().some((t) => typeof t.setCodecPreferences === \"function\");\n\n\t\tif (hasSetCodecPreferences) return sdp;\n\n\t\treturn this._preferH264InSdp(sdp);\n\t}\n\n\tprivate _addTracksToConnection(stream: MediaStream, peerConnection: RTCPeerConnection): void {\n\t\tlogger.log(`add tracks from stream ${stream.id} to peer connection`);\n\n\t\tif (!peerConnection.addTrack) {\n\t\t\tlogger.error(`Your browser doesn't support RTCPeerConnection#addTrack. Ignored.`);\n\t\t\treturn;\n\t\t}\n\n\t\tstream.getTracks().forEach((track) => {\n\t\t\tpeerConnection.addTrack(track, stream);\n\t\t});\n\t}\n\n\tprivate _addStreamToMediaConnection(stream: MediaStream, mediaConnection: MediaConnection): void {\n\t\tlogger.log(`add stream ${stream.id} to media connection ${mediaConnection.connectionId}`);\n\n\t\tmediaConnection.addStream(stream);\n\t}\n}\n","export const randomToken = () => Math.random().toString(36).slice(2);\n","import { BaseConnection, type BaseConnectionEvents } from \"../baseconnection\";\nimport type { Dendri } from \"../dendri\";\nimport type { EventsWithError } from \"../dendriError\";\nimport {\n\ttype BaseConnectionErrorType,\n\tConnectionType,\n\tDataConnectionErrorType,\n\tServerMessageType,\n} from \"../enums\";\nimport logger from \"../logger\";\nimport { Negotiator } from \"../negotiator\";\nimport type { ServerMessage } from \"../servermessage\";\nimport { randomToken } from \"../utils/randomToken\";\n\nexport interface DataConnectionEvents\n\textends EventsWithError<DataConnectionErrorType | BaseConnectionErrorType>,\n\t\tBaseConnectionEvents<DataConnectionErrorType | BaseConnectionErrorType> {\n\t/**\n\t * Emitted when data is received from the remote peer.\n\t */\n\tdata: (data: unknown) => void;\n\t/**\n\t * Emitted when the connection is established and ready-to-use.\n\t */\n\topen: () => void;\n}\n\n/**\n * Wraps a DataChannel between two Peers.\n */\nexport abstract class DataConnection extends BaseConnection<\n\tDataConnectionEvents,\n\tDataConnectionErrorType\n> {\n\tprotected static readonly ID_PREFIX = \"dc_\";\n\tprotected static readonly MAX_BUFFERED_AMOUNT = 8 * 1024 * 1024;\n\n\tprivate _negotiator: Negotiator<DataConnectionEvents, this> | null;\n\tabstract readonly serialization: string;\n\treadonly reliable: boolean;\n\n\tpublic get type() {\n\t\treturn ConnectionType.Data;\n\t}\n\n\tconstructor(peerId: string, provider: Dendri, options: any) {\n\t\tsuper(peerId, provider, options);\n\n\t\tthis.connectionId = this.options.connectionId || DataConnection.ID_PREFIX + randomToken();\n\n\t\tthis.label = this.options.label || this.connectionId;\n\t\tthis.reliable = !!this.options.reliable;\n\n\t\tthis._negotiator = new Negotiator(this);\n\n\t\tthis._negotiator.startConnection(\n\t\t\tthis.options._payload || {\n\t\t\t\toriginator: true,\n\t\t\t\treliable: this.reliable,\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Called by the Negotiator when the DataChannel is ready. */\n\toverride _initializeDataChannel(dc: RTCDataChannel): void {\n\t\tthis.dataChannel = dc;\n\n\t\tthis.dataChannel.onopen = () => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc connection success`);\n\t\t\tthis._open = true;\n\t\t\tthis._applyAdaptiveBuffer(dc);\n\t\t\tthis.emit(\"open\");\n\t\t};\n\n\t\tthis.dataChannel.onclose = () => {\n\t\t\tlogger.log(`DC#${this.connectionId} dc closed for:`, this.peer);\n\t\t\tthis.close();\n\t\t};\n\t}\n\n\tprivate _applyAdaptiveBuffer(dc: RTCDataChannel): void {\n\t\tconst pc = this.peerConnection;\n\t\tif (!pc || typeof (pc as any).getStats !== \"function\") return;\n\t\tpc.getStats()\n\t\t\t.then((stats: RTCStatsReport) => {\n\t\t\t\tlet rtt: number | null = null;\n\t\t\t\tstats.forEach((report: any) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\treport.type === \"candidate-pair\" &&\n\t\t\t\t\t\treport.state === \"succeeded\" &&\n\t\t\t\t\t\treport.currentRoundTripTime\n\t\t\t\t\t) {\n\t\t\t\t\t\trtt = report.currentRoundTripTime * 1000;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (rtt !== null) {\n\t\t\t\t\tconst bdp = 12.5 * 1024 * 1024 * (rtt / 1000);\n\t\t\t\t\tconst optimal = Math.max(1 * 1024 * 1024, Math.min(32 * 1024 * 1024, Math.ceil(bdp)));\n\t\t\t\t\tdc.bufferedAmountLowThreshold = optimal;\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch(() => {});\n\t}\n\n\t/**\n\t * Exposed functionality for users.\n\t */\n\n\tprivate _flushCloseTimeout: ReturnType<typeof setTimeout> | null = null;\n\n\t/** Allows user to close connection. */\n\tclose(options?: { flush?: boolean }): void {\n\t\tif (options?.flush) {\n\t\t\tthis.send({\n\t\t\t\t__peerData: {\n\t\t\t\t\ttype: \"close\",\n\t\t\t\t},\n\t\t\t});\n\t\t\t// Fallback timeout so close() is guaranteed even if flush hangs\n\t\t\tthis._flushCloseTimeout = setTimeout(() => {\n\t\t\t\tthis._flushCloseTimeout = null;\n\t\t\t\tthis.close();\n\t\t\t}, 5000);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._flushCloseTimeout) {\n\t\t\tclearTimeout(this._flushCloseTimeout);\n\t\t\tthis._flushCloseTimeout = null;\n\t\t}\n\n\t\tif (this._negotiator) {\n\t\t\tthis._negotiator.cleanup();\n\t\t\tthis._negotiator = null;\n\t\t}\n\n\t\tif (this.provider) {\n\t\t\tthis.provider._removeConnection(this);\n\n\t\t\tthis.provider = null;\n\t\t}\n\n\t\tif (this.dataChannel) {\n\t\t\tthis.dataChannel.onopen = null;\n\t\t\tthis.dataChannel.onmessage = null;\n\t\t\tthis.dataChannel.onclose = null;\n\t\t\tthis.dataChannel = null;\n\t\t}\n\n\t\tif (!this.open) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._open = false;\n\n\t\tsuper.emit(\"close\");\n\t\tthis.removeAllListeners();\n\t}\n\n\tprotected abstract _send(data: any, chunked: boolean): void | Promise<void>;\n\n\t/** Allows user to send data. */\n\tpublic send(data: any, chunked = false) {\n\t\tif (!this.open) {\n\t\t\tthis.emitError(\n\t\t\t\tDataConnectionErrorType.NotOpenYet,\n\t\t\t\t\"Connection is not open. You should listen for the `open` event before sending messages.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\treturn this._send(data, chunked);\n\t}\n\n\tasync handleMessage(message: ServerMessage) {\n\t\tconst payload = message.payload;\n\n\t\tswitch (message.type) {\n\t\t\tcase ServerMessageType.Answer:\n\t\t\t\tif (this._negotiator) {\n\t\t\t\t\tawait this._negotiator.handleSDP(message.type, payload.sdp);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase ServerMessageType.Candidate:\n\t\t\t\tif (this._negotiator) {\n\t\t\t\t\tawait this._negotiator.handleCandidate(payload.candidate);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlogger.warn(\"Unrecognized message type:\", message.type, \"from peer:\", this.peer);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n","import type { Dendri } from \"../../dendri\";\nimport logger from \"../../logger\";\nimport { DataConnection } from \"../DataConnection\";\n\nexport abstract class StreamConnection extends DataConnection {\n\tprivate _CHUNK_SIZE = 1024 * 8 * 4;\n\tprivate _splitStream = new TransformStream<Uint8Array>({\n\t\ttransform: (chunk, controller) => {\n\t\t\tfor (let split = 0; split < chunk.length; split += this._CHUNK_SIZE) {\n\t\t\t\tcontroller.enqueue(chunk.subarray(split, split + this._CHUNK_SIZE));\n\t\t\t}\n\t\t},\n\t});\n\tprivate _rawSendStream = new WritableStream<ArrayBuffer>({\n\t\twrite: async (chunk, controller) => {\n\t\t\t// Only register the backpressure listener when the buffer is actually full\n\t\t\tif (\n\t\t\t\tthis.dataChannel &&\n\t\t\t\tthis.dataChannel.bufferedAmount > DataConnection.MAX_BUFFERED_AMOUNT - chunk.byteLength\n\t\t\t) {\n\t\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\t\tconst onLow = () => {\n\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t};\n\t\t\t\t\tconst onClose = () => {\n\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\treject(new Error(\"DataChannel closed while waiting for buffer drain\"));\n\t\t\t\t\t};\n\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\tthis.dataChannel?.removeEventListener(\"bufferedamountlow\", onLow);\n\t\t\t\t\t\tthis.dataChannel?.removeEventListener(\"close\", onClose);\n\t\t\t\t\t};\n\n\t\t\t\t\tthis.dataChannel?.addEventListener(\"bufferedamountlow\", onLow, {\n\t\t\t\t\t\tonce: true,\n\t\t\t\t\t});\n\t\t\t\t\tthis.dataChannel?.addEventListener(\"close\", onClose, {\n\t\t\t\t\t\tonce: true,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!this.dataChannel || this.dataChannel.readyState !== \"open\") {\n\t\t\t\tcontroller.error(new Error(\"DataChannel is not open\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tthis.dataChannel.send(chunk);\n\t\t\t} catch (e) {\n\t\t\t\tlogger.error(`DC#:${this.connectionId} Error when sending:`, e);\n\t\t\t\tcontroller.error(e);\n\t\t\t\tthis.close();\n\t\t\t}\n\t\t},\n\t});\n\tprotected writer = this._splitStream.writable.getWriter();\n\n\tprivate _readStreamMessageHandler: ((e: MessageEvent) => void) | null = null;\n\tprivate _readStreamController: ReadableStreamDefaultController<ArrayBuffer> | null = null;\n\n\tprotected _rawReadStream = new ReadableStream<ArrayBuffer>({\n\t\tstart: (controller) => {\n\t\t\tthis._readStreamController = controller;\n\t\t\tthis.once(\"open\", () => {\n\t\t\t\tif (!this.dataChannel) return;\n\t\t\t\tthis._readStreamMessageHandler = (e: MessageEvent) => {\n\t\t\t\t\tcontroller.enqueue(e.data);\n\t\t\t\t};\n\t\t\t\tthis.dataChannel.addEventListener(\"message\", this._readStreamMessageHandler);\n\t\t\t});\n\t\t},\n\t});\n\n\tprotected constructor(peerId: string, provider: Dendri, options: any) {\n\t\tsuper(peerId, provider, { ...options, reliable: true });\n\n\t\tvoid this._splitStream.readable.pipeTo(this._rawSendStream);\n\t}\n\n\tpublic override _initializeDataChannel(dc: RTCDataChannel) {\n\t\tsuper._initializeDataChannel(dc);\n\t\tthis.dataChannel!.binaryType = \"arraybuffer\";\n\t\tthis.dataChannel!.bufferedAmountLowThreshold = DataConnection.MAX_BUFFERED_AMOUNT / 2;\n\t}\n\n\tpublic override close(options?: { flush?: boolean }): void {\n\t\t// Clean up stream resources\n\t\tif (this.dataChannel && this._readStreamMessageHandler) {\n\t\t\tthis.dataChannel.removeEventListener(\"message\", this._readStreamMessageHandler);\n\t\t\tthis._readStreamMessageHandler = null;\n\t\t}\n\n\t\t// Send flush message via super BEFORE aborting the writer\n\t\tsuper.close(options);\n\n\t\ttry {\n\t\t\tthis.writer.abort();\n\t\t} catch (_) {\n\t\t\t// Writer may already be closed\n\t\t}\n\n\t\tif (this._readStreamController) {\n\t\t\ttry {\n\t\t\t\tthis._readStreamController.close();\n\t\t\t} catch (_) {\n\t\t\t\t// Controller may already be closed\n\t\t\t}\n\t\t\tthis._readStreamController = null;\n\t\t}\n\t}\n}\n","import { decodeMultiStream, Encoder } from \"@msgpack/msgpack\";\nimport type { Dendri } from \"../../dendri\";\nimport logger from \"../../logger\";\nimport { StreamConnection } from \"./StreamConnection\";\n\nexport class MsgPack extends StreamConnection {\n\treadonly serialization = \"MsgPack\";\n\tprivate _encoder = new Encoder();\n\n\tconstructor(peerId: string, provider: Dendri, options: any) {\n\t\tsuper(peerId, provider, options);\n\n\t\t(async () => {\n\t\t\tfor await (const msg of decodeMultiStream(this._rawReadStream)) {\n\t\t\t\tconst peerData = (msg as any)?.__peerData;\n\t\t\t\tif (peerData?.type === \"close\") {\n\t\t\t\t\tthis.close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.emit(\"data\", msg);\n\t\t\t}\n\t\t})().catch((err) => {\n\t\t\t// Stream was closed or errored — expected during connection teardown\n\t\t\tif (this.open) {\n\t\t\t\tlogger.error(`DC#${this.connectionId} MsgPack decode error:`, err);\n\t\t\t}\n\t\t});\n\t}\n\n\tprotected override _send(data: unknown) {\n\t\treturn this.writer.write(this._encoder.encode(data));\n\t}\n}\n"],"mappings":"uhBAAA,IAAAA,GAAAC,GAAA,CAAAC,GAAAC,IAAA,cAEA,IAAIC,GAAM,OAAO,UAAU,eACvBC,EAAS,IASb,SAASC,GAAS,CAAC,CASf,OAAO,SACTA,EAAO,UAAY,OAAO,OAAO,IAAI,EAMhC,IAAIA,EAAO,EAAE,YAAWD,EAAS,KAYxC,SAASE,GAAGC,EAAIC,EAASC,EAAM,CAC7B,KAAK,GAAKF,EACV,KAAK,QAAUC,EACf,KAAK,KAAOC,GAAQ,EACtB,CAaA,SAASC,GAAYC,EAASC,EAAOL,EAAIC,EAASC,EAAM,CACtD,GAAI,OAAOF,GAAO,WAChB,MAAM,IAAI,UAAU,iCAAiC,EAGvD,IAAIM,EAAW,IAAIP,GAAGC,EAAIC,GAAWG,EAASF,CAAI,EAC9CK,EAAMV,EAASA,EAASQ,EAAQA,EAEpC,OAAKD,EAAQ,QAAQG,CAAG,EACdH,EAAQ,QAAQG,CAAG,EAAE,GAC1BH,EAAQ,QAAQG,CAAG,EAAI,CAACH,EAAQ,QAAQG,CAAG,EAAGD,CAAQ,EADxBF,EAAQ,QAAQG,CAAG,EAAE,KAAKD,CAAQ,GAD1CF,EAAQ,QAAQG,CAAG,EAAID,EAAUF,EAAQ,gBAI7DA,CACT,CASA,SAASI,EAAWJ,EAASG,EAAK,CAC5B,EAAEH,EAAQ,eAAiB,EAAGA,EAAQ,QAAU,IAAIN,EACnD,OAAOM,EAAQ,QAAQG,CAAG,CACjC,CASA,SAASE,GAAe,CACtB,KAAK,QAAU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AQ,CAEf,KAAK,MACRC,EAAO,MAAM,MAAM,KAAK,YAAY,yBAA0BD,CAAG,CAEnE,CAAC,CACF,CAEmB,MAAME,EAAe,CACvC,OAAO,KAAK,OAAO,MAAM,KAAK,SAAS,OAAOA,CAAI,CAAC,CACpD,CACD","names":["require_eventemitter3","__commonJSMin","exports","module","has","prefix","Events","EE","fn","context","once","addListener","emitter","event","listener","evt","clearEvent","EventEmitter","names","events","name","handlers","i","l","ee","listeners","a1","a2","a3","a4","a5","len","args","length","j","UINT32_MAX","setUint64","view","offset","value","high","low","setInt64","getInt64","getUint64","TEXT_ENCODING_AVAILABLE","_a","utf8Count","str","strLength","byteLength","pos","value","extra","utf8EncodeJs","output","outputOffset","offset","sharedTextEncoder","TEXT_ENCODER_THRESHOLD","_b","UINT32_MAX","utf8EncodeTEencode","utf8EncodeTEencodeInto","utf8EncodeTE","CHUNK_SIZE","utf8DecodeJs","bytes","inputOffset","end","units","result","byte1","byte2","byte3","byte4","unit","sharedTextDecoder","TEXT_DECODER_THRESHOLD","_c","utf8DecodeTD","stringBytes","ExtData","type","data","DecodeError","_super","__extends","message","_this","proto","EXT_TIMESTAMP","TIMESTAMP32_MAX_SEC","TIMESTAMP64_MAX_SEC","encodeTimeSpecToTimestamp","_a","sec","nsec","rv","view","secHigh","secLow","setInt64","encodeDateToTimeSpec","date","msec","nsecInSec","encodeTimestampExtension","object","timeSpec","decodeTimestampToTimeSpec","data","nsec30AndSecHigh2","secLow32","getInt64","DecodeError","decodeTimestampExtension","timestampExtension","ExtensionCodec","timestampExtension","_a","type","encode","decode","index","object","context","i","encodeExt","data","ExtData","decodeExt","ensureUint8Array","buffer","createDataView","bufferView","DEFAULT_MAX_DEPTH","DEFAULT_INITIAL_BUFFER_SIZE","Encoder","extensionCodec","context","maxDepth","initialBufferSize","sortKeys","forceFloat32","ignoreUndefined","forceIntegerToFloat","ExtensionCodec","object","depth","sizeToWrite","requiredSize","newSize","newBuffer","newBytes","newView","byteLength","maxHeaderSize","strLength","TEXT_ENCODER_THRESHOLD","utf8Count","utf8EncodeTE","utf8EncodeJs","ext","size","bytes","ensureUint8Array","_i","object_1","item","keys","count","keys_1","key","keys_2","value","values","setUint64","setInt64","prettyByte","byte","DEFAULT_MAX_KEY_LENGTH","DEFAULT_MAX_LENGTH_PER_KEY","CachedKeyDecoder","maxKeyLength","maxLengthPerKey","i","byteLength","bytes","inputOffset","records","FIND_CHUNK","_i","records_1","record","recordBytes","j","value","cachedValue","str","utf8DecodeJs","slicedCopyOfBytes","isValidMapKeyType","key","keyType","HEAD_BYTE_REQUIRED","EMPTY_VIEW","EMPTY_BYTES","DataViewIndexOutOfBoundsError","e","MORE_DATA","sharedCachedKeyDecoder","CachedKeyDecoder","Decoder","extensionCodec","context","maxStrLength","maxBinLength","maxArrayLength","maxMapLength","maxExtLength","keyDecoder","ExtensionCodec","UINT32_MAX","buffer","ensureUint8Array","createDataView","remainingData","newData","newBuffer","size","posToShow","_a","view","pos","object","stream","decoded","stream_1","__asyncValues","stream_1_1","_b","headByte","totalPos","prettyByte","isArray","isArrayHeaderRequired","arrayItemsLeft","stream_2","stream_2_1","e_2","DECODE","byteLength","DecodeError","stack","state","headerOffset","offset","TEXT_DECODER_THRESHOLD","utf8DecodeTD","utf8DecodeJs","headOffset","extType","data","value","getUint64","getInt64","defaultDecodeOptions","isAsyncIterable","object","assertNonNull","value","asyncIterableFromStream","stream","reader","__await","_a","_b","done","ensureAsyncIterable","streamLike","decodeMultiStream","streamLike","options","defaultDecodeOptions","stream","ensureAsyncIterable","decoder","Decoder","LOG_PREFIX","Logger","logLevel","args","fn","rest","copy","LOG_PREFIX","i","logger_default","import_eventemitter3","EventEmitterWithError","type","err","retryable","logger_default","error","DendriError","details","BaseConnection","EventEmitterWithError","peer","provider","options","Negotiator","connection","options","peerConnection","dataConnection","config","dataChannel","logger_default","isPublicCandidate","c","peerId","connectionId","connectionType","provider","evt","stream","mediaConnection","peerConnectionNotClosed","dataChannelNotClosed","offer","payload","err","err_1","answer","type","sdp","candidates","candidate","ice","pc","transceiver","codecs","h264","others","lines","result","h264Payloads","line","match","parts","prefix","payloads","reordered","p","t","track","randomToken","DataConnection","_DataConnection","BaseConnection","peerId","provider","options","randomToken","Negotiator","dc","logger_default","pc","stats","rtt","report","bdp","optimal","data","chunked","message","payload","StreamConnection","DataConnection","chunk","controller","split","resolve","reject","onLow","cleanup","onClose","e","logger_default","peerId","provider","options","dc","MsgPack","StreamConnection","Encoder","peerId","provider","options","msg","decodeMultiStream","err","logger_default","data"]}
|