@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
|
@@ -127,7 +127,10 @@ declare enum ServerMessageType {
|
|
|
127
127
|
RoomPeers = "ROOM-PEERS",// List of peers in a room.
|
|
128
128
|
HostMigrate = "HOST-MIGRATE",// Host migration notification.
|
|
129
129
|
PresenceUpdate = "PRESENCE-UPDATE",// Presence data broadcast.
|
|
130
|
-
KeyExchange = "KEY-EXCHANGE"
|
|
130
|
+
KeyExchange = "KEY-EXCHANGE",// E2E encryption key exchange for relay.
|
|
131
|
+
ConnectRequest = "CONNECT-REQUEST",// Address exchange for Connection Reversal (H1)
|
|
132
|
+
DcutrConnect = "DCUTR-CONNECT",// DCUtR hole punch address exchange (H2)
|
|
133
|
+
DcutrSync = "DCUTR-SYNC"
|
|
131
134
|
}
|
|
132
135
|
declare enum TransportMode {
|
|
133
136
|
WebRTC = "webrtc",
|
|
@@ -256,6 +259,7 @@ declare abstract class DataConnection extends BaseConnection<DataConnectionEvent
|
|
|
256
259
|
constructor(peerId: string, provider: Dendri, options: any);
|
|
257
260
|
/** Called by the Negotiator when the DataChannel is ready. */
|
|
258
261
|
_initializeDataChannel(dc: RTCDataChannel): void;
|
|
262
|
+
private _applyAdaptiveBuffer;
|
|
259
263
|
/**
|
|
260
264
|
* Exposed functionality for users.
|
|
261
265
|
*/
|
|
@@ -319,7 +323,7 @@ interface DendriOption {
|
|
|
319
323
|
config?: RTCConfiguration;
|
|
320
324
|
debug?: number;
|
|
321
325
|
referrerPolicy?: ReferrerPolicy;
|
|
322
|
-
/** Auto-fetch TURN credentials from the signaling server's GET /turn endpoint. */
|
|
326
|
+
/** Auto-fetch TURN credentials from the signaling server's GET /{key}/turn-credentials endpoint. */
|
|
323
327
|
fetchTurnCredentials?: boolean;
|
|
324
328
|
/** Optional JWT for authenticated connections. */
|
|
325
329
|
jwt?: string;
|
|
@@ -509,6 +513,9 @@ declare class HybridConnection extends EventEmitter<HybridConnectionEvents> {
|
|
|
509
513
|
* Respects `autoUpgrade`, `upgradeInterval`, and `maxUpgradeAttempts` options.
|
|
510
514
|
*/
|
|
511
515
|
private _scheduleUpgrade;
|
|
516
|
+
private _tryConnectionReversal;
|
|
517
|
+
private _gatherSrflxCandidates;
|
|
518
|
+
_dcutrHolePunch(): Promise<boolean>;
|
|
512
519
|
}
|
|
513
520
|
|
|
514
521
|
declare enum LogLevel {
|
|
@@ -642,7 +649,7 @@ declare class DendriOptions implements DendriOption {
|
|
|
642
649
|
*
|
|
643
650
|
* Defaults to {@apilink util.defaultConfig}
|
|
644
651
|
*/
|
|
645
|
-
config?:
|
|
652
|
+
config?: RTCConfiguration;
|
|
646
653
|
/**
|
|
647
654
|
* Set to true `true` if you're using TLS.
|
|
648
655
|
* :::danger
|
|
@@ -652,7 +659,7 @@ declare class DendriOptions implements DendriOption {
|
|
|
652
659
|
secure?: boolean;
|
|
653
660
|
pingInterval?: number;
|
|
654
661
|
referrerPolicy?: ReferrerPolicy;
|
|
655
|
-
logFunction?: (logLevel: LogLevel, ...rest:
|
|
662
|
+
logFunction?: (logLevel: LogLevel, ...rest: unknown[]) => void;
|
|
656
663
|
serializers?: SerializerMapping;
|
|
657
664
|
/** Auto-fetch TURN credentials from the signaling server's GET /turn endpoint. */
|
|
658
665
|
fetchTurnCredentials?: boolean;
|
|
@@ -664,6 +671,12 @@ declare class DendriOptions implements DendriOption {
|
|
|
664
671
|
validateMetadata?: (metadata: unknown) => boolean;
|
|
665
672
|
/** Signaling transport: 'websocket' (default), 'sse', 'polling', or 'auto' (tries WS then SSE then polling) */
|
|
666
673
|
signalingTransport?: "websocket" | "sse" | "polling" | "auto";
|
|
674
|
+
/**
|
|
675
|
+
* ICE candidate privacy policy.
|
|
676
|
+
* - 'all': RFC 8828 mode 1 — all candidates including host IPs (default)
|
|
677
|
+
* - 'public': RFC 8828 mode 3 — only STUN/TURN (srflx + relay) candidates
|
|
678
|
+
*/
|
|
679
|
+
ipPolicy?: "all" | "public";
|
|
667
680
|
}
|
|
668
681
|
|
|
669
682
|
interface SerializerMapping {
|
|
@@ -127,7 +127,10 @@ declare enum ServerMessageType {
|
|
|
127
127
|
RoomPeers = "ROOM-PEERS",// List of peers in a room.
|
|
128
128
|
HostMigrate = "HOST-MIGRATE",// Host migration notification.
|
|
129
129
|
PresenceUpdate = "PRESENCE-UPDATE",// Presence data broadcast.
|
|
130
|
-
KeyExchange = "KEY-EXCHANGE"
|
|
130
|
+
KeyExchange = "KEY-EXCHANGE",// E2E encryption key exchange for relay.
|
|
131
|
+
ConnectRequest = "CONNECT-REQUEST",// Address exchange for Connection Reversal (H1)
|
|
132
|
+
DcutrConnect = "DCUTR-CONNECT",// DCUtR hole punch address exchange (H2)
|
|
133
|
+
DcutrSync = "DCUTR-SYNC"
|
|
131
134
|
}
|
|
132
135
|
declare enum TransportMode {
|
|
133
136
|
WebRTC = "webrtc",
|
|
@@ -256,6 +259,7 @@ declare abstract class DataConnection extends BaseConnection<DataConnectionEvent
|
|
|
256
259
|
constructor(peerId: string, provider: Dendri, options: any);
|
|
257
260
|
/** Called by the Negotiator when the DataChannel is ready. */
|
|
258
261
|
_initializeDataChannel(dc: RTCDataChannel): void;
|
|
262
|
+
private _applyAdaptiveBuffer;
|
|
259
263
|
/**
|
|
260
264
|
* Exposed functionality for users.
|
|
261
265
|
*/
|
|
@@ -319,7 +323,7 @@ interface DendriOption {
|
|
|
319
323
|
config?: RTCConfiguration;
|
|
320
324
|
debug?: number;
|
|
321
325
|
referrerPolicy?: ReferrerPolicy;
|
|
322
|
-
/** Auto-fetch TURN credentials from the signaling server's GET /turn endpoint. */
|
|
326
|
+
/** Auto-fetch TURN credentials from the signaling server's GET /{key}/turn-credentials endpoint. */
|
|
323
327
|
fetchTurnCredentials?: boolean;
|
|
324
328
|
/** Optional JWT for authenticated connections. */
|
|
325
329
|
jwt?: string;
|
|
@@ -509,6 +513,9 @@ declare class HybridConnection extends EventEmitter<HybridConnectionEvents> {
|
|
|
509
513
|
* Respects `autoUpgrade`, `upgradeInterval`, and `maxUpgradeAttempts` options.
|
|
510
514
|
*/
|
|
511
515
|
private _scheduleUpgrade;
|
|
516
|
+
private _tryConnectionReversal;
|
|
517
|
+
private _gatherSrflxCandidates;
|
|
518
|
+
_dcutrHolePunch(): Promise<boolean>;
|
|
512
519
|
}
|
|
513
520
|
|
|
514
521
|
declare enum LogLevel {
|
|
@@ -642,7 +649,7 @@ declare class DendriOptions implements DendriOption {
|
|
|
642
649
|
*
|
|
643
650
|
* Defaults to {@apilink util.defaultConfig}
|
|
644
651
|
*/
|
|
645
|
-
config?:
|
|
652
|
+
config?: RTCConfiguration;
|
|
646
653
|
/**
|
|
647
654
|
* Set to true `true` if you're using TLS.
|
|
648
655
|
* :::danger
|
|
@@ -652,7 +659,7 @@ declare class DendriOptions implements DendriOption {
|
|
|
652
659
|
secure?: boolean;
|
|
653
660
|
pingInterval?: number;
|
|
654
661
|
referrerPolicy?: ReferrerPolicy;
|
|
655
|
-
logFunction?: (logLevel: LogLevel, ...rest:
|
|
662
|
+
logFunction?: (logLevel: LogLevel, ...rest: unknown[]) => void;
|
|
656
663
|
serializers?: SerializerMapping;
|
|
657
664
|
/** Auto-fetch TURN credentials from the signaling server's GET /turn endpoint. */
|
|
658
665
|
fetchTurnCredentials?: boolean;
|
|
@@ -664,6 +671,12 @@ declare class DendriOptions implements DendriOption {
|
|
|
664
671
|
validateMetadata?: (metadata: unknown) => boolean;
|
|
665
672
|
/** Signaling transport: 'websocket' (default), 'sse', 'polling', or 'auto' (tries WS then SSE then polling) */
|
|
666
673
|
signalingTransport?: "websocket" | "sse" | "polling" | "auto";
|
|
674
|
+
/**
|
|
675
|
+
* ICE candidate privacy policy.
|
|
676
|
+
* - 'all': RFC 8828 mode 1 — all candidates including host IPs (default)
|
|
677
|
+
* - 'public': RFC 8828 mode 3 — only STUN/TURN (srflx + relay) candidates
|
|
678
|
+
*/
|
|
679
|
+
ipPolicy?: "all" | "public";
|
|
667
680
|
}
|
|
668
681
|
|
|
669
682
|
interface SerializerMapping {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var we=Object.create;var Q=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var Ce=Object.getPrototypeOf,_e=Object.prototype.hasOwnProperty;var Te=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Se=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ee(e))!_e.call(i,r)&&r!==t&&Q(i,r,{get:()=>e[r],enumerable:!(n=ge(e,r))||n.enumerable});return i};var Ue=(i,e,t)=>(t=i!=null?we(Ce(i)):{},Se(e||!i||!i.__esModule?Q(t,"default",{value:i,enumerable:!0}):t,i));var ve=Te((Xt,J)=>{"use strict";var tt=Object.prototype.hasOwnProperty,m="~";function I(){}Object.create&&(I.prototype=Object.create(null),new I().__proto__||(m=!1));function nt(i,e,t){this.fn=i,this.context=e,this.once=t||!1}function pe(i,e,t,n,r){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new nt(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 P(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)tt.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 pe(this,e,t,n,!1)};y.prototype.once=function(e,t,n){return pe(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 P(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!r||s.once)&&(!n||s.context===n)&&P(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:P(this,o)}return this};y.prototype.removeAllListeners=function(e){var t;return e?(t=m?m+e:e,this._events[t]&&P(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 J<"u"&&(J.exports=y)});var w=4294967295;function j(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 b(i,e){var t=i.getInt32(e),n=i.getUint32(e+4);return t*4294967296+n}function ee(i,e){var t=i.getUint32(e),n=i.getUint32(e+4);return t*4294967296+n}var N,H,W,L=(typeof process>"u"||((N=process==null?void 0:process.env)===null||N===void 0?void 0:N.TEXT_ENCODING)!=="never")&&typeof TextEncoder<"u"&&typeof TextDecoder<"u";function $(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 te(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=L?new TextEncoder:void 0,ne=L?typeof process<"u"&&((H=process==null?void 0:process.env)===null||H===void 0?void 0:H.TEXT_ENCODING)!=="force"?200:0:w;function De(i,e,t){e.set(S.encode(i),t)}function Ie(i,e,t){S.encodeInto(i,e.subarray(t))}var re=S?.encodeInto?Ie:De,Ae=4096;function M(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>=Ae&&(s+=String.fromCharCode.apply(String,o),o.length=0)}return o.length>0&&(s+=String.fromCharCode.apply(String,o)),s}var be=L?new TextDecoder:null,ie=L?typeof process<"u"&&((W=process==null?void 0:process.env)===null||W===void 0?void 0:W.TEXT_DECODER)!=="force"?200:0:w;function oe(i,e,t){var n=i.subarray(e,e+t);return be.decode(n)}var U=(function(){function i(e,t){this.type=e,this.data=t}return i})();var Le=(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){Le(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 Me=-1,Re=4294967296-1,ke=17179869184-1;function Pe(i){var e=i.sec,t=i.nsec;if(e>=0&&t>=0&&e<=ke)if(t===0&&e<=Re){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 Be(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 ze(i){if(i instanceof Date){var e=Be(i);return Pe(e)}else return null}function Oe(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=b(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 Fe(i){var e=Oe(i);return new Date(e.sec*1e3+e.nsec/1e6)}var se={type:Me,encode:ze,decode:Fe};var R=(function(){function i(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(se)}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 ae(i){if(i instanceof ArrayBuffer)return new DataView(i);var e=E(i);return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Ne=100,He=2048,V=(function(){function i(e,t,n,r,o,s,f,c){e===void 0&&(e=R.defaultCodec),t===void 0&&(t=void 0),n===void 0&&(n=Ne),r===void 0&&(r=He),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>ne){var r=$(e);this.ensureBufferSizeToWrite(t+r),this.writeStringHeader(r),re(e,this.bytes,this.pos),this.pos+=r}else{var r=$(e);this.ensureBufferSizeToWrite(t+r),this.writeStringHeader(r),te(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),j(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 k(i){return"".concat(i<0?"-":"","0x").concat(Math.abs(i).toString(16).padStart(2,"0"))}var We=16,$e=16,ce=(function(){function i(e,t){e===void 0&&(e=We),t===void 0&&(t=$e),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=M(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,o),o},i})();var Ve=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())})},X=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}}},fe=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)},Xe=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])}},Ge=function(i){var e=typeof i;return e==="string"||e==="number"},D=-1,K=new DataView(new ArrayBuffer(0)),Ke=new Uint8Array(K.buffer),G=(function(){try{K.getInt8(0)}catch(i){return i.constructor}throw new Error("never reached")})(),le=new G("Insufficient data"),Ye=new ce,de=(function(){function i(e,t,n,r,o,s,f,c){e===void 0&&(e=R.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=Ye),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=K,this.bytes=Ke,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=ae(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 X(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 Ve(this,void 0,void 0,function(){var s,f,c,a,u,d,h,p;return X(this,function(v){switch(v.label){case 0:s=!1,v.label=1;case 1:v.trys.push([1,6,7,12]),t=fe(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 G))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(k(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 Xe(this,arguments,function(){var r,o,s,f,c,a,u,d,h;return X(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=fe(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 G))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(k(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(!Ge(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(k(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 le;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>ie?o=oe(this.bytes,r,e):o=M(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 le;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=ee(this.view,this.pos);return this.pos+=8,e},i.prototype.readI64=function(){var e=b(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 he={};var qe=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)},Je=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 Ze(i){return i[Symbol.asyncIterator]!=null}function Qe(i){if(i==null)throw new Error("Assertion Failure: value must not be null nor undefined")}function je(i){return Je(this,arguments,function(){var t,n,r,o;return qe(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 Qe(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 ue(i){return Ze(i)?i:je(i)}function Y(i,e){e===void 0&&(e=he);var t=ue(i),n=new de(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength);return n.decodeStream(t)}var et="Dendri: ";var q=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=[et,...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 q;var ye=Ue(ve(),1);var B=class extends ye.EventEmitter{emitError(e,t,n=!1){l.error("Error:",t);let r=new Z(`${e}`,t);r.retryable=n,this.emit("error",r)}},Z=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 z=class extends B{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=[];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);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&&(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
|
|
1
|
+
var we=Object.create;var Q=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var Ce=Object.getPrototypeOf,_e=Object.prototype.hasOwnProperty;var Te=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Se=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ee(e))!_e.call(i,r)&&r!==t&&Q(i,r,{get:()=>e[r],enumerable:!(n=ge(e,r))||n.enumerable});return i};var Ue=(i,e,t)=>(t=i!=null?we(Ce(i)):{},Se(e||!i||!i.__esModule?Q(t,"default",{value:i,enumerable:!0}):t,i));var ve=Te((Xt,J)=>{"use strict";var tt=Object.prototype.hasOwnProperty,m="~";function I(){}Object.create&&(I.prototype=Object.create(null),new I().__proto__||(m=!1));function nt(i,e,t){this.fn=i,this.context=e,this.once=t||!1}function pe(i,e,t,n,r){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new nt(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 P(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)tt.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 pe(this,e,t,n,!1)};y.prototype.once=function(e,t,n){return pe(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 P(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!r||s.once)&&(!n||s.context===n)&&P(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:P(this,o)}return this};y.prototype.removeAllListeners=function(e){var t;return e?(t=m?m+e:e,this._events[t]&&P(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 J<"u"&&(J.exports=y)});var w=4294967295;function j(i,e,t){var n=t/4294967296,r=t;i.setUint32(e,n),i.setUint32(e+4,r)}function b(i,e,t){var n=Math.floor(t/4294967296),r=t;i.setUint32(e,n),i.setUint32(e+4,r)}function A(i,e){var t=i.getInt32(e),n=i.getUint32(e+4);return t*4294967296+n}function ee(i,e){var t=i.getUint32(e),n=i.getUint32(e+4);return t*4294967296+n}var N,H,W,L=(typeof process>"u"||((N=process==null?void 0:process.env)===null||N===void 0?void 0:N.TEXT_ENCODING)!=="never")&&typeof TextEncoder<"u"&&typeof TextDecoder<"u";function $(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 te(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=L?new TextEncoder:void 0,ne=L?typeof process<"u"&&((H=process==null?void 0:process.env)===null||H===void 0?void 0:H.TEXT_ENCODING)!=="force"?200:0:w;function De(i,e,t){e.set(S.encode(i),t)}function Ie(i,e,t){S.encodeInto(i,e.subarray(t))}var re=S?.encodeInto?Ie:De,be=4096;function M(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>=be&&(s+=String.fromCharCode.apply(String,o),o.length=0)}return o.length>0&&(s+=String.fromCharCode.apply(String,o)),s}var Ae=L?new TextDecoder:null,ie=L?typeof process<"u"&&((W=process==null?void 0:process.env)===null||W===void 0?void 0:W.TEXT_DECODER)!=="force"?200:0:w;function oe(i,e,t){var n=i.subarray(e,e+t);return Ae.decode(n)}var U=(function(){function i(e,t){this.type=e,this.data=t}return i})();var Le=(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){Le(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 Me=-1,Re=4294967296-1,ke=17179869184-1;function Pe(i){var e=i.sec,t=i.nsec;if(e>=0&&t>=0&&e<=ke)if(t===0&&e<=Re){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),b(r,4,e),n}}function Be(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 ze(i){if(i instanceof Date){var e=Be(i);return Pe(e)}else return null}function Fe(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=A(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 Oe(i){var e=Fe(i);return new Date(e.sec*1e3+e.nsec/1e6)}var se={type:Me,encode:ze,decode:Oe};var R=(function(){function i(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(se)}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 ae(i){if(i instanceof ArrayBuffer)return new DataView(i);var e=E(i);return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Ne=100,He=2048,V=(function(){function i(e,t,n,r,o,s,f,c){e===void 0&&(e=R.defaultCodec),t===void 0&&(t=void 0),n===void 0&&(n=Ne),r===void 0&&(r=He),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>ne){var r=$(e);this.ensureBufferSizeToWrite(t+r),this.writeStringHeader(r),re(e,this.bytes,this.pos),this.pos+=r}else{var r=$(e);this.ensureBufferSizeToWrite(t+r),this.writeStringHeader(r),te(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),j(this.view,this.pos,e),this.pos+=8},i.prototype.writeI64=function(e){this.ensureBufferSizeToWrite(8),b(this.view,this.pos,e),this.pos+=8},i})();function k(i){return"".concat(i<0?"-":"","0x").concat(Math.abs(i).toString(16).padStart(2,"0"))}var We=16,$e=16,ce=(function(){function i(e,t){e===void 0&&(e=We),t===void 0&&(t=$e),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=M(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,o),o},i})();var Ve=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())})},X=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}}},fe=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)},Xe=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])}},Ge=function(i){var e=typeof i;return e==="string"||e==="number"},D=-1,K=new DataView(new ArrayBuffer(0)),Ke=new Uint8Array(K.buffer),G=(function(){try{K.getInt8(0)}catch(i){return i.constructor}throw new Error("never reached")})(),le=new G("Insufficient data"),Ye=new ce,de=(function(){function i(e,t,n,r,o,s,f,c){e===void 0&&(e=R.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=Ye),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=K,this.bytes=Ke,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=ae(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 X(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 Ve(this,void 0,void 0,function(){var s,f,c,a,u,d,h,p;return X(this,function(v){switch(v.label){case 0:s=!1,v.label=1;case 1:v.trys.push([1,6,7,12]),t=fe(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 G))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(k(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 Xe(this,arguments,function(){var r,o,s,f,c,a,u,d,h;return X(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=fe(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 G))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(k(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(!Ge(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(k(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 le;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>ie?o=oe(this.bytes,r,e):o=M(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 le;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=ee(this.view,this.pos);return this.pos+=8,e},i.prototype.readI64=function(){var e=A(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 he={};var qe=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)},Je=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 Ze(i){return i[Symbol.asyncIterator]!=null}function Qe(i){if(i==null)throw new Error("Assertion Failure: value must not be null nor undefined")}function je(i){return Je(this,arguments,function(){var t,n,r,o;return qe(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 Qe(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 ue(i){return Ze(i)?i:je(i)}function Y(i,e){e===void 0&&(e=he);var t=ue(i),n=new de(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength);return n.decodeStream(t)}var et="Dendri: ";var q=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=[et,...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 q;var ye=Ue(ve(),1);var B=class extends ye.EventEmitter{emitError(e,t,n=!1){l.error("Error:",t);let r=new Z(`${e}`,t);r.retryable=n,this.emit("error",r)}},Z=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 z=class extends B{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 F=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
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 me=()=>Math.random().toString(36).slice(2);var T=class i extends z{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+me(),this.label=this.options.label||this.connectionId,this.reliable=!!this.options.reliable,this._negotiator=new
|
|
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 me=()=>Math.random().toString(36).slice(2);var T=class i extends z{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+me(),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._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 O=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 xe=class extends O{serialization="MsgPack";_encoder=new V;constructor(e,t,n){super(e,t,n),(async()=>{for await(let r of Y(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))}};export{xe as MsgPack};
|
|
4
4
|
//# sourceMappingURL=serializer.msgpack.js.map
|