@afterrealism/dendri-client 2.3.7 → 2.5.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.
@@ -1,4 +1,4 @@
1
- "use strict";var ge=Object.create;var A=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var _e=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var Se=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ue=(r,e)=>{for(var t in e)A(r,t,{get:e[t],enumerable:!0})},ee=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ce(e))!Te.call(r,i)&&i!==t&&A(r,i,{get:()=>e[i],enumerable:!(n=Ee(e,i))||n.enumerable});return r};var De=(r,e,t)=>(t=r!=null?ge(_e(r)):{},ee(e||!r||!r.__esModule?A(t,"default",{value:r,enumerable:!0}):t,r)),Ie=r=>ee(A({},"__esModule",{value:!0}),r);var me=Se((Yt,Z)=>{"use strict";var rt=Object.prototype.hasOwnProperty,m="~";function I(){}Object.create&&(I.prototype=Object.create(null),new I().__proto__||(m=!1));function it(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function ye(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new it(t,n||r,i),s=m?m+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function B(r,e){--r._eventsCount===0?r._events=new I:delete r._events[e]}function y(){this._events=new I,this._eventsCount=0}y.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)rt.call(t,n)&&e.push(m?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};y.prototype.listeners=function(e){var t=m?m+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i<o;i++)s[i]=n[i].fn;return s};y.prototype.listenerCount=function(e){var t=m?m+e:e,n=this._events[t];return n?n.fn?1:n.length:0};y.prototype.emit=function(e,t,n,i,o,s){var f=m?m+e:e;if(!this._events[f])return!1;var c=this._events[f],a=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),a){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,o),!0;case 6:return c.fn.call(c.context,t,n,i,o,s),!0}for(d=1,u=new Array(a-1);d<a;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var h=c.length,p;for(d=0;d<h;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),a){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=new Array(a-1);p<a;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0};y.prototype.on=function(e,t,n){return ye(this,e,t,n,!1)};y.prototype.once=function(e,t,n){return ye(this,e,t,n,!0)};y.prototype.removeListener=function(e,t,n,i){var o=m?m+e:e;if(!this._events[o])return this;if(!t)return B(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&B(this,o);else{for(var f=0,c=[],a=s.length;f<a;f++)(s[f].fn!==t||i&&!s[f].once||n&&s[f].context!==n)&&c.push(s[f]);c.length?this._events[o]=c.length===1?c[0]:c:B(this,o)}return this};y.prototype.removeAllListeners=function(e){var t;return e?(t=m?m+e:e,this._events[t]&&B(this,t)):(this._events=new I,this._eventsCount=0),this};y.prototype.off=y.prototype.removeListener;y.prototype.addListener=y.prototype.on;y.prefixed=m;y.EventEmitter=y;typeof Z<"u"&&(Z.exports=y)});var ot={};Ue(ot,{MsgPack:()=>j});module.exports=Ie(ot);var w=4294967295;function te(r,e,t){var n=t/4294967296,i=t;r.setUint32(e,n),r.setUint32(e+4,i)}function b(r,e,t){var n=Math.floor(t/4294967296),i=t;r.setUint32(e,n),r.setUint32(e+4,i)}function L(r,e){var t=r.getInt32(e),n=r.getUint32(e+4);return t*4294967296+n}function ne(r,e){var t=r.getUint32(e),n=r.getUint32(e+4);return t*4294967296+n}var H,W,$,M=(typeof process>"u"||((H=process==null?void 0:process.env)===null||H===void 0?void 0:H.TEXT_ENCODING)!=="never")&&typeof TextEncoder<"u"&&typeof TextDecoder<"u";function V(r){for(var e=r.length,t=0,n=0;n<e;){var i=r.charCodeAt(n++);if((i&4294967168)===0){t++;continue}else if((i&4294965248)===0)t+=2;else{if(i>=55296&&i<=56319&&n<e){var o=r.charCodeAt(n);(o&64512)===56320&&(++n,i=((i&1023)<<10)+(o&1023)+65536)}(i&4294901760)===0?t+=3:t+=4}}return t}function re(r,e,t){for(var n=r.length,i=t,o=0;o<n;){var s=r.charCodeAt(o++);if((s&4294967168)===0){e[i++]=s;continue}else if((s&4294965248)===0)e[i++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&o<n){var f=r.charCodeAt(o);(f&64512)===56320&&(++o,s=((s&1023)<<10)+(f&1023)+65536)}(s&4294901760)===0?(e[i++]=s>>12&15|224,e[i++]=s>>6&63|128):(e[i++]=s>>18&7|240,e[i++]=s>>12&63|128,e[i++]=s>>6&63|128)}e[i++]=s&63|128}}var S=M?new TextEncoder:void 0,ie=M?typeof process<"u"&&((W=process==null?void 0:process.env)===null||W===void 0?void 0:W.TEXT_ENCODING)!=="force"?200:0:w;function Ae(r,e,t){e.set(S.encode(r),t)}function be(r,e,t){S.encodeInto(r,e.subarray(t))}var oe=S?.encodeInto?be:Ae,Le=4096;function R(r,e,t){for(var n=e,i=n+t,o=[],s="";n<i;){var f=r[n++];if((f&128)===0)o.push(f);else if((f&224)===192){var c=r[n++]&63;o.push((f&31)<<6|c)}else if((f&240)===224){var c=r[n++]&63,a=r[n++]&63;o.push((f&31)<<12|c<<6|a)}else if((f&248)===240){var c=r[n++]&63,a=r[n++]&63,u=r[n++]&63,d=(f&7)<<18|c<<12|a<<6|u;d>65535&&(d-=65536,o.push(d>>>10&1023|55296),d=56320|d&1023),o.push(d)}else o.push(f);o.length>=Le&&(s+=String.fromCharCode.apply(String,o),o.length=0)}return o.length>0&&(s+=String.fromCharCode.apply(String,o)),s}var Me=M?new TextDecoder:null,se=M?typeof process<"u"&&(($=process==null?void 0:process.env)===null||$===void 0?void 0:$.TEXT_DECODER)!=="force"?200:0:w;function ae(r,e,t){var n=r.subarray(e,e+t);return Me.decode(n)}var U=(function(){function r(e,t){this.type=e,this.data=t}return r})();var Re=(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),x=(function(r){Re(e,r);function e(t){var n=r.call(this,t)||this,i=Object.create(e.prototype);return Object.setPrototypeOf(n,i),Object.defineProperty(n,"name",{configurable:!0,enumerable:!1,value:e.name}),n}return e})(Error);var ke=-1,Pe=4294967296-1,Be=17179869184-1;function ze(r){var e=r.sec,t=r.nsec;if(e>=0&&t>=0&&e<=Be)if(t===0&&e<=Pe){var n=new Uint8Array(4),i=new DataView(n.buffer);return i.setUint32(0,e),n}else{var o=e/4294967296,s=e&4294967295,n=new Uint8Array(8),i=new DataView(n.buffer);return i.setUint32(0,t<<2|o&3),i.setUint32(4,s),n}else{var n=new Uint8Array(12),i=new DataView(n.buffer);return i.setUint32(0,t),b(i,4,e),n}}function Oe(r){var e=r.getTime(),t=Math.floor(e/1e3),n=(e-t*1e3)*1e6,i=Math.floor(n/1e9);return{sec:t+i,nsec:n-i*1e9}}function Fe(r){if(r instanceof Date){var e=Oe(r);return ze(e)}else return null}function Ne(r){var e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(r.byteLength){case 4:{var t=e.getUint32(0),n=0;return{sec:t,nsec:n}}case 8:{var i=e.getUint32(0),o=e.getUint32(4),t=(i&3)*4294967296+o,n=i>>>2;return{sec:t,nsec:n}}case 12:{var t=L(e,4),n=e.getUint32(0);return{sec:t,nsec:n}}default:throw new x("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(r.length))}}function He(r){var e=Ne(r);return new Date(e.sec*1e3+e.nsec/1e6)}var ce={type:ke,encode:Fe,decode:He};var k=(function(){function r(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(ce)}return r.prototype.register=function(e){var t=e.type,n=e.encode,i=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=i;else{var o=1+t;this.builtInEncoders[o]=n,this.builtInDecoders[o]=i}},r.prototype.tryToEncode=function(e,t){for(var n=0;n<this.builtInEncoders.length;n++){var i=this.builtInEncoders[n];if(i!=null){var o=i(e,t);if(o!=null){var s=-1-n;return new U(s,o)}}}for(var n=0;n<this.encoders.length;n++){var i=this.encoders[n];if(i!=null){var o=i(e,t);if(o!=null){var s=n;return new U(s,o)}}}return e instanceof U?e:null},r.prototype.decode=function(e,t,n){var i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(e,t,n):new U(t,e)},r.defaultCodec=new r,r})();function E(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r instanceof ArrayBuffer?new Uint8Array(r):Uint8Array.from(r)}function fe(r){if(r instanceof ArrayBuffer)return new DataView(r);var e=E(r);return new DataView(e.buffer,e.byteOffset,e.byteLength)}var We=100,$e=2048,X=(function(){function r(e,t,n,i,o,s,f,c){e===void 0&&(e=k.defaultCodec),t===void 0&&(t=void 0),n===void 0&&(n=We),i===void 0&&(i=$e),o===void 0&&(o=!1),s===void 0&&(s=!1),f===void 0&&(f=!1),c===void 0&&(c=!1),this.extensionCodec=e,this.context=t,this.maxDepth=n,this.initialBufferSize=i,this.sortKeys=o,this.forceFloat32=s,this.ignoreUndefined=f,this.forceIntegerToFloat=c,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return r.prototype.reinitializeState=function(){this.pos=0},r.prototype.encodeSharedRef=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)},r.prototype.encode=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)},r.prototype.doEncode=function(e,t){if(t>this.maxDepth)throw new Error("Too deep objects in depth ".concat(t));e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.encodeObject(e,t)},r.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)},r.prototype.resizeBuffer=function(e){var t=new ArrayBuffer(e),n=new Uint8Array(t),i=new DataView(t);n.set(this.bytes),this.view=i,this.bytes=n},r.prototype.encodeNil=function(){this.writeU8(192)},r.prototype.encodeBoolean=function(e){e===!1?this.writeU8(194):this.writeU8(195)},r.prototype.encodeNumber=function(e){Number.isSafeInteger(e)&&!this.forceIntegerToFloat?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},r.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error("Too long string: ".concat(e," bytes in UTF-8"))},r.prototype.encodeString=function(e){var t=5,n=e.length;if(n>ie){var i=V(e);this.ensureBufferSizeToWrite(t+i),this.writeStringHeader(i),oe(e,this.bytes,this.pos),this.pos+=i}else{var i=V(e);this.ensureBufferSizeToWrite(t+i),this.writeStringHeader(i),re(e,this.bytes,this.pos),this.pos+=i}},r.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)))},r.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error("Too large binary: ".concat(t));var n=E(e);this.writeU8a(n)},r.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error("Too large array: ".concat(n));for(var i=0,o=e;i<o.length;i++){var s=o[i];this.doEncode(s,t+1)}},r.prototype.countWithoutUndefined=function(e,t){for(var n=0,i=0,o=t;i<o.length;i++){var s=o[i];e[s]!==void 0&&n++}return n},r.prototype.encodeMap=function(e,t){var n=Object.keys(e);this.sortKeys&&n.sort();var i=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error("Too large map object: ".concat(i));for(var o=0,s=n;o<s.length;o++){var f=s[o],c=e[f];this.ignoreUndefined&&c===void 0||(this.encodeString(f),this.doEncode(c,t+1))}},r.prototype.encodeExtension=function(e){var t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error("Too large extension object: ".concat(t));this.writeI8(e.type),this.writeU8a(e.data)},r.prototype.writeU8=function(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++},r.prototype.writeU8a=function(e){var t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t},r.prototype.writeI8=function(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++},r.prototype.writeU16=function(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2},r.prototype.writeI16=function(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2},r.prototype.writeU32=function(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4},r.prototype.writeI32=function(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4},r.prototype.writeF32=function(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4},r.prototype.writeF64=function(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8},r.prototype.writeU64=function(e){this.ensureBufferSizeToWrite(8),te(this.view,this.pos,e),this.pos+=8},r.prototype.writeI64=function(e){this.ensureBufferSizeToWrite(8),b(this.view,this.pos,e),this.pos+=8},r})();function P(r){return"".concat(r<0?"-":"","0x").concat(Math.abs(r).toString(16).padStart(2,"0"))}var Ve=16,Xe=16,le=(function(){function r(e,t){e===void 0&&(e=Ve),t===void 0&&(t=Xe),this.maxKeyLength=e,this.maxLengthPerKey=t,this.hit=0,this.miss=0,this.caches=[];for(var n=0;n<this.maxKeyLength;n++)this.caches.push([])}return r.prototype.canBeCached=function(e){return e>0&&e<=this.maxKeyLength},r.prototype.find=function(e,t,n){var i=this.caches[n-1];e:for(var o=0,s=i;o<s.length;o++){for(var f=s[o],c=f.bytes,a=0;a<n;a++)if(c[a]!==e[t+a])continue e;return f.str}return null},r.prototype.store=function(e,t){var n=this.caches[e.length-1],i={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=i:n.push(i)},r.prototype.decode=function(e,t,n){var i=this.find(e,t,n);if(i!=null)return this.hit++,i;this.miss++;var o=R(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,o),o},r})();var Ge=function(r,e,t,n){function i(o){return o instanceof t?o:new t(function(s){s(o)})}return new(t||(t=Promise))(function(o,s){function f(u){try{a(n.next(u))}catch(d){s(d)}}function c(u){try{a(n.throw(u))}catch(d){s(d)}}function a(u){u.done?o(u.value):i(u.value).then(f,c)}a((n=n.apply(r,e||[])).next())})},G=function(r,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,s;return s={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function f(a){return function(u){return c([a,u])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,i&&(o=a[0]&2?i.return:a[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;switch(i=0,o&&(a=[a[0]&2,o.value]),a[0]){case 0:case 1:o=a;break;case 4:return t.label++,{value:a[1],done:!1};case 5:t.label++,i=a[1],a=[0];continue;case 7:a=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(a[0]===6||a[0]===2)){t=0;continue}if(a[0]===3&&(!o||a[1]>o[0]&&a[1]<o[3])){t.label=a[1];break}if(a[0]===6&&t.label<o[1]){t.label=o[1],o=a;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(a);break}o[2]&&t.ops.pop(),t.trys.pop();continue}a=e.call(r,t)}catch(u){a=[6,u],i=0}finally{n=o=0}if(a[0]&5)throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},de=function(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof __values=="function"?__values(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(o){t[o]=r[o]&&function(s){return new Promise(function(f,c){s=r[o](s),i(f,c,s.done,s.value)})}}function i(o,s,f,c){Promise.resolve(c).then(function(a){o({value:a,done:f})},s)}},C=function(r){return this instanceof C?(this.v=r,this):new C(r)},Ke=function(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),i,o=[];return i={},s("next"),s("throw"),s("return"),i[Symbol.asyncIterator]=function(){return this},i;function s(h){n[h]&&(i[h]=function(p){return new Promise(function(v,g){o.push([h,p,v,g])>1||f(h,p)})})}function f(h,p){try{c(n[h](p))}catch(v){d(o[0][3],v)}}function c(h){h.value instanceof C?Promise.resolve(h.value.v).then(a,u):d(o[0][2],h)}function a(h){f("next",h)}function u(h){f("throw",h)}function d(h,p){h(p),o.shift(),o.length&&f(o[0][0],o[0][1])}},Ye=function(r){var e=typeof r;return e==="string"||e==="number"},D=-1,Y=new DataView(new ArrayBuffer(0)),qe=new Uint8Array(Y.buffer),K=(function(){try{Y.getInt8(0)}catch(r){return r.constructor}throw new Error("never reached")})(),he=new K("Insufficient data"),Je=new le,ue=(function(){function r(e,t,n,i,o,s,f,c){e===void 0&&(e=k.defaultCodec),t===void 0&&(t=void 0),n===void 0&&(n=w),i===void 0&&(i=w),o===void 0&&(o=w),s===void 0&&(s=w),f===void 0&&(f=w),c===void 0&&(c=Je),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=i,this.maxArrayLength=o,this.maxMapLength=s,this.maxExtLength=f,this.keyDecoder=c,this.totalPos=0,this.pos=0,this.view=Y,this.bytes=qe,this.headByte=D,this.stack=[]}return r.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=D,this.stack.length=0},r.prototype.setBuffer=function(e){this.bytes=E(e),this.view=fe(this.bytes),this.pos=0},r.prototype.appendBuffer=function(e){if(this.headByte===D&&!this.hasRemaining(1))this.setBuffer(e);else{var t=this.bytes.subarray(this.pos),n=E(e),i=new Uint8Array(t.length+n.length);i.set(t),i.set(n,t.length),this.setBuffer(i)}},r.prototype.hasRemaining=function(e){return this.view.byteLength-this.pos>=e},r.prototype.createExtraByteError=function(e){var t=this,n=t.view,i=t.pos;return new RangeError("Extra ".concat(n.byteLength-i," of ").concat(n.byteLength," byte(s) found at buffer[").concat(e,"]"))},r.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},r.prototype.decodeMulti=function(e){return G(this,function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}})},r.prototype.decodeAsync=function(e){var t,n,i,o;return Ge(this,void 0,void 0,function(){var s,f,c,a,u,d,h,p;return G(this,function(v){switch(v.label){case 0:s=!1,v.label=1;case 1:v.trys.push([1,6,7,12]),t=de(e),v.label=2;case 2:return[4,t.next()];case 3:if(n=v.sent(),!!n.done)return[3,5];if(c=n.value,s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{f=this.doDecodeSync(),s=!0}catch(g){if(!(g instanceof K))throw g}this.totalPos+=this.pos,v.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return a=v.sent(),i={error:a},[3,12];case 7:return v.trys.push([7,,10,11]),n&&!n.done&&(o=t.return)?[4,o.call(t)]:[3,9];case 8:v.sent(),v.label=9;case 9:return[3,11];case 10:if(i)throw i.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,f]}throw u=this,d=u.headByte,h=u.pos,p=u.totalPos,new RangeError("Insufficient data in parsing ".concat(P(d)," at ").concat(p," (").concat(h," in the current buffer)"))}})})},r.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},r.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},r.prototype.decodeMultiAsync=function(e,t){return Ke(this,arguments,function(){var i,o,s,f,c,a,u,d,h;return G(this,function(p){switch(p.label){case 0:i=t,o=-1,p.label=1;case 1:p.trys.push([1,13,14,19]),s=de(e),p.label=2;case 2:return[4,C(s.next())];case 3:if(f=p.sent(),!!f.done)return[3,12];if(c=f.value,t&&o===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c),i&&(o=this.readArraySize(),i=!1,this.complete()),p.label=4;case 4:p.trys.push([4,9,,10]),p.label=5;case 5:return[4,C(this.doDecodeSync())];case 6:return[4,p.sent()];case 7:return p.sent(),--o===0?[3,8]:[3,5];case 8:return[3,10];case 9:if(a=p.sent(),!(a instanceof K))throw a;return[3,10];case 10:this.totalPos+=this.pos,p.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return u=p.sent(),d={error:u},[3,19];case 14:return p.trys.push([14,,17,18]),f&&!f.done&&(h=s.return)?[4,C(h.call(s))]:[3,16];case 15:p.sent(),p.label=16;case 16:return[3,18];case 17:if(d)throw d.error;return[7];case 18:return[7];case 19:return[2]}})})},r.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){var n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e<160){var n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else{var i=e-160;t=this.decodeUtf8String(i,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)t=this.readI64();else if(e===217){var i=this.lookU8();t=this.decodeUtf8String(i,1)}else if(e===218){var i=this.lookU16();t=this.decodeUtf8String(i,2)}else if(e===219){var i=this.lookU32();t=this.decodeUtf8String(i,4)}else if(e===220){var n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===221){var n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===222){var n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===223){var n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===196){var n=this.lookU8();t=this.decodeBinary(n,1)}else if(e===197){var n=this.lookU16();t=this.decodeBinary(n,2)}else if(e===198){var n=this.lookU32();t=this.decodeBinary(n,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){var n=this.lookU8();t=this.decodeExtension(n,1)}else if(e===200){var n=this.lookU16();t=this.decodeExtension(n,2)}else if(e===201){var n=this.lookU32();t=this.decodeExtension(n,4)}else throw new x("Unrecognized type byte: ".concat(P(e)));this.complete();for(var o=this.stack;o.length>0;){var s=o[o.length-1];if(s.type===0)if(s.array[s.position]=t,s.position++,s.position===s.size)o.pop(),t=s.array;else continue e;else if(s.type===1){if(!Ye(t))throw new x("The type of key must be string or number but "+typeof t);if(t==="__proto__")throw new x("The key __proto__ is not allowed");s.key=t,s.type=2;continue e}else if(s.map[s.key]=t,s.readCount++,s.readCount===s.size)o.pop(),t=s.map;else{s.key=null,s.type=1;continue e}}return t}},r.prototype.readHeadByte=function(){return this.headByte===D&&(this.headByte=this.readU8()),this.headByte},r.prototype.complete=function(){this.headByte=D},r.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new x("Unrecognized array type byte: ".concat(P(e)))}}},r.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new x("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},r.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new x("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},r.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new x("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLength<this.pos+t+e)throw he;var i=this.pos+t,o;return this.stateIsMapKey()&&(!((n=this.keyDecoder)===null||n===void 0)&&n.canBeCached(e))?o=this.keyDecoder.decode(this.bytes,i,e):e>se?o=ae(this.bytes,i,e):o=R(this.bytes,i,e),this.pos+=t+e,o},r.prototype.stateIsMapKey=function(){if(this.stack.length>0){var e=this.stack[this.stack.length-1];return e.type===1}return!1},r.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new x("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw he;var n=this.pos+t,i=this.bytes.subarray(n,n+e);return this.pos+=t+e,i},r.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new x("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),i=this.decodeBinary(e,t+1);return this.extensionCodec.decode(i,n,this.context)},r.prototype.lookU8=function(){return this.view.getUint8(this.pos)},r.prototype.lookU16=function(){return this.view.getUint16(this.pos)},r.prototype.lookU32=function(){return this.view.getUint32(this.pos)},r.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},r.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},r.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},r.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},r.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},r.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},r.prototype.readU64=function(){var e=ne(this.view,this.pos);return this.pos+=8,e},r.prototype.readI64=function(){var e=L(this.view,this.pos);return this.pos+=8,e},r.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},r.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},r})();var pe={};var Ze=function(r,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,s;return s={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function f(a){return function(u){return c([a,u])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,i&&(o=a[0]&2?i.return:a[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;switch(i=0,o&&(a=[a[0]&2,o.value]),a[0]){case 0:case 1:o=a;break;case 4:return t.label++,{value:a[1],done:!1};case 5:t.label++,i=a[1],a=[0];continue;case 7:a=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(a[0]===6||a[0]===2)){t=0;continue}if(a[0]===3&&(!o||a[1]>o[0]&&a[1]<o[3])){t.label=a[1];break}if(a[0]===6&&t.label<o[1]){t.label=o[1],o=a;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(a);break}o[2]&&t.ops.pop(),t.trys.pop();continue}a=e.call(r,t)}catch(u){a=[6,u],i=0}finally{n=o=0}if(a[0]&5)throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},_=function(r){return this instanceof _?(this.v=r,this):new _(r)},Qe=function(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(r,e||[]),i,o=[];return i={},s("next"),s("throw"),s("return"),i[Symbol.asyncIterator]=function(){return this},i;function s(h){n[h]&&(i[h]=function(p){return new Promise(function(v,g){o.push([h,p,v,g])>1||f(h,p)})})}function f(h,p){try{c(n[h](p))}catch(v){d(o[0][3],v)}}function c(h){h.value instanceof _?Promise.resolve(h.value.v).then(a,u):d(o[0][2],h)}function a(h){f("next",h)}function u(h){f("throw",h)}function d(h,p){h(p),o.shift(),o.length&&f(o[0][0],o[0][1])}};function je(r){return r[Symbol.asyncIterator]!=null}function et(r){if(r==null)throw new Error("Assertion Failure: value must not be null nor undefined")}function tt(r){return Qe(this,arguments,function(){var t,n,i,o;return Ze(this,function(s){switch(s.label){case 0:t=r.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,_(t.read())];case 3:return n=s.sent(),i=n.done,o=n.value,i?[4,_(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return et(o),[4,_(o)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function ve(r){return je(r)?r:tt(r)}function q(r,e){e===void 0&&(e=pe);var t=ve(r),n=new ue(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength);return n.decodeStream(t)}var nt="Dendri: ";var J=class{_logLevel=0;get logLevel(){return this._logLevel}set logLevel(e){this._logLevel=e}log(...e){this._logLevel>=3&&this._print(3,...e)}warn(...e){this._logLevel>=2&&this._print(2,...e)}error(...e){this._logLevel>=1&&this._print(1,...e)}setLogFunction(e){this._print=e}_print(e,...t){let n=[nt,...t];for(let i in n)n[i]instanceof Error&&(n[i]=`(${n[i].name}) ${n[i].message}`);e>=3?console.log(...n):e>=2?console.warn("WARNING",...n):e>=1&&console.error("ERROR",...n)}},l=new J;var xe=De(me(),1);var z=class extends xe.EventEmitter{emitError(e,t,n=!1){l.error("Error:",t);let i=new Q(`${e}`,t);i.retryable=n,this.emit("error",i)}},Q=class extends Error{type;retryable;details;constructor(e,t){typeof t=="string"?super(t):(super(t.message),this.stack=t.stack),this.type=e,this.retryable=!1}setRetryable(e){return this.retryable=e,this}setDetails(e){return this.details=e,this}};var O=class extends z{constructor(t,n,i){super();this.peer=t;this.provider=n;this.options=i;this.metadata=i.metadata}peer;provider;options;_open=!1;metadata;connectionId;peerConnection;dataChannel=null;label;get open(){return this._open}};var F=class{constructor(e){this.connection=e}connection;_pendingCandidates=[];startConnection(e){let t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type==="media"&&e._stream&&(this._addTracksToConnection(e._stream,t),this._setCodecPreferences(t)),e.originator){let n=this.connection,i={ordered:!!e.reliable},o=t.createDataChannel(n.label,i);n._initializeDataChannel(o),this._makeOffer()}else this.handleSDP("OFFER",e.sdp)}_startPeerConnection(){l.log("Creating RTCPeerConnection.");let e=new RTCPeerConnection(this.connection.provider?.options.config);return this._setupListeners(e),e}_setupListeners(e){let t=this.connection.peer,n=this.connection.connectionId,i=this.connection.type,o=this.connection.provider;l.log("Listening for ICE candidates."),e.onicecandidate=s=>{s.candidate?.candidate&&(l.log(`Received ICE candidates for ${t}:`,s.candidate),o.socket.send({type:"CANDIDATE",payload:{candidate:s.candidate,type:i,connectionId:n},dst:t}))},e.oniceconnectionstatechange=()=>{switch(e.iceConnectionState){case"failed":l.log(`iceConnectionState is failed, closing connections to ${t}`),this.connection.emitError("negotiation-failed",`Negotiation of connection to ${t} failed.`),this.connection.close();break;case"closed":l.log(`iceConnectionState is closed, closing connections to ${t}`),this.connection.emitError("connection-closed",`Connection to ${t} closed.`),this.connection.close();break;case"disconnected":l.log(`iceConnectionState changed to disconnected on the connection with ${t}`);break;case"completed":e.onicecandidate=()=>{};break}this.connection.emit("iceStateChanged",e.iceConnectionState)},l.log("Listening for data channel"),e.ondatachannel=s=>{l.log("Received data channel");let f=s.channel,c=o.getConnection(t,n);if(!c){l.warn(`Received data channel for non-existent connection ${n}`);return}c._initializeDataChannel(f)},l.log("Listening for remote stream"),e.ontrack=s=>{l.log("Received remote stream");let f=s.streams[0],c=o.getConnection(t,n);if(!c){l.warn(`Received remote stream for non-existent connection ${n}`);return}if(c.type==="media"){let a=c;this._addStreamToMediaConnection(f,a)}}}cleanup(){l.log(`Cleaning up PeerConnection to ${this.connection.peer}`);let e=this.connection.peerConnection;if(!e)return;this.connection.peerConnection=null,this._pendingCandidates=[],e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=()=>{};let t=e.signalingState!=="closed",n=!1,i=this.connection.dataChannel;i&&(n=!!i.readyState&&i.readyState!=="closed",n&&i.close()),(t||n)&&e.close()}async _makeOffer(){let e=this.connection.peerConnection,t=this.connection.provider;try{let n=await e.createOffer(this.connection.options.constraints);if(!this.connection.peerConnection){l.log("PeerConnection closed during createOffer");return}l.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp),this.connection.type==="media"&&n.sdp&&(n.sdp=this._applyH264SdpFallback(n.sdp,e));try{if(await e.setLocalDescription(n),!this.connection.peerConnection){l.log("PeerConnection closed during setLocalDescription");return}l.log("Set localDescription:",n,`for:${this.connection.peer}`);let i={sdp:n,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata};if(this.connection.type==="data"){let o=this.connection;i={...i,label:o.label,reliable:o.reliable,serialization:o.serialization}}t.socket.send({type:"OFFER",payload:i,dst:this.connection.peer})}catch(i){i!=="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError("webrtc",i instanceof Error?i:String(i)),l.log("Failed to setLocalDescription, ",i))}}catch(n){t.emitError("webrtc",n instanceof Error?n:String(n)),l.log("Failed to createOffer, ",n)}}async _makeAnswer(){let e=this.connection.peerConnection,t=this.connection.provider;try{let n=await e.createAnswer();if(!this.connection.peerConnection){l.log("PeerConnection closed during createAnswer");return}l.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp),this.connection.type==="media"&&n.sdp&&(n.sdp=this._applyH264SdpFallback(n.sdp,e));try{if(await e.setLocalDescription(n),!this.connection.peerConnection){l.log("PeerConnection closed during setLocalDescription");return}l.log("Set localDescription:",n,`for:${this.connection.peer}`),t.socket.send({type:"ANSWER",payload:{sdp:n,type:this.connection.type,connectionId:this.connection.connectionId},dst:this.connection.peer})}catch(i){t.emitError("webrtc",i instanceof Error?i:String(i)),l.log("Failed to setLocalDescription, ",i)}}catch(n){t.emitError("webrtc",n instanceof Error?n:String(n)),l.log("Failed to create answer, ",n)}}async handleSDP(e,t){let n=this.connection.peerConnection,i=this.connection.provider;l.log("Setting remote description",t);try{if(await n.setRemoteDescription(t),!this.connection.peerConnection){l.log("PeerConnection closed during setRemoteDescription");return}if(l.log(`Set remoteDescription:${e} for:${this.connection.peer}`),this._pendingCandidates.length>0){l.log(`Flushing ${this._pendingCandidates.length} pending ICE candidates`);let o=this._pendingCandidates;this._pendingCandidates=[];for(let s of o)await this.handleCandidate(s)}e==="OFFER"&&await this._makeAnswer()}catch(o){i.emitError("webrtc",o instanceof Error?o:String(o)),l.log("Failed to setRemoteDescription, ",o)}}async handleCandidate(e){l.log("handleCandidate:",e);let t=this.connection.peerConnection;if(!t){l.warn(`PeerConnection not set for ${this.connection.peer}, cannot add ICE candidate`);return}if(!t.remoteDescription){l.log("Queueing ICE candidate (no remote description yet)"),this._pendingCandidates.push(e);return}try{await t.addIceCandidate(e),l.log(`Added ICE candidate for:${this.connection.peer}`)}catch(n){this.connection.provider?.emitError("webrtc",n instanceof Error?n:String(n)),l.log("Failed to handleCandidate, ",n)}}_setCodecPreferences(e){if(e.getTransceivers){for(let t of e.getTransceivers())if(t.sender?.track?.kind==="video"){let n=typeof RTCRtpReceiver<"u"?RTCRtpReceiver.getCapabilities?.("video")?.codecs:void 0;if(!n)continue;let i=n.filter(s=>s.mimeType==="video/H264"),o=n.filter(s=>s.mimeType!=="video/H264");if(i.length>0&&typeof t.setCodecPreferences=="function")try{t.setCodecPreferences([...i,...o])}catch{}}}}_preferH264InSdp(e){let t=e.split(`\r
2
- `),n=[],i=[];for(let o of t)if(o.includes("a=rtpmap:")&&o.toLowerCase().includes("h264")){let s=o.match(/a=rtpmap:(\d+)/);s&&i.push(s[1])}for(let o of t){if(o.startsWith("m=video")&&i.length>0){let s=o.split(" "),f=s.slice(0,3).join(" "),c=s.slice(3),a=[...i,...c.filter(u=>!i.includes(u))];n.push(`${f} ${a.join(" ")}`);continue}n.push(o)}return n.join(`\r
3
- `)}_applyH264SdpFallback(e,t){return t.getTransceivers&&t.getTransceivers().some(i=>typeof i.setCodecPreferences=="function")?e:this._preferH264InSdp(e)}_addTracksToConnection(e,t){if(l.log(`add tracks from stream ${e.id} to peer connection`),!t.addTrack){l.error("Your browser doesn't support RTCPeerConnection#addTrack. Ignored.");return}e.getTracks().forEach(n=>{t.addTrack(n,e)})}_addStreamToMediaConnection(e,t){l.log(`add stream ${e.id} to media connection ${t.connectionId}`),t.addStream(e)}};var we=()=>Math.random().toString(36).slice(2);var T=class r extends O{static ID_PREFIX="dc_";static MAX_BUFFERED_AMOUNT=8*1024*1024;_negotiator;reliable;get type(){return"data"}constructor(e,t,n){super(e,t,n),this.connectionId=this.options.connectionId||r.ID_PREFIX+we(),this.label=this.options.label||this.connectionId,this.reliable=!!this.options.reliable,this._negotiator=new F(this),this._negotiator.startConnection(this.options._payload||{originator:!0,reliable:this.reliable})}_initializeDataChannel(e){this.dataChannel=e,this.dataChannel.onopen=()=>{l.log(`DC#${this.connectionId} dc connection success`),this._open=!0,this.emit("open")},this.dataChannel.onclose=()=>{l.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}_flushCloseTimeout=null;close(e){if(e?.flush){this.send({__peerData:{type:"close"}}),this._flushCloseTimeout=setTimeout(()=>{this._flushCloseTimeout=null,this.close()},5e3);return}this._flushCloseTimeout&&(clearTimeout(this._flushCloseTimeout),this._flushCloseTimeout=null),this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this.dataChannel=null),this.open&&(this._open=!1,super.emit("close"),this.removeAllListeners())}send(e,t=!1){if(!this.open){this.emitError("not-open-yet","Connection is not open. You should listen for the `open` event before sending messages.");return}return this._send(e,t)}async handleMessage(e){let t=e.payload;switch(e.type){case"ANSWER":this._negotiator&&await this._negotiator.handleSDP(e.type,t.sdp);break;case"CANDIDATE":this._negotiator&&await this._negotiator.handleCandidate(t.candidate);break;default:l.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}}};var N=class extends T{_CHUNK_SIZE=1024*8*4;_splitStream=new TransformStream({transform:(e,t)=>{for(let n=0;n<e.length;n+=this._CHUNK_SIZE)t.enqueue(e.subarray(n,n+this._CHUNK_SIZE))}});_rawSendStream=new WritableStream({write:async(e,t)=>{if(this.dataChannel&&this.dataChannel.bufferedAmount>T.MAX_BUFFERED_AMOUNT-e.byteLength&&await new Promise((n,i)=>{let o=()=>{f(),n()},s=()=>{f(),i(new Error("DataChannel closed while waiting for buffer drain"))},f=()=>{this.dataChannel?.removeEventListener("bufferedamountlow",o),this.dataChannel?.removeEventListener("close",s)};this.dataChannel?.addEventListener("bufferedamountlow",o,{once:!0}),this.dataChannel?.addEventListener("close",s,{once:!0})}),!this.dataChannel||this.dataChannel.readyState!=="open"){t.error(new Error("DataChannel is not open"));return}try{this.dataChannel.send(e)}catch(n){l.error(`DC#:${this.connectionId} Error when sending:`,n),t.error(n),this.close()}}});writer=this._splitStream.writable.getWriter();_readStreamMessageHandler=null;_readStreamController=null;_rawReadStream=new ReadableStream({start:e=>{this._readStreamController=e,this.once("open",()=>{this.dataChannel&&(this._readStreamMessageHandler=t=>{e.enqueue(t.data)},this.dataChannel.addEventListener("message",this._readStreamMessageHandler))})}});constructor(e,t,n){super(e,t,{...n,reliable:!0}),this._splitStream.readable.pipeTo(this._rawSendStream)}_initializeDataChannel(e){super._initializeDataChannel(e),this.dataChannel.binaryType="arraybuffer",this.dataChannel.bufferedAmountLowThreshold=T.MAX_BUFFERED_AMOUNT/2}close(e){this.dataChannel&&this._readStreamMessageHandler&&(this.dataChannel.removeEventListener("message",this._readStreamMessageHandler),this._readStreamMessageHandler=null),super.close(e);try{this.writer.abort()}catch{}if(this._readStreamController){try{this._readStreamController.close()}catch{}this._readStreamController=null}}};var j=class extends N{serialization="MsgPack";_encoder=new X;constructor(e,t,n){super(e,t,n),(async()=>{for await(let i of q(this._rawReadStream)){if(i?.__peerData?.type==="close"){this.close();return}this.emit("data",i)}})().catch(i=>{this.open&&l.error(`DC#${this.connectionId} MsgPack decode error:`,i)})}_send(e){return this.writer.write(this._encoder.encode(e))}};0&&(module.exports={MsgPack});
1
+ "use strict";var ge=Object.create;var b=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var _e=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var Se=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Ue=(i,e)=>{for(var t in e)b(i,t,{get:e[t],enumerable:!0})},ee=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ce(e))!Te.call(i,r)&&r!==t&&b(i,r,{get:()=>e[r],enumerable:!(n=Ee(e,r))||n.enumerable});return i};var De=(i,e,t)=>(t=i!=null?ge(_e(i)):{},ee(e||!i||!i.__esModule?b(t,"default",{value:i,enumerable:!0}):t,i)),Ie=i=>ee(b({},"__esModule",{value:!0}),i);var me=Se((Yt,Z)=>{"use strict";var rt=Object.prototype.hasOwnProperty,m="~";function I(){}Object.create&&(I.prototype=Object.create(null),new I().__proto__||(m=!1));function it(i,e,t){this.fn=i,this.context=e,this.once=t||!1}function ye(i,e,t,n,r){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new it(t,n||i,r),s=m?m+e:e;return i._events[s]?i._events[s].fn?i._events[s]=[i._events[s],o]:i._events[s].push(o):(i._events[s]=o,i._eventsCount++),i}function B(i,e){--i._eventsCount===0?i._events=new I:delete i._events[e]}function y(){this._events=new I,this._eventsCount=0}y.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)rt.call(t,n)&&e.push(m?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};y.prototype.listeners=function(e){var t=m?m+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var r=0,o=n.length,s=new Array(o);r<o;r++)s[r]=n[r].fn;return s};y.prototype.listenerCount=function(e){var t=m?m+e:e,n=this._events[t];return n?n.fn?1:n.length:0};y.prototype.emit=function(e,t,n,r,o,s){var f=m?m+e:e;if(!this._events[f])return!1;var c=this._events[f],a=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),a){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,r),!0;case 5:return c.fn.call(c.context,t,n,r,o),!0;case 6:return c.fn.call(c.context,t,n,r,o,s),!0}for(d=1,u=new Array(a-1);d<a;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var h=c.length,p;for(d=0;d<h;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),a){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,r);break;default:if(!u)for(p=1,u=new Array(a-1);p<a;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0};y.prototype.on=function(e,t,n){return ye(this,e,t,n,!1)};y.prototype.once=function(e,t,n){return ye(this,e,t,n,!0)};y.prototype.removeListener=function(e,t,n,r){var o=m?m+e:e;if(!this._events[o])return this;if(!t)return B(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!r||s.once)&&(!n||s.context===n)&&B(this,o);else{for(var f=0,c=[],a=s.length;f<a;f++)(s[f].fn!==t||r&&!s[f].once||n&&s[f].context!==n)&&c.push(s[f]);c.length?this._events[o]=c.length===1?c[0]:c:B(this,o)}return this};y.prototype.removeAllListeners=function(e){var t;return e?(t=m?m+e:e,this._events[t]&&B(this,t)):(this._events=new I,this._eventsCount=0),this};y.prototype.off=y.prototype.removeListener;y.prototype.addListener=y.prototype.on;y.prefixed=m;y.EventEmitter=y;typeof Z<"u"&&(Z.exports=y)});var ot={};Ue(ot,{MsgPack:()=>j});module.exports=Ie(ot);var w=4294967295;function te(i,e,t){var n=t/4294967296,r=t;i.setUint32(e,n),i.setUint32(e+4,r)}function A(i,e,t){var n=Math.floor(t/4294967296),r=t;i.setUint32(e,n),i.setUint32(e+4,r)}function L(i,e){var t=i.getInt32(e),n=i.getUint32(e+4);return t*4294967296+n}function ne(i,e){var t=i.getUint32(e),n=i.getUint32(e+4);return t*4294967296+n}var H,W,$,M=(typeof process>"u"||((H=process==null?void 0:process.env)===null||H===void 0?void 0:H.TEXT_ENCODING)!=="never")&&typeof TextEncoder<"u"&&typeof TextDecoder<"u";function V(i){for(var e=i.length,t=0,n=0;n<e;){var r=i.charCodeAt(n++);if((r&4294967168)===0){t++;continue}else if((r&4294965248)===0)t+=2;else{if(r>=55296&&r<=56319&&n<e){var o=i.charCodeAt(n);(o&64512)===56320&&(++n,r=((r&1023)<<10)+(o&1023)+65536)}(r&4294901760)===0?t+=3:t+=4}}return t}function re(i,e,t){for(var n=i.length,r=t,o=0;o<n;){var s=i.charCodeAt(o++);if((s&4294967168)===0){e[r++]=s;continue}else if((s&4294965248)===0)e[r++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&o<n){var f=i.charCodeAt(o);(f&64512)===56320&&(++o,s=((s&1023)<<10)+(f&1023)+65536)}(s&4294901760)===0?(e[r++]=s>>12&15|224,e[r++]=s>>6&63|128):(e[r++]=s>>18&7|240,e[r++]=s>>12&63|128,e[r++]=s>>6&63|128)}e[r++]=s&63|128}}var S=M?new TextEncoder:void 0,ie=M?typeof process<"u"&&((W=process==null?void 0:process.env)===null||W===void 0?void 0:W.TEXT_ENCODING)!=="force"?200:0:w;function be(i,e,t){e.set(S.encode(i),t)}function Ae(i,e,t){S.encodeInto(i,e.subarray(t))}var oe=S?.encodeInto?Ae:be,Le=4096;function R(i,e,t){for(var n=e,r=n+t,o=[],s="";n<r;){var f=i[n++];if((f&128)===0)o.push(f);else if((f&224)===192){var c=i[n++]&63;o.push((f&31)<<6|c)}else if((f&240)===224){var c=i[n++]&63,a=i[n++]&63;o.push((f&31)<<12|c<<6|a)}else if((f&248)===240){var c=i[n++]&63,a=i[n++]&63,u=i[n++]&63,d=(f&7)<<18|c<<12|a<<6|u;d>65535&&(d-=65536,o.push(d>>>10&1023|55296),d=56320|d&1023),o.push(d)}else o.push(f);o.length>=Le&&(s+=String.fromCharCode.apply(String,o),o.length=0)}return o.length>0&&(s+=String.fromCharCode.apply(String,o)),s}var Me=M?new TextDecoder:null,se=M?typeof process<"u"&&(($=process==null?void 0:process.env)===null||$===void 0?void 0:$.TEXT_DECODER)!=="force"?200:0:w;function ae(i,e,t){var n=i.subarray(e,e+t);return Me.decode(n)}var U=(function(){function i(e,t){this.type=e,this.data=t}return i})();var Re=(function(){var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},i(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");i(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),x=(function(i){Re(e,i);function e(t){var n=i.call(this,t)||this,r=Object.create(e.prototype);return Object.setPrototypeOf(n,r),Object.defineProperty(n,"name",{configurable:!0,enumerable:!1,value:e.name}),n}return e})(Error);var ke=-1,Pe=4294967296-1,Be=17179869184-1;function ze(i){var e=i.sec,t=i.nsec;if(e>=0&&t>=0&&e<=Be)if(t===0&&e<=Pe){var n=new Uint8Array(4),r=new DataView(n.buffer);return r.setUint32(0,e),n}else{var o=e/4294967296,s=e&4294967295,n=new Uint8Array(8),r=new DataView(n.buffer);return r.setUint32(0,t<<2|o&3),r.setUint32(4,s),n}else{var n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,t),A(r,4,e),n}}function Fe(i){var e=i.getTime(),t=Math.floor(e/1e3),n=(e-t*1e3)*1e6,r=Math.floor(n/1e9);return{sec:t+r,nsec:n-r*1e9}}function Oe(i){if(i instanceof Date){var e=Fe(i);return ze(e)}else return null}function Ne(i){var e=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(i.byteLength){case 4:{var t=e.getUint32(0),n=0;return{sec:t,nsec:n}}case 8:{var r=e.getUint32(0),o=e.getUint32(4),t=(r&3)*4294967296+o,n=r>>>2;return{sec:t,nsec:n}}case 12:{var t=L(e,4),n=e.getUint32(0);return{sec:t,nsec:n}}default:throw new x("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(i.length))}}function He(i){var e=Ne(i);return new Date(e.sec*1e3+e.nsec/1e6)}var ce={type:ke,encode:Oe,decode:He};var k=(function(){function i(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(ce)}return i.prototype.register=function(e){var t=e.type,n=e.encode,r=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=r;else{var o=1+t;this.builtInEncoders[o]=n,this.builtInDecoders[o]=r}},i.prototype.tryToEncode=function(e,t){for(var n=0;n<this.builtInEncoders.length;n++){var r=this.builtInEncoders[n];if(r!=null){var o=r(e,t);if(o!=null){var s=-1-n;return new U(s,o)}}}for(var n=0;n<this.encoders.length;n++){var r=this.encoders[n];if(r!=null){var o=r(e,t);if(o!=null){var s=n;return new U(s,o)}}}return e instanceof U?e:null},i.prototype.decode=function(e,t,n){var r=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return r?r(e,t,n):new U(t,e)},i.defaultCodec=new i,i})();function E(i){return i instanceof Uint8Array?i:ArrayBuffer.isView(i)?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):i instanceof ArrayBuffer?new Uint8Array(i):Uint8Array.from(i)}function fe(i){if(i instanceof ArrayBuffer)return new DataView(i);var e=E(i);return new DataView(e.buffer,e.byteOffset,e.byteLength)}var We=100,$e=2048,X=(function(){function i(e,t,n,r,o,s,f,c){e===void 0&&(e=k.defaultCodec),t===void 0&&(t=void 0),n===void 0&&(n=We),r===void 0&&(r=$e),o===void 0&&(o=!1),s===void 0&&(s=!1),f===void 0&&(f=!1),c===void 0&&(c=!1),this.extensionCodec=e,this.context=t,this.maxDepth=n,this.initialBufferSize=r,this.sortKeys=o,this.forceFloat32=s,this.ignoreUndefined=f,this.forceIntegerToFloat=c,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return i.prototype.reinitializeState=function(){this.pos=0},i.prototype.encodeSharedRef=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)},i.prototype.encode=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)},i.prototype.doEncode=function(e,t){if(t>this.maxDepth)throw new Error("Too deep objects in depth ".concat(t));e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.encodeObject(e,t)},i.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)},i.prototype.resizeBuffer=function(e){var t=new ArrayBuffer(e),n=new Uint8Array(t),r=new DataView(t);n.set(this.bytes),this.view=r,this.bytes=n},i.prototype.encodeNil=function(){this.writeU8(192)},i.prototype.encodeBoolean=function(e){e===!1?this.writeU8(194):this.writeU8(195)},i.prototype.encodeNumber=function(e){Number.isSafeInteger(e)&&!this.forceIntegerToFloat?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},i.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error("Too long string: ".concat(e," bytes in UTF-8"))},i.prototype.encodeString=function(e){var t=5,n=e.length;if(n>ie){var r=V(e);this.ensureBufferSizeToWrite(t+r),this.writeStringHeader(r),oe(e,this.bytes,this.pos),this.pos+=r}else{var r=V(e);this.ensureBufferSizeToWrite(t+r),this.writeStringHeader(r),re(e,this.bytes,this.pos),this.pos+=r}},i.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)))},i.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error("Too large binary: ".concat(t));var n=E(e);this.writeU8a(n)},i.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error("Too large array: ".concat(n));for(var r=0,o=e;r<o.length;r++){var s=o[r];this.doEncode(s,t+1)}},i.prototype.countWithoutUndefined=function(e,t){for(var n=0,r=0,o=t;r<o.length;r++){var s=o[r];e[s]!==void 0&&n++}return n},i.prototype.encodeMap=function(e,t){var n=Object.keys(e);this.sortKeys&&n.sort();var r=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(r<16)this.writeU8(128+r);else if(r<65536)this.writeU8(222),this.writeU16(r);else if(r<4294967296)this.writeU8(223),this.writeU32(r);else throw new Error("Too large map object: ".concat(r));for(var o=0,s=n;o<s.length;o++){var f=s[o],c=e[f];this.ignoreUndefined&&c===void 0||(this.encodeString(f),this.doEncode(c,t+1))}},i.prototype.encodeExtension=function(e){var t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error("Too large extension object: ".concat(t));this.writeI8(e.type),this.writeU8a(e.data)},i.prototype.writeU8=function(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++},i.prototype.writeU8a=function(e){var t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t},i.prototype.writeI8=function(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++},i.prototype.writeU16=function(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2},i.prototype.writeI16=function(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2},i.prototype.writeU32=function(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4},i.prototype.writeI32=function(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4},i.prototype.writeF32=function(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4},i.prototype.writeF64=function(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8},i.prototype.writeU64=function(e){this.ensureBufferSizeToWrite(8),te(this.view,this.pos,e),this.pos+=8},i.prototype.writeI64=function(e){this.ensureBufferSizeToWrite(8),A(this.view,this.pos,e),this.pos+=8},i})();function P(i){return"".concat(i<0?"-":"","0x").concat(Math.abs(i).toString(16).padStart(2,"0"))}var Ve=16,Xe=16,le=(function(){function i(e,t){e===void 0&&(e=Ve),t===void 0&&(t=Xe),this.maxKeyLength=e,this.maxLengthPerKey=t,this.hit=0,this.miss=0,this.caches=[];for(var n=0;n<this.maxKeyLength;n++)this.caches.push([])}return i.prototype.canBeCached=function(e){return e>0&&e<=this.maxKeyLength},i.prototype.find=function(e,t,n){var r=this.caches[n-1];e:for(var o=0,s=r;o<s.length;o++){for(var f=s[o],c=f.bytes,a=0;a<n;a++)if(c[a]!==e[t+a])continue e;return f.str}return null},i.prototype.store=function(e,t){var n=this.caches[e.length-1],r={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)},i.prototype.decode=function(e,t,n){var r=this.find(e,t,n);if(r!=null)return this.hit++,r;this.miss++;var o=R(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,o),o},i})();var Ge=function(i,e,t,n){function r(o){return o instanceof t?o:new t(function(s){s(o)})}return new(t||(t=Promise))(function(o,s){function f(u){try{a(n.next(u))}catch(d){s(d)}}function c(u){try{a(n.throw(u))}catch(d){s(d)}}function a(u){u.done?o(u.value):r(u.value).then(f,c)}a((n=n.apply(i,e||[])).next())})},G=function(i,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,r,o,s;return s={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function f(a){return function(u){return c([a,u])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,r&&(o=a[0]&2?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[a[0]&2,o.value]),a[0]){case 0:case 1:o=a;break;case 4:return t.label++,{value:a[1],done:!1};case 5:t.label++,r=a[1],a=[0];continue;case 7:a=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(a[0]===6||a[0]===2)){t=0;continue}if(a[0]===3&&(!o||a[1]>o[0]&&a[1]<o[3])){t.label=a[1];break}if(a[0]===6&&t.label<o[1]){t.label=o[1],o=a;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(a);break}o[2]&&t.ops.pop(),t.trys.pop();continue}a=e.call(i,t)}catch(u){a=[6,u],r=0}finally{n=o=0}if(a[0]&5)throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},de=function(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof __values=="function"?__values(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(o){t[o]=i[o]&&function(s){return new Promise(function(f,c){s=i[o](s),r(f,c,s.done,s.value)})}}function r(o,s,f,c){Promise.resolve(c).then(function(a){o({value:a,done:f})},s)}},C=function(i){return this instanceof C?(this.v=i,this):new C(i)},Ke=function(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(i,e||[]),r,o=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(h){n[h]&&(r[h]=function(p){return new Promise(function(v,g){o.push([h,p,v,g])>1||f(h,p)})})}function f(h,p){try{c(n[h](p))}catch(v){d(o[0][3],v)}}function c(h){h.value instanceof C?Promise.resolve(h.value.v).then(a,u):d(o[0][2],h)}function a(h){f("next",h)}function u(h){f("throw",h)}function d(h,p){h(p),o.shift(),o.length&&f(o[0][0],o[0][1])}},Ye=function(i){var e=typeof i;return e==="string"||e==="number"},D=-1,Y=new DataView(new ArrayBuffer(0)),qe=new Uint8Array(Y.buffer),K=(function(){try{Y.getInt8(0)}catch(i){return i.constructor}throw new Error("never reached")})(),he=new K("Insufficient data"),Je=new le,ue=(function(){function i(e,t,n,r,o,s,f,c){e===void 0&&(e=k.defaultCodec),t===void 0&&(t=void 0),n===void 0&&(n=w),r===void 0&&(r=w),o===void 0&&(o=w),s===void 0&&(s=w),f===void 0&&(f=w),c===void 0&&(c=Je),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=s,this.maxExtLength=f,this.keyDecoder=c,this.totalPos=0,this.pos=0,this.view=Y,this.bytes=qe,this.headByte=D,this.stack=[]}return i.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=D,this.stack.length=0},i.prototype.setBuffer=function(e){this.bytes=E(e),this.view=fe(this.bytes),this.pos=0},i.prototype.appendBuffer=function(e){if(this.headByte===D&&!this.hasRemaining(1))this.setBuffer(e);else{var t=this.bytes.subarray(this.pos),n=E(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}},i.prototype.hasRemaining=function(e){return this.view.byteLength-this.pos>=e},i.prototype.createExtraByteError=function(e){var t=this,n=t.view,r=t.pos;return new RangeError("Extra ".concat(n.byteLength-r," of ").concat(n.byteLength," byte(s) found at buffer[").concat(e,"]"))},i.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},i.prototype.decodeMulti=function(e){return G(this,function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}})},i.prototype.decodeAsync=function(e){var t,n,r,o;return Ge(this,void 0,void 0,function(){var s,f,c,a,u,d,h,p;return G(this,function(v){switch(v.label){case 0:s=!1,v.label=1;case 1:v.trys.push([1,6,7,12]),t=de(e),v.label=2;case 2:return[4,t.next()];case 3:if(n=v.sent(),!!n.done)return[3,5];if(c=n.value,s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{f=this.doDecodeSync(),s=!0}catch(g){if(!(g instanceof K))throw g}this.totalPos+=this.pos,v.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return a=v.sent(),r={error:a},[3,12];case 7:return v.trys.push([7,,10,11]),n&&!n.done&&(o=t.return)?[4,o.call(t)]:[3,9];case 8:v.sent(),v.label=9;case 9:return[3,11];case 10:if(r)throw r.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,f]}throw u=this,d=u.headByte,h=u.pos,p=u.totalPos,new RangeError("Insufficient data in parsing ".concat(P(d)," at ").concat(p," (").concat(h," in the current buffer)"))}})})},i.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},i.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},i.prototype.decodeMultiAsync=function(e,t){return Ke(this,arguments,function(){var r,o,s,f,c,a,u,d,h;return G(this,function(p){switch(p.label){case 0:r=t,o=-1,p.label=1;case 1:p.trys.push([1,13,14,19]),s=de(e),p.label=2;case 2:return[4,C(s.next())];case 3:if(f=p.sent(),!!f.done)return[3,12];if(c=f.value,t&&o===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c),r&&(o=this.readArraySize(),r=!1,this.complete()),p.label=4;case 4:p.trys.push([4,9,,10]),p.label=5;case 5:return[4,C(this.doDecodeSync())];case 6:return[4,p.sent()];case 7:return p.sent(),--o===0?[3,8]:[3,5];case 8:return[3,10];case 9:if(a=p.sent(),!(a instanceof K))throw a;return[3,10];case 10:this.totalPos+=this.pos,p.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return u=p.sent(),d={error:u},[3,19];case 14:return p.trys.push([14,,17,18]),f&&!f.done&&(h=s.return)?[4,C(h.call(s))]:[3,16];case 15:p.sent(),p.label=16;case 16:return[3,18];case 17:if(d)throw d.error;return[7];case 18:return[7];case 19:return[2]}})})},i.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){var n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e<160){var n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else{var r=e-160;t=this.decodeUtf8String(r,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)t=this.readI64();else if(e===217){var r=this.lookU8();t=this.decodeUtf8String(r,1)}else if(e===218){var r=this.lookU16();t=this.decodeUtf8String(r,2)}else if(e===219){var r=this.lookU32();t=this.decodeUtf8String(r,4)}else if(e===220){var n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===221){var n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else t=[]}else if(e===222){var n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===223){var n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else t={}}else if(e===196){var n=this.lookU8();t=this.decodeBinary(n,1)}else if(e===197){var n=this.lookU16();t=this.decodeBinary(n,2)}else if(e===198){var n=this.lookU32();t=this.decodeBinary(n,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){var n=this.lookU8();t=this.decodeExtension(n,1)}else if(e===200){var n=this.lookU16();t=this.decodeExtension(n,2)}else if(e===201){var n=this.lookU32();t=this.decodeExtension(n,4)}else throw new x("Unrecognized type byte: ".concat(P(e)));this.complete();for(var o=this.stack;o.length>0;){var s=o[o.length-1];if(s.type===0)if(s.array[s.position]=t,s.position++,s.position===s.size)o.pop(),t=s.array;else continue e;else if(s.type===1){if(!Ye(t))throw new x("The type of key must be string or number but "+typeof t);if(t==="__proto__")throw new x("The key __proto__ is not allowed");s.key=t,s.type=2;continue e}else if(s.map[s.key]=t,s.readCount++,s.readCount===s.size)o.pop(),t=s.map;else{s.key=null,s.type=1;continue e}}return t}},i.prototype.readHeadByte=function(){return this.headByte===D&&(this.headByte=this.readU8()),this.headByte},i.prototype.complete=function(){this.headByte=D},i.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new x("Unrecognized array type byte: ".concat(P(e)))}}},i.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new x("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},i.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new x("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},i.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new x("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLength<this.pos+t+e)throw he;var r=this.pos+t,o;return this.stateIsMapKey()&&(!((n=this.keyDecoder)===null||n===void 0)&&n.canBeCached(e))?o=this.keyDecoder.decode(this.bytes,r,e):e>se?o=ae(this.bytes,r,e):o=R(this.bytes,r,e),this.pos+=t+e,o},i.prototype.stateIsMapKey=function(){if(this.stack.length>0){var e=this.stack[this.stack.length-1];return e.type===1}return!1},i.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new x("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw he;var n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r},i.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new x("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,this.context)},i.prototype.lookU8=function(){return this.view.getUint8(this.pos)},i.prototype.lookU16=function(){return this.view.getUint16(this.pos)},i.prototype.lookU32=function(){return this.view.getUint32(this.pos)},i.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},i.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},i.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},i.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},i.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},i.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},i.prototype.readU64=function(){var e=ne(this.view,this.pos);return this.pos+=8,e},i.prototype.readI64=function(){var e=L(this.view,this.pos);return this.pos+=8,e},i.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},i.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},i})();var pe={};var Ze=function(i,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,r,o,s;return s={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function f(a){return function(u){return c([a,u])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,r&&(o=a[0]&2?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[a[0]&2,o.value]),a[0]){case 0:case 1:o=a;break;case 4:return t.label++,{value:a[1],done:!1};case 5:t.label++,r=a[1],a=[0];continue;case 7:a=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(a[0]===6||a[0]===2)){t=0;continue}if(a[0]===3&&(!o||a[1]>o[0]&&a[1]<o[3])){t.label=a[1];break}if(a[0]===6&&t.label<o[1]){t.label=o[1],o=a;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(a);break}o[2]&&t.ops.pop(),t.trys.pop();continue}a=e.call(i,t)}catch(u){a=[6,u],r=0}finally{n=o=0}if(a[0]&5)throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},_=function(i){return this instanceof _?(this.v=i,this):new _(i)},Qe=function(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(i,e||[]),r,o=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(h){n[h]&&(r[h]=function(p){return new Promise(function(v,g){o.push([h,p,v,g])>1||f(h,p)})})}function f(h,p){try{c(n[h](p))}catch(v){d(o[0][3],v)}}function c(h){h.value instanceof _?Promise.resolve(h.value.v).then(a,u):d(o[0][2],h)}function a(h){f("next",h)}function u(h){f("throw",h)}function d(h,p){h(p),o.shift(),o.length&&f(o[0][0],o[0][1])}};function je(i){return i[Symbol.asyncIterator]!=null}function et(i){if(i==null)throw new Error("Assertion Failure: value must not be null nor undefined")}function tt(i){return Qe(this,arguments,function(){var t,n,r,o;return Ze(this,function(s){switch(s.label){case 0:t=i.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,_(t.read())];case 3:return n=s.sent(),r=n.done,o=n.value,r?[4,_(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return et(o),[4,_(o)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function ve(i){return je(i)?i:tt(i)}function q(i,e){e===void 0&&(e=pe);var t=ve(i),n=new ue(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength);return n.decodeStream(t)}var nt="Dendri: ";var J=class{_logLevel=0;get logLevel(){return this._logLevel}set logLevel(e){this._logLevel=e}log(...e){this._logLevel>=3&&this._print(3,...e)}warn(...e){this._logLevel>=2&&this._print(2,...e)}error(...e){this._logLevel>=1&&this._print(1,...e)}setLogFunction(e){this._print=e}_print(e,...t){let n=[nt,...t];for(let r in n)n[r]instanceof Error&&(n[r]=`(${n[r].name}) ${n[r].message}`);e>=3?console.log(...n):e>=2?console.warn("WARNING",...n):e>=1&&console.error("ERROR",...n)}},l=new J;var xe=De(me(),1);var z=class extends xe.EventEmitter{emitError(e,t,n=!1){l.error("Error:",t);let r=new Q(`${e}`,t);r.retryable=n,this.emit("error",r)}},Q=class extends Error{type;retryable;details;constructor(e,t){typeof t=="string"?super(t):(super(t.message),this.stack=t.stack),this.type=e,this.retryable=!1}setRetryable(e){return this.retryable=e,this}setDetails(e){return this.details=e,this}};var F=class extends z{constructor(t,n,r){super();this.peer=t;this.provider=n;this.options=r;this.metadata=r.metadata}peer;provider;options;_open=!1;metadata;connectionId;peerConnection;dataChannel=null;label;get open(){return this._open}};var O=class{constructor(e){this.connection=e}connection;_pendingCandidates=[];_iceCandidateFilter=null;startConnection(e){let t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type==="media"&&e._stream&&(this._addTracksToConnection(e._stream,t),this._setCodecPreferences(t)),e.originator){let n=this.connection,r={ordered:!!e.reliable},o=t.createDataChannel(n.label,r);n._initializeDataChannel(o),this._makeOffer()}else this.handleSDP("OFFER",e.sdp)}_startPeerConnection(){l.log("Creating RTCPeerConnection.");let e=new RTCPeerConnection(this.connection.provider?.options.config);if(this.connection.provider?.options.ipPolicy==="public"){let t=n=>!(n.candidate??"").includes("typ host");this._iceCandidateFilter=t}return this._setupListeners(e),e}_setupListeners(e){let t=this.connection.peer,n=this.connection.connectionId,r=this.connection.type,o=this.connection.provider;l.log("Listening for ICE candidates."),e.onicecandidate=s=>{s.candidate?.candidate&&(this._iceCandidateFilter&&!this._iceCandidateFilter(s.candidate)||(l.log(`Received ICE candidates for ${t}:`,s.candidate),o.socket.send({type:"CANDIDATE",payload:{candidate:s.candidate,type:r,connectionId:n},dst:t})))},e.oniceconnectionstatechange=()=>{switch(e.iceConnectionState){case"failed":l.log(`iceConnectionState is failed, closing connections to ${t}`),this.connection.emitError("negotiation-failed",`Negotiation of connection to ${t} failed.`),this.connection.close();break;case"closed":l.log(`iceConnectionState is closed, closing connections to ${t}`),this.connection.emitError("connection-closed",`Connection to ${t} closed.`),this.connection.close();break;case"disconnected":l.log(`iceConnectionState changed to disconnected on the connection with ${t}`);break;case"completed":e.onicecandidate=()=>{};break}this.connection.emit("iceStateChanged",e.iceConnectionState)},l.log("Listening for data channel"),e.ondatachannel=s=>{l.log("Received data channel");let f=s.channel,c=o.getConnection(t,n);if(!c){l.warn(`Received data channel for non-existent connection ${n}`);return}c._initializeDataChannel(f)},l.log("Listening for remote stream"),e.ontrack=s=>{l.log("Received remote stream");let f=s.streams[0],c=o.getConnection(t,n);if(!c){l.warn(`Received remote stream for non-existent connection ${n}`);return}if(c.type==="media"){let a=c;this._addStreamToMediaConnection(f,a)}}}cleanup(){l.log(`Cleaning up PeerConnection to ${this.connection.peer}`);let e=this.connection.peerConnection;if(!e)return;this.connection.peerConnection=null,this._pendingCandidates=[],e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=()=>{};let t=e.signalingState!=="closed",n=!1,r=this.connection.dataChannel;r&&(n=!!r.readyState&&r.readyState!=="closed",n&&r.close()),(t||n)&&e.close()}async _makeOffer(){let e=this.connection.peerConnection,t=this.connection.provider;try{let n=await e.createOffer(this.connection.options.constraints);if(!this.connection.peerConnection){l.log("PeerConnection closed during createOffer");return}l.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp),this.connection.type==="media"&&n.sdp&&(n.sdp=this._applyH264SdpFallback(n.sdp,e));try{if(await e.setLocalDescription(n),!this.connection.peerConnection){l.log("PeerConnection closed during setLocalDescription");return}l.log("Set localDescription:",n,`for:${this.connection.peer}`);let r={sdp:n,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata};if(this.connection.type==="data"){let o=this.connection;r={...r,label:o.label,reliable:o.reliable,serialization:o.serialization}}t.socket.send({type:"OFFER",payload:r,dst:this.connection.peer})}catch(r){r!=="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError("webrtc",r instanceof Error?r:String(r)),l.log("Failed to setLocalDescription, ",r))}}catch(n){t.emitError("webrtc",n instanceof Error?n:String(n)),l.log("Failed to createOffer, ",n)}}async _makeAnswer(){let e=this.connection.peerConnection,t=this.connection.provider;try{let n=await e.createAnswer();if(!this.connection.peerConnection){l.log("PeerConnection closed during createAnswer");return}l.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp),this.connection.type==="media"&&n.sdp&&(n.sdp=this._applyH264SdpFallback(n.sdp,e));try{if(await e.setLocalDescription(n),!this.connection.peerConnection){l.log("PeerConnection closed during setLocalDescription");return}l.log("Set localDescription:",n,`for:${this.connection.peer}`),t.socket.send({type:"ANSWER",payload:{sdp:n,type:this.connection.type,connectionId:this.connection.connectionId},dst:this.connection.peer})}catch(r){t.emitError("webrtc",r instanceof Error?r:String(r)),l.log("Failed to setLocalDescription, ",r)}}catch(n){t.emitError("webrtc",n instanceof Error?n:String(n)),l.log("Failed to create answer, ",n)}}async handleSDP(e,t){let n=this.connection.peerConnection,r=this.connection.provider;l.log("Setting remote description",t);try{if(await n.setRemoteDescription(t),!this.connection.peerConnection){l.log("PeerConnection closed during setRemoteDescription");return}if(l.log(`Set remoteDescription:${e} for:${this.connection.peer}`),this._pendingCandidates.length>0){l.log(`Flushing ${this._pendingCandidates.length} pending ICE candidates`);let o=this._pendingCandidates;this._pendingCandidates=[];for(let s of o)await this.handleCandidate(s)}e==="OFFER"&&await this._makeAnswer()}catch(o){r.emitError("webrtc",o instanceof Error?o:String(o)),l.log("Failed to setRemoteDescription, ",o)}}async handleCandidate(e){l.log("handleCandidate:",e);let t=this.connection.peerConnection;if(!t){l.warn(`PeerConnection not set for ${this.connection.peer}, cannot add ICE candidate`);return}if(!t.remoteDescription){l.log("Queueing ICE candidate (no remote description yet)"),this._pendingCandidates.push(e);return}try{await t.addIceCandidate(e),l.log(`Added ICE candidate for:${this.connection.peer}`)}catch(n){this.connection.provider?.emitError("webrtc",n instanceof Error?n:String(n)),l.log("Failed to handleCandidate, ",n)}}_setCodecPreferences(e){if(e.getTransceivers){for(let t of e.getTransceivers())if(t.sender?.track?.kind==="video"){let n=typeof RTCRtpReceiver<"u"?RTCRtpReceiver.getCapabilities?.("video")?.codecs:void 0;if(!n)continue;let r=n.filter(s=>s.mimeType==="video/H264"),o=n.filter(s=>s.mimeType!=="video/H264");if(r.length>0&&typeof t.setCodecPreferences=="function")try{t.setCodecPreferences([...r,...o])}catch{}}}}_preferH264InSdp(e){let t=e.split(`\r
2
+ `),n=[],r=[];for(let o of t)if(o.includes("a=rtpmap:")&&o.toLowerCase().includes("h264")){let s=o.match(/a=rtpmap:(\d+)/);s&&r.push(s[1])}for(let o of t){if(o.startsWith("m=video")&&r.length>0){let s=o.split(" "),f=s.slice(0,3).join(" "),c=s.slice(3),a=[...r,...c.filter(u=>!r.includes(u))];n.push(`${f} ${a.join(" ")}`);continue}n.push(o)}return n.join(`\r
3
+ `)}_applyH264SdpFallback(e,t){return t.getTransceivers&&t.getTransceivers().some(r=>typeof r.setCodecPreferences=="function")?e:this._preferH264InSdp(e)}_addTracksToConnection(e,t){if(l.log(`add tracks from stream ${e.id} to peer connection`),!t.addTrack){l.error("Your browser doesn't support RTCPeerConnection#addTrack. Ignored.");return}e.getTracks().forEach(n=>{t.addTrack(n,e)})}_addStreamToMediaConnection(e,t){l.log(`add stream ${e.id} to media connection ${t.connectionId}`),t.addStream(e)}};var we=()=>Math.random().toString(36).slice(2);var T=class i extends F{static ID_PREFIX="dc_";static MAX_BUFFERED_AMOUNT=8*1024*1024;_negotiator;reliable;get type(){return"data"}constructor(e,t,n){super(e,t,n),this.connectionId=this.options.connectionId||i.ID_PREFIX+we(),this.label=this.options.label||this.connectionId,this.reliable=!!this.options.reliable,this._negotiator=new O(this),this._negotiator.startConnection(this.options._payload||{originator:!0,reliable:this.reliable})}_initializeDataChannel(e){this.dataChannel=e,this.dataChannel.onopen=()=>{l.log(`DC#${this.connectionId} dc connection success`),this._open=!0,this._applyAdaptiveBuffer(e),this.emit("open")},this.dataChannel.onclose=()=>{l.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}_applyAdaptiveBuffer(e){let t=this.peerConnection;!t||typeof t.getStats!="function"||t.getStats().then(n=>{let r=null;if(n.forEach(o=>{o.type==="candidate-pair"&&o.state==="succeeded"&&o.currentRoundTripTime&&(r=o.currentRoundTripTime*1e3)}),r!==null){let o=13107200*(r/1e3),s=Math.max(1*1024*1024,Math.min(32*1024*1024,Math.ceil(o)));e.bufferedAmountLowThreshold=s}}).catch(()=>{})}_flushCloseTimeout=null;close(e){if(e?.flush){this.send({__peerData:{type:"close"}}),this._flushCloseTimeout=setTimeout(()=>{this._flushCloseTimeout=null,this.close()},5e3);return}this._flushCloseTimeout&&(clearTimeout(this._flushCloseTimeout),this._flushCloseTimeout=null),this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this.dataChannel=null),this.open&&(this._open=!1,super.emit("close"),this.removeAllListeners())}send(e,t=!1){if(!this.open){this.emitError("not-open-yet","Connection is not open. You should listen for the `open` event before sending messages.");return}return this._send(e,t)}async handleMessage(e){let t=e.payload;switch(e.type){case"ANSWER":this._negotiator&&await this._negotiator.handleSDP(e.type,t.sdp);break;case"CANDIDATE":this._negotiator&&await this._negotiator.handleCandidate(t.candidate);break;default:l.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}}};var N=class extends T{_CHUNK_SIZE=1024*8*4;_splitStream=new TransformStream({transform:(e,t)=>{for(let n=0;n<e.length;n+=this._CHUNK_SIZE)t.enqueue(e.subarray(n,n+this._CHUNK_SIZE))}});_rawSendStream=new WritableStream({write:async(e,t)=>{if(this.dataChannel&&this.dataChannel.bufferedAmount>T.MAX_BUFFERED_AMOUNT-e.byteLength&&await new Promise((n,r)=>{let o=()=>{f(),n()},s=()=>{f(),r(new Error("DataChannel closed while waiting for buffer drain"))},f=()=>{this.dataChannel?.removeEventListener("bufferedamountlow",o),this.dataChannel?.removeEventListener("close",s)};this.dataChannel?.addEventListener("bufferedamountlow",o,{once:!0}),this.dataChannel?.addEventListener("close",s,{once:!0})}),!this.dataChannel||this.dataChannel.readyState!=="open"){t.error(new Error("DataChannel is not open"));return}try{this.dataChannel.send(e)}catch(n){l.error(`DC#:${this.connectionId} Error when sending:`,n),t.error(n),this.close()}}});writer=this._splitStream.writable.getWriter();_readStreamMessageHandler=null;_readStreamController=null;_rawReadStream=new ReadableStream({start:e=>{this._readStreamController=e,this.once("open",()=>{this.dataChannel&&(this._readStreamMessageHandler=t=>{e.enqueue(t.data)},this.dataChannel.addEventListener("message",this._readStreamMessageHandler))})}});constructor(e,t,n){super(e,t,{...n,reliable:!0}),this._splitStream.readable.pipeTo(this._rawSendStream)}_initializeDataChannel(e){super._initializeDataChannel(e),this.dataChannel.binaryType="arraybuffer",this.dataChannel.bufferedAmountLowThreshold=T.MAX_BUFFERED_AMOUNT/2}close(e){this.dataChannel&&this._readStreamMessageHandler&&(this.dataChannel.removeEventListener("message",this._readStreamMessageHandler),this._readStreamMessageHandler=null),super.close(e);try{this.writer.abort()}catch{}if(this._readStreamController){try{this._readStreamController.close()}catch{}this._readStreamController=null}}};var j=class extends N{serialization="MsgPack";_encoder=new X;constructor(e,t,n){super(e,t,n),(async()=>{for await(let r of q(this._rawReadStream)){if(r?.__peerData?.type==="close"){this.close();return}this.emit("data",r)}})().catch(r=>{this.open&&l.error(`DC#${this.connectionId} MsgPack decode error:`,r)})}_send(e){return this.writer.write(this._encoder.encode(e))}};0&&(module.exports={MsgPack});
4
4
  //# sourceMappingURL=serializer.msgpack.cjs.map