@dxos/shell 0.5.0 → 0.5.1-main.2ed734f
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/dist/bundle/{index-Dvri-LiT.mjs → index-Ba9TfOfV.mjs} +2 -2
- package/dist/bundle/{index-Dvri-LiT.mjs.map → index-Ba9TfOfV.mjs.map} +1 -1
- package/dist/bundle/{index-C6Dqr0aO.mjs → index-DaiI_12x.mjs} +18 -12
- package/dist/bundle/{index-C6Dqr0aO.mjs.map → index-DaiI_12x.mjs.map} +1 -1
- package/dist/bundle/shell.mjs +1 -1
- package/dist/bundle/shell.umd.js +5 -5
- package/dist/bundle/shell.umd.js.map +1 -1
- package/package.json +20 -20
package/dist/bundle/shell.umd.js
CHANGED
|
@@ -848,7 +848,7 @@ button {
|
|
|
848
848
|
*
|
|
849
849
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
850
850
|
* @license MIT
|
|
851
|
-
*/(function($){const I=base64Js,U=ieee754,q=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;$.Buffer=J,$.SlowBuffer=se,$.INSPECT_MAX_BYTES=50;const G=2147483647;$.kMaxLength=G,J.TYPED_ARRAY_SUPPORT=K(),!J.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function K(){try{const le=new Uint8Array(1),re={foo:function(){return 42}};return Object.setPrototypeOf(re,Uint8Array.prototype),Object.setPrototypeOf(le,re),le.foo()===42}catch{return!1}}Object.defineProperty(J.prototype,"parent",{enumerable:!0,get:function(){if(J.isBuffer(this))return this.buffer}}),Object.defineProperty(J.prototype,"offset",{enumerable:!0,get:function(){if(J.isBuffer(this))return this.byteOffset}});function Y(le){if(le>G)throw new RangeError('The value "'+le+'" is invalid for option "size"');const re=new Uint8Array(le);return Object.setPrototypeOf(re,J.prototype),re}function J(le,re,ae){if(typeof le=="number"){if(typeof re=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return ee(le)}return X(le,re,ae)}J.poolSize=8192;function X(le,re,ae){if(typeof le=="string")return te(le,re);if(ArrayBuffer.isView(le))return ie(le);if(le==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof le);if(At(le,ArrayBuffer)||le&&At(le.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(At(le,SharedArrayBuffer)||le&&At(le.buffer,SharedArrayBuffer)))return oe(le,re,ae);if(typeof le=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const he=le.valueOf&&le.valueOf();if(he!=null&&he!==le)return J.from(he,re,ae);const we=ce(le);if(we)return we;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof le[Symbol.toPrimitive]=="function")return J.from(le[Symbol.toPrimitive]("string"),re,ae);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof le)}J.from=function(le,re,ae){return X(le,re,ae)},Object.setPrototypeOf(J.prototype,Uint8Array.prototype),Object.setPrototypeOf(J,Uint8Array);function Z(le){if(typeof le!="number")throw new TypeError('"size" argument must be of type number');if(le<0)throw new RangeError('The value "'+le+'" is invalid for option "size"')}function Q(le,re,ae){return Z(le),le<=0?Y(le):re!==void 0?typeof ae=="string"?Y(le).fill(re,ae):Y(le).fill(re):Y(le)}J.alloc=function(le,re,ae){return Q(le,re,ae)};function ee(le){return Z(le),Y(le<0?0:fe(le)|0)}J.allocUnsafe=function(le){return ee(le)},J.allocUnsafeSlow=function(le){return ee(le)};function te(le,re){if((typeof re!="string"||re==="")&&(re="utf8"),!J.isEncoding(re))throw new TypeError("Unknown encoding: "+re);const ae=de(le,re)|0;let he=Y(ae);const we=he.write(le,re);return we!==ae&&(he=he.slice(0,we)),he}function ne(le){const re=le.length<0?0:fe(le.length)|0,ae=Y(re);for(let he=0;he<re;he+=1)ae[he]=le[he]&255;return ae}function ie(le){if(At(le,Uint8Array)){const re=new Uint8Array(le);return oe(re.buffer,re.byteOffset,re.byteLength)}return ne(le)}function oe(le,re,ae){if(re<0||le.byteLength<re)throw new RangeError('"offset" is outside of buffer bounds');if(le.byteLength<re+(ae||0))throw new RangeError('"length" is outside of buffer bounds');let he;return re===void 0&&ae===void 0?he=new Uint8Array(le):ae===void 0?he=new Uint8Array(le,re):he=new Uint8Array(le,re,ae),Object.setPrototypeOf(he,J.prototype),he}function ce(le){if(J.isBuffer(le)){const re=fe(le.length)|0,ae=Y(re);return ae.length===0||le.copy(ae,0,0,re),ae}if(le.length!==void 0)return typeof le.length!="number"||zt(le.length)?Y(0):ne(le);if(le.type==="Buffer"&&Array.isArray(le.data))return ne(le.data)}function fe(le){if(le>=G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");return le|0}function se(le){return+le!=le&&(le=0),J.alloc(+le)}J.isBuffer=function(re){return re!=null&&re._isBuffer===!0&&re!==J.prototype},J.compare=function(re,ae){if(At(re,Uint8Array)&&(re=J.from(re,re.offset,re.byteLength)),At(ae,Uint8Array)&&(ae=J.from(ae,ae.offset,ae.byteLength)),!J.isBuffer(re)||!J.isBuffer(ae))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(re===ae)return 0;let he=re.length,we=ae.length;for(let Ee=0,Le=Math.min(he,we);Ee<Le;++Ee)if(re[Ee]!==ae[Ee]){he=re[Ee],we=ae[Ee];break}return he<we?-1:we<he?1:0},J.isEncoding=function(re){switch(String(re).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},J.concat=function(re,ae){if(!Array.isArray(re))throw new TypeError('"list" argument must be an Array of Buffers');if(re.length===0)return J.alloc(0);let he;if(ae===void 0)for(ae=0,he=0;he<re.length;++he)ae+=re[he].length;const we=J.allocUnsafe(ae);let Ee=0;for(he=0;he<re.length;++he){let Le=re[he];if(At(Le,Uint8Array))Ee+Le.length>we.length?(J.isBuffer(Le)||(Le=J.from(Le)),Le.copy(we,Ee)):Uint8Array.prototype.set.call(we,Le,Ee);else if(J.isBuffer(Le))Le.copy(we,Ee);else throw new TypeError('"list" argument must be an Array of Buffers');Ee+=Le.length}return we};function de(le,re){if(J.isBuffer(le))return le.length;if(ArrayBuffer.isView(le)||At(le,ArrayBuffer))return le.byteLength;if(typeof le!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof le);const ae=le.length,he=arguments.length>2&&arguments[2]===!0;if(!he&&ae===0)return 0;let we=!1;for(;;)switch(re){case"ascii":case"latin1":case"binary":return ae;case"utf8":case"utf-8":return $t(le).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ae*2;case"hex":return ae>>>1;case"base64":return jt(le).length;default:if(we)return he?-1:$t(le).length;re=(""+re).toLowerCase(),we=!0}}J.byteLength=de;function ue(le,re,ae){let he=!1;if((re===void 0||re<0)&&(re=0),re>this.length||((ae===void 0||ae>this.length)&&(ae=this.length),ae<=0)||(ae>>>=0,re>>>=0,ae<=re))return"";for(le||(le="utf8");;)switch(le){case"hex":return it(this,re,ae);case"utf8":case"utf-8":return Be(this,re,ae);case"ascii":return ot(this,re,ae);case"latin1":case"binary":return ft(this,re,ae);case"base64":return De(this,re,ae);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ut(this,re,ae);default:if(he)throw new TypeError("Unknown encoding: "+le);le=(le+"").toLowerCase(),he=!0}}J.prototype._isBuffer=!0;function pe(le,re,ae){const he=le[re];le[re]=le[ae],le[ae]=he}J.prototype.swap16=function(){const re=this.length;if(re%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let ae=0;ae<re;ae+=2)pe(this,ae,ae+1);return this},J.prototype.swap32=function(){const re=this.length;if(re%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let ae=0;ae<re;ae+=4)pe(this,ae,ae+3),pe(this,ae+1,ae+2);return this},J.prototype.swap64=function(){const re=this.length;if(re%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let ae=0;ae<re;ae+=8)pe(this,ae,ae+7),pe(this,ae+1,ae+6),pe(this,ae+2,ae+5),pe(this,ae+3,ae+4);return this},J.prototype.toString=function(){const re=this.length;return re===0?"":arguments.length===0?Be(this,0,re):ue.apply(this,arguments)},J.prototype.toLocaleString=J.prototype.toString,J.prototype.equals=function(re){if(!J.isBuffer(re))throw new TypeError("Argument must be a Buffer");return this===re?!0:J.compare(this,re)===0},J.prototype.inspect=function(){let re="";const ae=$.INSPECT_MAX_BYTES;return re=this.toString("hex",0,ae).replace(/(.{2})/g,"$1 ").trim(),this.length>ae&&(re+=" ... "),"<Buffer "+re+">"},q&&(J.prototype[q]=J.prototype.inspect),J.prototype.compare=function(re,ae,he,we,Ee){if(At(re,Uint8Array)&&(re=J.from(re,re.offset,re.byteLength)),!J.isBuffer(re))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof re);if(ae===void 0&&(ae=0),he===void 0&&(he=re?re.length:0),we===void 0&&(we=0),Ee===void 0&&(Ee=this.length),ae<0||he>re.length||we<0||Ee>this.length)throw new RangeError("out of range index");if(we>=Ee&&ae>=he)return 0;if(we>=Ee)return-1;if(ae>=he)return 1;if(ae>>>=0,he>>>=0,we>>>=0,Ee>>>=0,this===re)return 0;let Le=Ee-we,bt=he-ae;const Lt=Math.min(Le,bt),Ct=this.slice(we,Ee),It=re.slice(ae,he);for(let Tt=0;Tt<Lt;++Tt)if(Ct[Tt]!==It[Tt]){Le=Ct[Tt],bt=It[Tt];break}return Le<bt?-1:bt<Le?1:0};function ve(le,re,ae,he,we){if(le.length===0)return-1;if(typeof ae=="string"?(he=ae,ae=0):ae>2147483647?ae=2147483647:ae<-2147483648&&(ae=-2147483648),ae=+ae,zt(ae)&&(ae=we?0:le.length-1),ae<0&&(ae=le.length+ae),ae>=le.length){if(we)return-1;ae=le.length-1}else if(ae<0)if(we)ae=0;else return-1;if(typeof re=="string"&&(re=J.from(re,he)),J.isBuffer(re))return re.length===0?-1:me(le,re,ae,he,we);if(typeof re=="number")return re=re&255,typeof Uint8Array.prototype.indexOf=="function"?we?Uint8Array.prototype.indexOf.call(le,re,ae):Uint8Array.prototype.lastIndexOf.call(le,re,ae):me(le,[re],ae,he,we);throw new TypeError("val must be string, number or Buffer")}function me(le,re,ae,he,we){let Ee=1,Le=le.length,bt=re.length;if(he!==void 0&&(he=String(he).toLowerCase(),he==="ucs2"||he==="ucs-2"||he==="utf16le"||he==="utf-16le")){if(le.length<2||re.length<2)return-1;Ee=2,Le/=2,bt/=2,ae/=2}function Lt(It,Tt){return Ee===1?It[Tt]:It.readUInt16BE(Tt*Ee)}let Ct;if(we){let It=-1;for(Ct=ae;Ct<Le;Ct++)if(Lt(le,Ct)===Lt(re,It===-1?0:Ct-It)){if(It===-1&&(It=Ct),Ct-It+1===bt)return It*Ee}else It!==-1&&(Ct-=Ct-It),It=-1}else for(ae+bt>Le&&(ae=Le-bt),Ct=ae;Ct>=0;Ct--){let It=!0;for(let Tt=0;Tt<bt;Tt++)if(Lt(le,Ct+Tt)!==Lt(re,Tt)){It=!1;break}if(It)return Ct}return-1}J.prototype.includes=function(re,ae,he){return this.indexOf(re,ae,he)!==-1},J.prototype.indexOf=function(re,ae,he){return ve(this,re,ae,he,!0)},J.prototype.lastIndexOf=function(re,ae,he){return ve(this,re,ae,he,!1)};function be(le,re,ae,he){ae=Number(ae)||0;const we=le.length-ae;he?(he=Number(he),he>we&&(he=we)):he=we;const Ee=re.length;he>Ee/2&&(he=Ee/2);let Le;for(Le=0;Le<he;++Le){const bt=parseInt(re.substr(Le*2,2),16);if(zt(bt))return Le;le[ae+Le]=bt}return Le}function ye(le,re,ae,he){return Gt($t(re,le.length-ae),le,ae,he)}function Se(le,re,ae,he){return Gt(Et(re),le,ae,he)}function xe(le,re,ae,he){return Gt(jt(re),le,ae,he)}function ke(le,re,ae,he){return Gt(rt(re,le.length-ae),le,ae,he)}J.prototype.write=function(re,ae,he,we){if(ae===void 0)we="utf8",he=this.length,ae=0;else if(he===void 0&&typeof ae=="string")we=ae,he=this.length,ae=0;else if(isFinite(ae))ae=ae>>>0,isFinite(he)?(he=he>>>0,we===void 0&&(we="utf8")):(we=he,he=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const Ee=this.length-ae;if((he===void 0||he>Ee)&&(he=Ee),re.length>0&&(he<0||ae<0)||ae>this.length)throw new RangeError("Attempt to write outside buffer bounds");we||(we="utf8");let Le=!1;for(;;)switch(we){case"hex":return be(this,re,ae,he);case"utf8":case"utf-8":return ye(this,re,ae,he);case"ascii":case"latin1":case"binary":return Se(this,re,ae,he);case"base64":return xe(this,re,ae,he);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ke(this,re,ae,he);default:if(Le)throw new TypeError("Unknown encoding: "+we);we=(""+we).toLowerCase(),Le=!0}},J.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function De(le,re,ae){return re===0&&ae===le.length?I.fromByteArray(le):I.fromByteArray(le.slice(re,ae))}function Be(le,re,ae){ae=Math.min(le.length,ae);const he=[];let we=re;for(;we<ae;){const Ee=le[we];let Le=null,bt=Ee>239?4:Ee>223?3:Ee>191?2:1;if(we+bt<=ae){let Lt,Ct,It,Tt;switch(bt){case 1:Ee<128&&(Le=Ee);break;case 2:Lt=le[we+1],(Lt&192)===128&&(Tt=(Ee&31)<<6|Lt&63,Tt>127&&(Le=Tt));break;case 3:Lt=le[we+1],Ct=le[we+2],(Lt&192)===128&&(Ct&192)===128&&(Tt=(Ee&15)<<12|(Lt&63)<<6|Ct&63,Tt>2047&&(Tt<55296||Tt>57343)&&(Le=Tt));break;case 4:Lt=le[we+1],Ct=le[we+2],It=le[we+3],(Lt&192)===128&&(Ct&192)===128&&(It&192)===128&&(Tt=(Ee&15)<<18|(Lt&63)<<12|(Ct&63)<<6|It&63,Tt>65535&&Tt<1114112&&(Le=Tt))}}Le===null?(Le=65533,bt=1):Le>65535&&(Le-=65536,he.push(Le>>>10&1023|55296),Le=56320|Le&1023),he.push(Le),we+=bt}return nt(he)}const Ve=4096;function nt(le){const re=le.length;if(re<=Ve)return String.fromCharCode.apply(String,le);let ae="",he=0;for(;he<re;)ae+=String.fromCharCode.apply(String,le.slice(he,he+=Ve));return ae}function ot(le,re,ae){let he="";ae=Math.min(le.length,ae);for(let we=re;we<ae;++we)he+=String.fromCharCode(le[we]&127);return he}function ft(le,re,ae){let he="";ae=Math.min(le.length,ae);for(let we=re;we<ae;++we)he+=String.fromCharCode(le[we]);return he}function it(le,re,ae){const he=le.length;(!re||re<0)&&(re=0),(!ae||ae<0||ae>he)&&(ae=he);let we="";for(let Ee=re;Ee<ae;++Ee)we+=nn[le[Ee]];return we}function ut(le,re,ae){const he=le.slice(re,ae);let we="";for(let Ee=0;Ee<he.length-1;Ee+=2)we+=String.fromCharCode(he[Ee]+he[Ee+1]*256);return we}J.prototype.slice=function(re,ae){const he=this.length;re=~~re,ae=ae===void 0?he:~~ae,re<0?(re+=he,re<0&&(re=0)):re>he&&(re=he),ae<0?(ae+=he,ae<0&&(ae=0)):ae>he&&(ae=he),ae<re&&(ae=re);const we=this.subarray(re,ae);return Object.setPrototypeOf(we,J.prototype),we};function et(le,re,ae){if(le%1!==0||le<0)throw new RangeError("offset is not uint");if(le+re>ae)throw new RangeError("Trying to access beyond buffer length")}J.prototype.readUintLE=J.prototype.readUIntLE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=this[re],Ee=1,Le=0;for(;++Le<ae&&(Ee*=256);)we+=this[re+Le]*Ee;return we},J.prototype.readUintBE=J.prototype.readUIntBE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=this[re+--ae],Ee=1;for(;ae>0&&(Ee*=256);)we+=this[re+--ae]*Ee;return we},J.prototype.readUint8=J.prototype.readUInt8=function(re,ae){return re=re>>>0,ae||et(re,1,this.length),this[re]},J.prototype.readUint16LE=J.prototype.readUInt16LE=function(re,ae){return re=re>>>0,ae||et(re,2,this.length),this[re]|this[re+1]<<8},J.prototype.readUint16BE=J.prototype.readUInt16BE=function(re,ae){return re=re>>>0,ae||et(re,2,this.length),this[re]<<8|this[re+1]},J.prototype.readUint32LE=J.prototype.readUInt32LE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),(this[re]|this[re+1]<<8|this[re+2]<<16)+this[re+3]*16777216},J.prototype.readUint32BE=J.prototype.readUInt32BE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),this[re]*16777216+(this[re+1]<<16|this[re+2]<<8|this[re+3])},J.prototype.readBigUInt64LE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=ae+this[++re]*2**8+this[++re]*2**16+this[++re]*2**24,Ee=this[++re]+this[++re]*2**8+this[++re]*2**16+he*2**24;return BigInt(we)+(BigInt(Ee)<<BigInt(32))}),J.prototype.readBigUInt64BE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=ae*2**24+this[++re]*2**16+this[++re]*2**8+this[++re],Ee=this[++re]*2**24+this[++re]*2**16+this[++re]*2**8+he;return(BigInt(we)<<BigInt(32))+BigInt(Ee)}),J.prototype.readIntLE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=this[re],Ee=1,Le=0;for(;++Le<ae&&(Ee*=256);)we+=this[re+Le]*Ee;return Ee*=128,we>=Ee&&(we-=Math.pow(2,8*ae)),we},J.prototype.readIntBE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=ae,Ee=1,Le=this[re+--we];for(;we>0&&(Ee*=256);)Le+=this[re+--we]*Ee;return Ee*=128,Le>=Ee&&(Le-=Math.pow(2,8*ae)),Le},J.prototype.readInt8=function(re,ae){return re=re>>>0,ae||et(re,1,this.length),this[re]&128?(255-this[re]+1)*-1:this[re]},J.prototype.readInt16LE=function(re,ae){re=re>>>0,ae||et(re,2,this.length);const he=this[re]|this[re+1]<<8;return he&32768?he|4294901760:he},J.prototype.readInt16BE=function(re,ae){re=re>>>0,ae||et(re,2,this.length);const he=this[re+1]|this[re]<<8;return he&32768?he|4294901760:he},J.prototype.readInt32LE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),this[re]|this[re+1]<<8|this[re+2]<<16|this[re+3]<<24},J.prototype.readInt32BE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),this[re]<<24|this[re+1]<<16|this[re+2]<<8|this[re+3]},J.prototype.readBigInt64LE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=this[re+4]+this[re+5]*2**8+this[re+6]*2**16+(he<<24);return(BigInt(we)<<BigInt(32))+BigInt(ae+this[++re]*2**8+this[++re]*2**16+this[++re]*2**24)}),J.prototype.readBigInt64BE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=(ae<<24)+this[++re]*2**16+this[++re]*2**8+this[++re];return(BigInt(we)<<BigInt(32))+BigInt(this[++re]*2**24+this[++re]*2**16+this[++re]*2**8+he)}),J.prototype.readFloatLE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),U.read(this,re,!0,23,4)},J.prototype.readFloatBE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),U.read(this,re,!1,23,4)},J.prototype.readDoubleLE=function(re,ae){return re=re>>>0,ae||et(re,8,this.length),U.read(this,re,!0,52,8)},J.prototype.readDoubleBE=function(re,ae){return re=re>>>0,ae||et(re,8,this.length),U.read(this,re,!1,52,8)};function Ue(le,re,ae,he,we,Ee){if(!J.isBuffer(le))throw new TypeError('"buffer" argument must be a Buffer instance');if(re>we||re<Ee)throw new RangeError('"value" argument is out of bounds');if(ae+he>le.length)throw new RangeError("Index out of range")}J.prototype.writeUintLE=J.prototype.writeUIntLE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,he=he>>>0,!we){const bt=Math.pow(2,8*he)-1;Ue(this,re,ae,he,bt,0)}let Ee=1,Le=0;for(this[ae]=re&255;++Le<he&&(Ee*=256);)this[ae+Le]=re/Ee&255;return ae+he},J.prototype.writeUintBE=J.prototype.writeUIntBE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,he=he>>>0,!we){const bt=Math.pow(2,8*he)-1;Ue(this,re,ae,he,bt,0)}let Ee=he-1,Le=1;for(this[ae+Ee]=re&255;--Ee>=0&&(Le*=256);)this[ae+Ee]=re/Le&255;return ae+he},J.prototype.writeUint8=J.prototype.writeUInt8=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,1,255,0),this[ae]=re&255,ae+1},J.prototype.writeUint16LE=J.prototype.writeUInt16LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,65535,0),this[ae]=re&255,this[ae+1]=re>>>8,ae+2},J.prototype.writeUint16BE=J.prototype.writeUInt16BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,65535,0),this[ae]=re>>>8,this[ae+1]=re&255,ae+2},J.prototype.writeUint32LE=J.prototype.writeUInt32LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,4294967295,0),this[ae+3]=re>>>24,this[ae+2]=re>>>16,this[ae+1]=re>>>8,this[ae]=re&255,ae+4},J.prototype.writeUint32BE=J.prototype.writeUInt32BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,4294967295,0),this[ae]=re>>>24,this[ae+1]=re>>>16,this[ae+2]=re>>>8,this[ae+3]=re&255,ae+4};function We(le,re,ae,he,we){_e(re,he,we,le,ae,7);let Ee=Number(re&BigInt(4294967295));le[ae++]=Ee,Ee=Ee>>8,le[ae++]=Ee,Ee=Ee>>8,le[ae++]=Ee,Ee=Ee>>8,le[ae++]=Ee;let Le=Number(re>>BigInt(32)&BigInt(4294967295));return le[ae++]=Le,Le=Le>>8,le[ae++]=Le,Le=Le>>8,le[ae++]=Le,Le=Le>>8,le[ae++]=Le,ae}function tt(le,re,ae,he,we){_e(re,he,we,le,ae,7);let Ee=Number(re&BigInt(4294967295));le[ae+7]=Ee,Ee=Ee>>8,le[ae+6]=Ee,Ee=Ee>>8,le[ae+5]=Ee,Ee=Ee>>8,le[ae+4]=Ee;let Le=Number(re>>BigInt(32)&BigInt(4294967295));return le[ae+3]=Le,Le=Le>>8,le[ae+2]=Le,Le=Le>>8,le[ae+1]=Le,Le=Le>>8,le[ae]=Le,ae+8}J.prototype.writeBigUInt64LE=St(function(re,ae=0){return We(this,re,ae,BigInt(0),BigInt("0xffffffffffffffff"))}),J.prototype.writeBigUInt64BE=St(function(re,ae=0){return tt(this,re,ae,BigInt(0),BigInt("0xffffffffffffffff"))}),J.prototype.writeIntLE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,!we){const Lt=Math.pow(2,8*he-1);Ue(this,re,ae,he,Lt-1,-Lt)}let Ee=0,Le=1,bt=0;for(this[ae]=re&255;++Ee<he&&(Le*=256);)re<0&&bt===0&&this[ae+Ee-1]!==0&&(bt=1),this[ae+Ee]=(re/Le>>0)-bt&255;return ae+he},J.prototype.writeIntBE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,!we){const Lt=Math.pow(2,8*he-1);Ue(this,re,ae,he,Lt-1,-Lt)}let Ee=he-1,Le=1,bt=0;for(this[ae+Ee]=re&255;--Ee>=0&&(Le*=256);)re<0&&bt===0&&this[ae+Ee+1]!==0&&(bt=1),this[ae+Ee]=(re/Le>>0)-bt&255;return ae+he},J.prototype.writeInt8=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,1,127,-128),re<0&&(re=255+re+1),this[ae]=re&255,ae+1},J.prototype.writeInt16LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,32767,-32768),this[ae]=re&255,this[ae+1]=re>>>8,ae+2},J.prototype.writeInt16BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,32767,-32768),this[ae]=re>>>8,this[ae+1]=re&255,ae+2},J.prototype.writeInt32LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,2147483647,-2147483648),this[ae]=re&255,this[ae+1]=re>>>8,this[ae+2]=re>>>16,this[ae+3]=re>>>24,ae+4},J.prototype.writeInt32BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,2147483647,-2147483648),re<0&&(re=4294967295+re+1),this[ae]=re>>>24,this[ae+1]=re>>>16,this[ae+2]=re>>>8,this[ae+3]=re&255,ae+4},J.prototype.writeBigInt64LE=St(function(re,ae=0){return We(this,re,ae,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),J.prototype.writeBigInt64BE=St(function(re,ae=0){return tt(this,re,ae,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function vt(le,re,ae,he,we,Ee){if(ae+he>le.length)throw new RangeError("Index out of range");if(ae<0)throw new RangeError("Index out of range")}function je(le,re,ae,he,we){return re=+re,ae=ae>>>0,we||vt(le,re,ae,4),U.write(le,re,ae,he,23,4),ae+4}J.prototype.writeFloatLE=function(re,ae,he){return je(this,re,ae,!0,he)},J.prototype.writeFloatBE=function(re,ae,he){return je(this,re,ae,!1,he)};function ze(le,re,ae,he,we){return re=+re,ae=ae>>>0,we||vt(le,re,ae,8),U.write(le,re,ae,he,52,8),ae+8}J.prototype.writeDoubleLE=function(re,ae,he){return ze(this,re,ae,!0,he)},J.prototype.writeDoubleBE=function(re,ae,he){return ze(this,re,ae,!1,he)},J.prototype.copy=function(re,ae,he,we){if(!J.isBuffer(re))throw new TypeError("argument should be a Buffer");if(he||(he=0),!we&&we!==0&&(we=this.length),ae>=re.length&&(ae=re.length),ae||(ae=0),we>0&&we<he&&(we=he),we===he||re.length===0||this.length===0)return 0;if(ae<0)throw new RangeError("targetStart out of bounds");if(he<0||he>=this.length)throw new RangeError("Index out of range");if(we<0)throw new RangeError("sourceEnd out of bounds");we>this.length&&(we=this.length),re.length-ae<we-he&&(we=re.length-ae+he);const Ee=we-he;return this===re&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(ae,he,we):Uint8Array.prototype.set.call(re,this.subarray(he,we),ae),Ee},J.prototype.fill=function(re,ae,he,we){if(typeof re=="string"){if(typeof ae=="string"?(we=ae,ae=0,he=this.length):typeof he=="string"&&(we=he,he=this.length),we!==void 0&&typeof we!="string")throw new TypeError("encoding must be a string");if(typeof we=="string"&&!J.isEncoding(we))throw new TypeError("Unknown encoding: "+we);if(re.length===1){const Le=re.charCodeAt(0);(we==="utf8"&&Le<128||we==="latin1")&&(re=Le)}}else typeof re=="number"?re=re&255:typeof re=="boolean"&&(re=Number(re));if(ae<0||this.length<ae||this.length<he)throw new RangeError("Out of range index");if(he<=ae)return this;ae=ae>>>0,he=he===void 0?this.length:he>>>0,re||(re=0);let Ee;if(typeof re=="number")for(Ee=ae;Ee<he;++Ee)this[Ee]=re;else{const Le=J.isBuffer(re)?re:J.from(re,we),bt=Le.length;if(bt===0)throw new TypeError('The value "'+re+'" is invalid for argument "value"');for(Ee=0;Ee<he-ae;++Ee)this[Ee+ae]=Le[Ee%bt]}return this};const Ae={};function Re(le,re,ae){Ae[le]=class extends ae{constructor(){super(),Object.defineProperty(this,"message",{value:re.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${le}]`,this.stack,delete this.name}get code(){return le}set code(we){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:we,writable:!0})}toString(){return`${this.name} [${le}]: ${this.message}`}}}Re("ERR_BUFFER_OUT_OF_BOUNDS",function(le){return le?`${le} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Re("ERR_INVALID_ARG_TYPE",function(le,re){return`The "${le}" argument must be of type number. Received type ${typeof re}`},TypeError),Re("ERR_OUT_OF_RANGE",function(le,re,ae){let he=`The value of "${le}" is out of range.`,we=ae;return Number.isInteger(ae)&&Math.abs(ae)>2**32?we=Ce(String(ae)):typeof ae=="bigint"&&(we=String(ae),(ae>BigInt(2)**BigInt(32)||ae<-(BigInt(2)**BigInt(32)))&&(we=Ce(we)),we+="n"),he+=` It must be ${re}. Received ${we}`,he},RangeError);function Ce(le){let re="",ae=le.length;const he=le[0]==="-"?1:0;for(;ae>=he+4;ae-=3)re=`_${le.slice(ae-3,ae)}${re}`;return`${le.slice(0,ae)}${re}`}function ge(le,re,ae){Me(re,"offset"),(le[re]===void 0||le[re+ae]===void 0)&&Ke(re,le.length-(ae+1))}function _e(le,re,ae,he,we,Ee){if(le>ae||le<re){const Le=typeof re=="bigint"?"n":"";let bt;throw Ee>3?re===0||re===BigInt(0)?bt=`>= 0${Le} and < 2${Le} ** ${(Ee+1)*8}${Le}`:bt=`>= -(2${Le} ** ${(Ee+1)*8-1}${Le}) and < 2 ** ${(Ee+1)*8-1}${Le}`:bt=`>= ${re}${Le} and <= ${ae}${Le}`,new Ae.ERR_OUT_OF_RANGE("value",bt,le)}ge(he,we,Ee)}function Me(le,re){if(typeof le!="number")throw new Ae.ERR_INVALID_ARG_TYPE(re,"number",le)}function Ke(le,re,ae){throw Math.floor(le)!==le?(Me(le,ae),new Ae.ERR_OUT_OF_RANGE(ae||"offset","an integer",le)):re<0?new Ae.ERR_BUFFER_OUT_OF_BOUNDS:new Ae.ERR_OUT_OF_RANGE(ae||"offset",`>= ${ae?1:0} and <= ${re}`,le)}const st=/[^+/0-9A-Za-z-_]/g;function dt(le){if(le=le.split("=")[0],le=le.trim().replace(st,""),le.length<2)return"";for(;le.length%4!==0;)le=le+"=";return le}function $t(le,re){re=re||1/0;let ae;const he=le.length;let we=null;const Ee=[];for(let Le=0;Le<he;++Le){if(ae=le.charCodeAt(Le),ae>55295&&ae<57344){if(!we){if(ae>56319){(re-=3)>-1&&Ee.push(239,191,189);continue}else if(Le+1===he){(re-=3)>-1&&Ee.push(239,191,189);continue}we=ae;continue}if(ae<56320){(re-=3)>-1&&Ee.push(239,191,189),we=ae;continue}ae=(we-55296<<10|ae-56320)+65536}else we&&(re-=3)>-1&&Ee.push(239,191,189);if(we=null,ae<128){if((re-=1)<0)break;Ee.push(ae)}else if(ae<2048){if((re-=2)<0)break;Ee.push(ae>>6|192,ae&63|128)}else if(ae<65536){if((re-=3)<0)break;Ee.push(ae>>12|224,ae>>6&63|128,ae&63|128)}else if(ae<1114112){if((re-=4)<0)break;Ee.push(ae>>18|240,ae>>12&63|128,ae>>6&63|128,ae&63|128)}else throw new Error("Invalid code point")}return Ee}function Et(le){const re=[];for(let ae=0;ae<le.length;++ae)re.push(le.charCodeAt(ae)&255);return re}function rt(le,re){let ae,he,we;const Ee=[];for(let Le=0;Le<le.length&&!((re-=2)<0);++Le)ae=le.charCodeAt(Le),he=ae>>8,we=ae%256,Ee.push(we),Ee.push(he);return Ee}function jt(le){return I.toByteArray(dt(le))}function Gt(le,re,ae,he){let we;for(we=0;we<he&&!(we+ae>=re.length||we>=le.length);++we)re[we+ae]=le[we];return we}function At(le,re){return le instanceof re||le!=null&&le.constructor!=null&&le.constructor.name!=null&&le.constructor.name===re.name}function zt(le){return le!==le}const nn=function(){const le="0123456789abcdef",re=new Array(256);for(let ae=0;ae<16;++ae){const he=ae*16;for(let we=0;we<16;++we)re[he+we]=le[ae]+le[we]}return re}();function St(le){return typeof BigInt>"u"?Ut:le}function Ut(){throw new Error("BigInt not supported")}})(buffer);const __viteBrowserExternal={},__viteBrowserExternal$1=Object.freeze(Object.defineProperty({__proto__:null,default:__viteBrowserExternal},Symbol.toStringTag,{value:"Module"})),require$$3=getAugmentedNamespace(__viteBrowserExternal$1);var buffer_list,hasRequiredBuffer_list;function requireBuffer_list(){if(hasRequiredBuffer_list)return buffer_list;hasRequiredBuffer_list=1;function $(te,ne){var ie=Object.keys(te);if(Object.getOwnPropertySymbols){var oe=Object.getOwnPropertySymbols(te);ne&&(oe=oe.filter(function(ce){return Object.getOwnPropertyDescriptor(te,ce).enumerable})),ie.push.apply(ie,oe)}return ie}function I(te){for(var ne=1;ne<arguments.length;ne++){var ie=arguments[ne]!=null?arguments[ne]:{};ne%2?$(Object(ie),!0).forEach(function(oe){U(te,oe,ie[oe])}):Object.getOwnPropertyDescriptors?Object.defineProperties(te,Object.getOwnPropertyDescriptors(ie)):$(Object(ie)).forEach(function(oe){Object.defineProperty(te,oe,Object.getOwnPropertyDescriptor(ie,oe))})}return te}function U(te,ne,ie){return ne in te?Object.defineProperty(te,ne,{value:ie,enumerable:!0,configurable:!0,writable:!0}):te[ne]=ie,te}function q(te,ne){if(!(te instanceof ne))throw new TypeError("Cannot call a class as a function")}function G(te,ne){for(var ie=0;ie<ne.length;ie++){var oe=ne[ie];oe.enumerable=oe.enumerable||!1,oe.configurable=!0,"value"in oe&&(oe.writable=!0),Object.defineProperty(te,oe.key,oe)}}function K(te,ne,ie){return ne&&G(te.prototype,ne),ie&&G(te,ie),te}var Y=buffer,J=Y.Buffer,X=require$$3,Z=X.inspect,Q=Z&&Z.custom||"inspect";function ee(te,ne,ie){J.prototype.copy.call(te,ne,ie)}return buffer_list=function(){function te(){q(this,te),this.head=null,this.tail=null,this.length=0}return K(te,[{key:"push",value:function(ie){var oe={data:ie,next:null};this.length>0?this.tail.next=oe:this.head=oe,this.tail=oe,++this.length}},{key:"unshift",value:function(ie){var oe={data:ie,next:this.head};this.length===0&&(this.tail=oe),this.head=oe,++this.length}},{key:"shift",value:function(){if(this.length!==0){var ie=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,ie}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(ie){if(this.length===0)return"";for(var oe=this.head,ce=""+oe.data;oe=oe.next;)ce+=ie+oe.data;return ce}},{key:"concat",value:function(ie){if(this.length===0)return J.alloc(0);for(var oe=J.allocUnsafe(ie>>>0),ce=this.head,fe=0;ce;)ee(ce.data,oe,fe),fe+=ce.data.length,ce=ce.next;return oe}},{key:"consume",value:function(ie,oe){var ce;return ie<this.head.data.length?(ce=this.head.data.slice(0,ie),this.head.data=this.head.data.slice(ie)):ie===this.head.data.length?ce=this.shift():ce=oe?this._getString(ie):this._getBuffer(ie),ce}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(ie){var oe=this.head,ce=1,fe=oe.data;for(ie-=fe.length;oe=oe.next;){var se=oe.data,de=ie>se.length?se.length:ie;if(de===se.length?fe+=se:fe+=se.slice(0,ie),ie-=de,ie===0){de===se.length?(++ce,oe.next?this.head=oe.next:this.head=this.tail=null):(this.head=oe,oe.data=se.slice(de));break}++ce}return this.length-=ce,fe}},{key:"_getBuffer",value:function(ie){var oe=J.allocUnsafe(ie),ce=this.head,fe=1;for(ce.data.copy(oe),ie-=ce.data.length;ce=ce.next;){var se=ce.data,de=ie>se.length?se.length:ie;if(se.copy(oe,oe.length-ie,0,de),ie-=de,ie===0){de===se.length?(++fe,ce.next?this.head=ce.next:this.head=this.tail=null):(this.head=ce,ce.data=se.slice(de));break}++fe}return this.length-=fe,oe}},{key:Q,value:function(ie,oe){return Z(this,I({},oe,{depth:0,customInspect:!1}))}}]),te}(),buffer_list}function destroy($,I){var U=this,q=this._readableState&&this._readableState.destroyed,G=this._writableState&&this._writableState.destroyed;return q||G?(I?I($):$&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,$)):process.nextTick(emitErrorNT,this,$)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy($||null,function(K){!I&&K?U._writableState?U._writableState.errorEmitted?process.nextTick(emitCloseNT,U):(U._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,U,K)):process.nextTick(emitErrorAndCloseNT,U,K):I?(process.nextTick(emitCloseNT,U),I(K)):process.nextTick(emitCloseNT,U)}),this)}function emitErrorAndCloseNT($,I){emitErrorNT($,I),emitCloseNT($)}function emitCloseNT($){$._writableState&&!$._writableState.emitClose||$._readableState&&!$._readableState.emitClose||$.emit("close")}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT($,I){$.emit("error",I)}function errorOrDestroy($,I){var U=$._readableState,q=$._writableState;U&&U.autoDestroy||q&&q.autoDestroy?$.destroy(I):$.emit("error",I)}var destroy_1={destroy,undestroy,errorOrDestroy},errorsBrowser={};function _inheritsLoose($,I){$.prototype=Object.create(I.prototype),$.prototype.constructor=$,$.__proto__=I}var codes={};function createErrorType($,I,U){U||(U=Error);function q(K,Y,J){return typeof I=="string"?I:I(K,Y,J)}var G=function(K){_inheritsLoose(Y,K);function Y(J,X,Z){return K.call(this,q(J,X,Z))||this}return Y}(U);G.prototype.name=U.name,G.prototype.code=$,codes[$]=G}function oneOf($,I){if(Array.isArray($)){var U=$.length;return $=$.map(function(q){return String(q)}),U>2?"one of ".concat(I," ").concat($.slice(0,U-1).join(", "),", or ")+$[U-1]:U===2?"one of ".concat(I," ").concat($[0]," or ").concat($[1]):"of ".concat(I," ").concat($[0])}else return"of ".concat(I," ").concat(String($))}function startsWith($,I,U){return $.substr(!U||U<0?0:+U,I.length)===I}function endsWith($,I,U){return(U===void 0||U>$.length)&&(U=$.length),$.substring(U-I.length,U)===I}function includes($,I,U){return typeof U!="number"&&(U=0),U+I.length>$.length?!1:$.indexOf(I,U)!==-1}createErrorType("ERR_INVALID_OPT_VALUE",function($,I){return'The value "'+I+'" is invalid for option "'+$+'"'},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function($,I,U){var q;typeof I=="string"&&startsWith(I,"not ")?(q="must not be",I=I.replace(/^not /,"")):q="must be";var G;if(endsWith($," argument"))G="The ".concat($," ").concat(q," ").concat(oneOf(I,"type"));else{var K=includes($,".")?"property":"argument";G='The "'.concat($,'" ').concat(K," ").concat(q," ").concat(oneOf(I,"type"))}return G+=". Received type ".concat(typeof U),G},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function($){return"The "+$+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function($){return"Cannot call "+$+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function($){return"Unknown encoding: "+$},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),errorsBrowser.codes=codes;var ERR_INVALID_OPT_VALUE=errorsBrowser.codes.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom($,I,U){return $.highWaterMark!=null?$.highWaterMark:I?$[U]:null}function getHighWaterMark($,I,U,q){var G=highWaterMarkFrom(I,q,U);if(G!=null){if(!(isFinite(G)&&Math.floor(G)===G)||G<0){var K=q?U:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(K,G)}return Math.floor(G)}return $.objectMode?16:16*1024}var state={getHighWaterMark},inherits_browser={exports:{}};typeof Object.create=="function"?inherits_browser.exports=function(I,U){U&&(I.super_=U,I.prototype=Object.create(U.prototype,{constructor:{value:I,enumerable:!1,writable:!0,configurable:!0}}))}:inherits_browser.exports=function(I,U){if(U){I.super_=U;var q=function(){};q.prototype=U.prototype,I.prototype=new q,I.prototype.constructor=I}};var inherits_browserExports=inherits_browser.exports,browser$4=deprecate;function deprecate($,I){if(config$1("noDeprecation"))return $;var U=!1;function q(){if(!U){if(config$1("throwDeprecation"))throw new Error(I);config$1("traceDeprecation")?console.trace(I):console.warn(I),U=!0}return $.apply(this,arguments)}return q}function config$1($){try{if(!commonjsGlobal.localStorage)return!1}catch{return!1}var I=commonjsGlobal.localStorage[$];return I==null?!1:String(I).toLowerCase()==="true"}var _stream_writable,hasRequired_stream_writable;function require_stream_writable(){if(hasRequired_stream_writable)return _stream_writable;hasRequired_stream_writable=1,_stream_writable=be;function $(je){var ze=this;this.next=null,this.entry=null,this.finish=function(){vt(ze,je)}}var I;be.WritableState=ve;var U={deprecate:browser$4},q=streamBrowser,G=buffer.Buffer,K=commonjsGlobal.Uint8Array||function(){};function Y(je){return G.from(je)}function J(je){return G.isBuffer(je)||je instanceof K}var X=destroy_1,Z=state,Q=Z.getHighWaterMark,ee=errorsBrowser.codes,te=ee.ERR_INVALID_ARG_TYPE,ne=ee.ERR_METHOD_NOT_IMPLEMENTED,ie=ee.ERR_MULTIPLE_CALLBACK,oe=ee.ERR_STREAM_CANNOT_PIPE,ce=ee.ERR_STREAM_DESTROYED,fe=ee.ERR_STREAM_NULL_VALUES,se=ee.ERR_STREAM_WRITE_AFTER_END,de=ee.ERR_UNKNOWN_ENCODING,ue=X.errorOrDestroy;inherits_browserExports(be,q);function pe(){}function ve(je,ze,Ae){I=I||require_stream_duplex(),je=je||{},typeof Ae!="boolean"&&(Ae=ze instanceof I),this.objectMode=!!je.objectMode,Ae&&(this.objectMode=this.objectMode||!!je.writableObjectMode),this.highWaterMark=Q(this,je,"writableHighWaterMark",Ae),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var Re=je.decodeStrings===!1;this.decodeStrings=!Re,this.defaultEncoding=je.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(Ce){nt(ze,Ce)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=je.emitClose!==!1,this.autoDestroy=!!je.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new $(this)}ve.prototype.getBuffer=function(){for(var ze=this.bufferedRequest,Ae=[];ze;)Ae.push(ze),ze=ze.next;return Ae},function(){try{Object.defineProperty(ve.prototype,"buffer",{get:U.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}}();var me;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(me=Function.prototype[Symbol.hasInstance],Object.defineProperty(be,Symbol.hasInstance,{value:function(ze){return me.call(this,ze)?!0:this!==be?!1:ze&&ze._writableState instanceof ve}})):me=function(ze){return ze instanceof this};function be(je){I=I||require_stream_duplex();var ze=this instanceof I;if(!ze&&!me.call(be,this))return new be(je);this._writableState=new ve(je,this,ze),this.writable=!0,je&&(typeof je.write=="function"&&(this._write=je.write),typeof je.writev=="function"&&(this._writev=je.writev),typeof je.destroy=="function"&&(this._destroy=je.destroy),typeof je.final=="function"&&(this._final=je.final)),q.call(this)}be.prototype.pipe=function(){ue(this,new oe)};function ye(je,ze){var Ae=new se;ue(je,Ae),process.nextTick(ze,Ae)}function Se(je,ze,Ae,Re){var Ce;return Ae===null?Ce=new fe:typeof Ae!="string"&&!ze.objectMode&&(Ce=new te("chunk",["string","Buffer"],Ae)),Ce?(ue(je,Ce),process.nextTick(Re,Ce),!1):!0}be.prototype.write=function(je,ze,Ae){var Re=this._writableState,Ce=!1,ge=!Re.objectMode&&J(je);return ge&&!G.isBuffer(je)&&(je=Y(je)),typeof ze=="function"&&(Ae=ze,ze=null),ge?ze="buffer":ze||(ze=Re.defaultEncoding),typeof Ae!="function"&&(Ae=pe),Re.ending?ye(this,Ae):(ge||Se(this,Re,je,Ae))&&(Re.pendingcb++,Ce=ke(this,Re,ge,je,ze,Ae)),Ce},be.prototype.cork=function(){this._writableState.corked++},be.prototype.uncork=function(){var je=this._writableState;je.corked&&(je.corked--,!je.writing&&!je.corked&&!je.bufferProcessing&&je.bufferedRequest&&it(this,je))},be.prototype.setDefaultEncoding=function(ze){if(typeof ze=="string"&&(ze=ze.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((ze+"").toLowerCase())>-1))throw new de(ze);return this._writableState.defaultEncoding=ze,this},Object.defineProperty(be.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function xe(je,ze,Ae){return!je.objectMode&&je.decodeStrings!==!1&&typeof ze=="string"&&(ze=G.from(ze,Ae)),ze}Object.defineProperty(be.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function ke(je,ze,Ae,Re,Ce,ge){if(!Ae){var _e=xe(ze,Re,Ce);Re!==_e&&(Ae=!0,Ce="buffer",Re=_e)}var Me=ze.objectMode?1:Re.length;ze.length+=Me;var Ke=ze.length<ze.highWaterMark;if(Ke||(ze.needDrain=!0),ze.writing||ze.corked){var st=ze.lastBufferedRequest;ze.lastBufferedRequest={chunk:Re,encoding:Ce,isBuf:Ae,callback:ge,next:null},st?st.next=ze.lastBufferedRequest:ze.bufferedRequest=ze.lastBufferedRequest,ze.bufferedRequestCount+=1}else De(je,ze,!1,Me,Re,Ce,ge);return Ke}function De(je,ze,Ae,Re,Ce,ge,_e){ze.writelen=Re,ze.writecb=_e,ze.writing=!0,ze.sync=!0,ze.destroyed?ze.onwrite(new ce("write")):Ae?je._writev(Ce,ze.onwrite):je._write(Ce,ge,ze.onwrite),ze.sync=!1}function Be(je,ze,Ae,Re,Ce){--ze.pendingcb,Ae?(process.nextTick(Ce,Re),process.nextTick(We,je,ze),je._writableState.errorEmitted=!0,ue(je,Re)):(Ce(Re),je._writableState.errorEmitted=!0,ue(je,Re),We(je,ze))}function Ve(je){je.writing=!1,je.writecb=null,je.length-=je.writelen,je.writelen=0}function nt(je,ze){var Ae=je._writableState,Re=Ae.sync,Ce=Ae.writecb;if(typeof Ce!="function")throw new ie;if(Ve(Ae),ze)Be(je,Ae,Re,ze,Ce);else{var ge=ut(Ae)||je.destroyed;!ge&&!Ae.corked&&!Ae.bufferProcessing&&Ae.bufferedRequest&&it(je,Ae),Re?process.nextTick(ot,je,Ae,ge,Ce):ot(je,Ae,ge,Ce)}}function ot(je,ze,Ae,Re){Ae||ft(je,ze),ze.pendingcb--,Re(),We(je,ze)}function ft(je,ze){ze.length===0&&ze.needDrain&&(ze.needDrain=!1,je.emit("drain"))}function it(je,ze){ze.bufferProcessing=!0;var Ae=ze.bufferedRequest;if(je._writev&&Ae&&Ae.next){var Re=ze.bufferedRequestCount,Ce=new Array(Re),ge=ze.corkedRequestsFree;ge.entry=Ae;for(var _e=0,Me=!0;Ae;)Ce[_e]=Ae,Ae.isBuf||(Me=!1),Ae=Ae.next,_e+=1;Ce.allBuffers=Me,De(je,ze,!0,ze.length,Ce,"",ge.finish),ze.pendingcb++,ze.lastBufferedRequest=null,ge.next?(ze.corkedRequestsFree=ge.next,ge.next=null):ze.corkedRequestsFree=new $(ze),ze.bufferedRequestCount=0}else{for(;Ae;){var Ke=Ae.chunk,st=Ae.encoding,dt=Ae.callback,$t=ze.objectMode?1:Ke.length;if(De(je,ze,!1,$t,Ke,st,dt),Ae=Ae.next,ze.bufferedRequestCount--,ze.writing)break}Ae===null&&(ze.lastBufferedRequest=null)}ze.bufferedRequest=Ae,ze.bufferProcessing=!1}be.prototype._write=function(je,ze,Ae){Ae(new ne("_write()"))},be.prototype._writev=null,be.prototype.end=function(je,ze,Ae){var Re=this._writableState;return typeof je=="function"?(Ae=je,je=null,ze=null):typeof ze=="function"&&(Ae=ze,ze=null),je!=null&&this.write(je,ze),Re.corked&&(Re.corked=1,this.uncork()),Re.ending||tt(this,Re,Ae),this},Object.defineProperty(be.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function ut(je){return je.ending&&je.length===0&&je.bufferedRequest===null&&!je.finished&&!je.writing}function et(je,ze){je._final(function(Ae){ze.pendingcb--,Ae&&ue(je,Ae),ze.prefinished=!0,je.emit("prefinish"),We(je,ze)})}function Ue(je,ze){!ze.prefinished&&!ze.finalCalled&&(typeof je._final=="function"&&!ze.destroyed?(ze.pendingcb++,ze.finalCalled=!0,process.nextTick(et,je,ze)):(ze.prefinished=!0,je.emit("prefinish")))}function We(je,ze){var Ae=ut(ze);if(Ae&&(Ue(je,ze),ze.pendingcb===0&&(ze.finished=!0,je.emit("finish"),ze.autoDestroy))){var Re=je._readableState;(!Re||Re.autoDestroy&&Re.endEmitted)&&je.destroy()}return Ae}function tt(je,ze,Ae){ze.ending=!0,We(je,ze),Ae&&(ze.finished?process.nextTick(Ae):je.once("finish",Ae)),ze.ended=!0,je.writable=!1}function vt(je,ze,Ae){var Re=je.entry;for(je.entry=null;Re;){var Ce=Re.callback;ze.pendingcb--,Ce(Ae),Re=Re.next}ze.corkedRequestsFree.next=je}return Object.defineProperty(be.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(ze){this._writableState&&(this._writableState.destroyed=ze)}}),be.prototype.destroy=X.destroy,be.prototype._undestroy=X.undestroy,be.prototype._destroy=function(je,ze){ze(je)},_stream_writable}var _stream_duplex,hasRequired_stream_duplex;function require_stream_duplex(){if(hasRequired_stream_duplex)return _stream_duplex;hasRequired_stream_duplex=1;var $=Object.keys||function(Z){var Q=[];for(var ee in Z)Q.push(ee);return Q};_stream_duplex=Y;var I=require_stream_readable(),U=require_stream_writable();inherits_browserExports(Y,I);for(var q=$(U.prototype),G=0;G<q.length;G++){var K=q[G];Y.prototype[K]||(Y.prototype[K]=U.prototype[K])}function Y(Z){if(!(this instanceof Y))return new Y(Z);I.call(this,Z),U.call(this,Z),this.allowHalfOpen=!0,Z&&(Z.readable===!1&&(this.readable=!1),Z.writable===!1&&(this.writable=!1),Z.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",J)))}Object.defineProperty(Y.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(Y.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Y.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function J(){this._writableState.ended||process.nextTick(X,this)}function X(Z){Z.end()}return Object.defineProperty(Y.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(Q){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=Q,this._writableState.destroyed=Q)}}),_stream_duplex}var string_decoder={},safeBuffer={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var hasRequiredSafeBuffer;function requireSafeBuffer(){return hasRequiredSafeBuffer||(hasRequiredSafeBuffer=1,function($,I){var U=buffer,q=U.Buffer;function G(Y,J){for(var X in Y)J[X]=Y[X]}q.from&&q.alloc&&q.allocUnsafe&&q.allocUnsafeSlow?$.exports=U:(G(U,I),I.Buffer=K);function K(Y,J,X){return q(Y,J,X)}K.prototype=Object.create(q.prototype),G(q,K),K.from=function(Y,J,X){if(typeof Y=="number")throw new TypeError("Argument must not be a number");return q(Y,J,X)},K.alloc=function(Y,J,X){if(typeof Y!="number")throw new TypeError("Argument must be a number");var Z=q(Y);return J!==void 0?typeof X=="string"?Z.fill(J,X):Z.fill(J):Z.fill(0),Z},K.allocUnsafe=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return q(Y)},K.allocUnsafeSlow=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return U.SlowBuffer(Y)}}(safeBuffer,safeBuffer.exports)),safeBuffer.exports}var hasRequiredString_decoder;function requireString_decoder(){if(hasRequiredString_decoder)return string_decoder;hasRequiredString_decoder=1;var $=requireSafeBuffer().Buffer,I=$.isEncoding||function(fe){switch(fe=""+fe,fe&&fe.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function U(fe){if(!fe)return"utf8";for(var se;;)switch(fe){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return fe;default:if(se)return;fe=(""+fe).toLowerCase(),se=!0}}function q(fe){var se=U(fe);if(typeof se!="string"&&($.isEncoding===I||!I(fe)))throw new Error("Unknown encoding: "+fe);return se||fe}string_decoder.StringDecoder=G;function G(fe){this.encoding=q(fe);var se;switch(this.encoding){case"utf16le":this.text=ee,this.end=te,se=4;break;case"utf8":this.fillLast=X,se=4;break;case"base64":this.text=ne,this.end=ie,se=3;break;default:this.write=oe,this.end=ce;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=$.allocUnsafe(se)}G.prototype.write=function(fe){if(fe.length===0)return"";var se,de;if(this.lastNeed){if(se=this.fillLast(fe),se===void 0)return"";de=this.lastNeed,this.lastNeed=0}else de=0;return de<fe.length?se?se+this.text(fe,de):this.text(fe,de):se||""},G.prototype.end=Q,G.prototype.text=Z,G.prototype.fillLast=function(fe){if(this.lastNeed<=fe.length)return fe.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);fe.copy(this.lastChar,this.lastTotal-this.lastNeed,0,fe.length),this.lastNeed-=fe.length};function K(fe){return fe<=127?0:fe>>5===6?2:fe>>4===14?3:fe>>3===30?4:fe>>6===2?-1:-2}function Y(fe,se,de){var ue=se.length-1;if(ue<de)return 0;var pe=K(se[ue]);return pe>=0?(pe>0&&(fe.lastNeed=pe-1),pe):--ue<de||pe===-2?0:(pe=K(se[ue]),pe>=0?(pe>0&&(fe.lastNeed=pe-2),pe):--ue<de||pe===-2?0:(pe=K(se[ue]),pe>=0?(pe>0&&(pe===2?pe=0:fe.lastNeed=pe-3),pe):0))}function J(fe,se,de){if((se[0]&192)!==128)return fe.lastNeed=0,"�";if(fe.lastNeed>1&&se.length>1){if((se[1]&192)!==128)return fe.lastNeed=1,"�";if(fe.lastNeed>2&&se.length>2&&(se[2]&192)!==128)return fe.lastNeed=2,"�"}}function X(fe){var se=this.lastTotal-this.lastNeed,de=J(this,fe);if(de!==void 0)return de;if(this.lastNeed<=fe.length)return fe.copy(this.lastChar,se,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);fe.copy(this.lastChar,se,0,fe.length),this.lastNeed-=fe.length}function Z(fe,se){var de=Y(this,fe,se);if(!this.lastNeed)return fe.toString("utf8",se);this.lastTotal=de;var ue=fe.length-(de-this.lastNeed);return fe.copy(this.lastChar,0,ue),fe.toString("utf8",se,ue)}function Q(fe){var se=fe&&fe.length?this.write(fe):"";return this.lastNeed?se+"�":se}function ee(fe,se){if((fe.length-se)%2===0){var de=fe.toString("utf16le",se);if(de){var ue=de.charCodeAt(de.length-1);if(ue>=55296&&ue<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=fe[fe.length-2],this.lastChar[1]=fe[fe.length-1],de.slice(0,-1)}return de}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=fe[fe.length-1],fe.toString("utf16le",se,fe.length-1)}function te(fe){var se=fe&&fe.length?this.write(fe):"";if(this.lastNeed){var de=this.lastTotal-this.lastNeed;return se+this.lastChar.toString("utf16le",0,de)}return se}function ne(fe,se){var de=(fe.length-se)%3;return de===0?fe.toString("base64",se):(this.lastNeed=3-de,this.lastTotal=3,de===1?this.lastChar[0]=fe[fe.length-1]:(this.lastChar[0]=fe[fe.length-2],this.lastChar[1]=fe[fe.length-1]),fe.toString("base64",se,fe.length-de))}function ie(fe){var se=fe&&fe.length?this.write(fe):"";return this.lastNeed?se+this.lastChar.toString("base64",0,3-this.lastNeed):se}function oe(fe){return fe.toString(this.encoding)}function ce(fe){return fe&&fe.length?this.write(fe):""}return string_decoder}var ERR_STREAM_PREMATURE_CLOSE=errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE;function once$1($){var I=!1;return function(){if(!I){I=!0;for(var U=arguments.length,q=new Array(U),G=0;G<U;G++)q[G]=arguments[G];$.apply(this,q)}}}function noop$2(){}function isRequest$1($){return $.setHeader&&typeof $.abort=="function"}function eos$1($,I,U){if(typeof I=="function")return eos$1($,null,I);I||(I={}),U=once$1(U||noop$2);var q=I.readable||I.readable!==!1&&$.readable,G=I.writable||I.writable!==!1&&$.writable,K=function(){$.writable||J()},Y=$._writableState&&$._writableState.finished,J=function(){G=!1,Y=!0,q||U.call($)},X=$._readableState&&$._readableState.endEmitted,Z=function(){q=!1,X=!0,G||U.call($)},Q=function(ie){U.call($,ie)},ee=function(){var ie;if(q&&!X)return(!$._readableState||!$._readableState.ended)&&(ie=new ERR_STREAM_PREMATURE_CLOSE),U.call($,ie);if(G&&!Y)return(!$._writableState||!$._writableState.ended)&&(ie=new ERR_STREAM_PREMATURE_CLOSE),U.call($,ie)},te=function(){$.req.on("finish",J)};return isRequest$1($)?($.on("complete",J),$.on("abort",ee),$.req?te():$.on("request",te)):G&&!$._writableState&&($.on("end",K),$.on("close",K)),$.on("end",Z),$.on("finish",J),I.error!==!1&&$.on("error",Q),$.on("close",ee),function(){$.removeListener("complete",J),$.removeListener("abort",ee),$.removeListener("request",te),$.req&&$.req.removeListener("finish",J),$.removeListener("end",K),$.removeListener("close",K),$.removeListener("finish",J),$.removeListener("end",Z),$.removeListener("error",Q),$.removeListener("close",ee)}}var endOfStream=eos$1,async_iterator,hasRequiredAsync_iterator;function requireAsync_iterator(){if(hasRequiredAsync_iterator)return async_iterator;hasRequiredAsync_iterator=1;var $;function I(fe,se,de){return se in fe?Object.defineProperty(fe,se,{value:de,enumerable:!0,configurable:!0,writable:!0}):fe[se]=de,fe}var U=endOfStream,q=Symbol("lastResolve"),G=Symbol("lastReject"),K=Symbol("error"),Y=Symbol("ended"),J=Symbol("lastPromise"),X=Symbol("handlePromise"),Z=Symbol("stream");function Q(fe,se){return{value:fe,done:se}}function ee(fe){var se=fe[q];if(se!==null){var de=fe[Z].read();de!==null&&(fe[J]=null,fe[q]=null,fe[G]=null,se(Q(de,!1)))}}function te(fe){process.nextTick(ee,fe)}function ne(fe,se){return function(de,ue){fe.then(function(){if(se[Y]){de(Q(void 0,!0));return}se[X](de,ue)},ue)}}var ie=Object.getPrototypeOf(function(){}),oe=Object.setPrototypeOf(($={get stream(){return this[Z]},next:function(){var se=this,de=this[K];if(de!==null)return Promise.reject(de);if(this[Y])return Promise.resolve(Q(void 0,!0));if(this[Z].destroyed)return new Promise(function(me,be){process.nextTick(function(){se[K]?be(se[K]):me(Q(void 0,!0))})});var ue=this[J],pe;if(ue)pe=new Promise(ne(ue,this));else{var ve=this[Z].read();if(ve!==null)return Promise.resolve(Q(ve,!1));pe=new Promise(this[X])}return this[J]=pe,pe}},I($,Symbol.asyncIterator,function(){return this}),I($,"return",function(){var se=this;return new Promise(function(de,ue){se[Z].destroy(null,function(pe){if(pe){ue(pe);return}de(Q(void 0,!0))})})}),$),ie),ce=function(se){var de,ue=Object.create(oe,(de={},I(de,Z,{value:se,writable:!0}),I(de,q,{value:null,writable:!0}),I(de,G,{value:null,writable:!0}),I(de,K,{value:null,writable:!0}),I(de,Y,{value:se._readableState.endEmitted,writable:!0}),I(de,X,{value:function(ve,me){var be=ue[Z].read();be?(ue[J]=null,ue[q]=null,ue[G]=null,ve(Q(be,!1))):(ue[q]=ve,ue[G]=me)},writable:!0}),de));return ue[J]=null,U(se,function(pe){if(pe&&pe.code!=="ERR_STREAM_PREMATURE_CLOSE"){var ve=ue[G];ve!==null&&(ue[J]=null,ue[q]=null,ue[G]=null,ve(pe)),ue[K]=pe;return}var me=ue[q];me!==null&&(ue[J]=null,ue[q]=null,ue[G]=null,me(Q(void 0,!0))),ue[Y]=!0}),se.on("readable",te.bind(null,ue)),ue};return async_iterator=ce,async_iterator}var fromBrowser,hasRequiredFromBrowser;function requireFromBrowser(){return hasRequiredFromBrowser||(hasRequiredFromBrowser=1,fromBrowser=function(){throw new Error("Readable.from is not available in the browser")}),fromBrowser}var _stream_readable,hasRequired_stream_readable;function require_stream_readable(){if(hasRequired_stream_readable)return _stream_readable;hasRequired_stream_readable=1,_stream_readable=ye;var $;ye.ReadableState=be,eventsExports.EventEmitter;var I=function(_e,Me){return _e.listeners(Me).length},U=streamBrowser,q=buffer.Buffer,G=commonjsGlobal.Uint8Array||function(){};function K(ge){return q.from(ge)}function Y(ge){return q.isBuffer(ge)||ge instanceof G}var J=require$$3,X;J&&J.debuglog?X=J.debuglog("stream"):X=function(){};var Z=requireBuffer_list(),Q=destroy_1,ee=state,te=ee.getHighWaterMark,ne=errorsBrowser.codes,ie=ne.ERR_INVALID_ARG_TYPE,oe=ne.ERR_STREAM_PUSH_AFTER_EOF,ce=ne.ERR_METHOD_NOT_IMPLEMENTED,fe=ne.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,se,de,ue;inherits_browserExports(ye,U);var pe=Q.errorOrDestroy,ve=["error","close","destroy","pause","resume"];function me(ge,_e,Me){if(typeof ge.prependListener=="function")return ge.prependListener(_e,Me);!ge._events||!ge._events[_e]?ge.on(_e,Me):Array.isArray(ge._events[_e])?ge._events[_e].unshift(Me):ge._events[_e]=[Me,ge._events[_e]]}function be(ge,_e,Me){$=$||require_stream_duplex(),ge=ge||{},typeof Me!="boolean"&&(Me=_e instanceof $),this.objectMode=!!ge.objectMode,Me&&(this.objectMode=this.objectMode||!!ge.readableObjectMode),this.highWaterMark=te(this,ge,"readableHighWaterMark",Me),this.buffer=new Z,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=ge.emitClose!==!1,this.autoDestroy=!!ge.autoDestroy,this.destroyed=!1,this.defaultEncoding=ge.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,ge.encoding&&(se||(se=requireString_decoder().StringDecoder),this.decoder=new se(ge.encoding),this.encoding=ge.encoding)}function ye(ge){if($=$||require_stream_duplex(),!(this instanceof ye))return new ye(ge);var _e=this instanceof $;this._readableState=new be(ge,this,_e),this.readable=!0,ge&&(typeof ge.read=="function"&&(this._read=ge.read),typeof ge.destroy=="function"&&(this._destroy=ge.destroy)),U.call(this)}Object.defineProperty(ye.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(_e){this._readableState&&(this._readableState.destroyed=_e)}}),ye.prototype.destroy=Q.destroy,ye.prototype._undestroy=Q.undestroy,ye.prototype._destroy=function(ge,_e){_e(ge)},ye.prototype.push=function(ge,_e){var Me=this._readableState,Ke;return Me.objectMode?Ke=!0:typeof ge=="string"&&(_e=_e||Me.defaultEncoding,_e!==Me.encoding&&(ge=q.from(ge,_e),_e=""),Ke=!0),Se(this,ge,_e,!1,Ke)},ye.prototype.unshift=function(ge){return Se(this,ge,null,!0,!1)};function Se(ge,_e,Me,Ke,st){X("readableAddChunk",_e);var dt=ge._readableState;if(_e===null)dt.reading=!1,nt(ge,dt);else{var $t;if(st||($t=ke(dt,_e)),$t)pe(ge,$t);else if(dt.objectMode||_e&&_e.length>0)if(typeof _e!="string"&&!dt.objectMode&&Object.getPrototypeOf(_e)!==q.prototype&&(_e=K(_e)),Ke)dt.endEmitted?pe(ge,new fe):xe(ge,dt,_e,!0);else if(dt.ended)pe(ge,new oe);else{if(dt.destroyed)return!1;dt.reading=!1,dt.decoder&&!Me?(_e=dt.decoder.write(_e),dt.objectMode||_e.length!==0?xe(ge,dt,_e,!1):it(ge,dt)):xe(ge,dt,_e,!1)}else Ke||(dt.reading=!1,it(ge,dt))}return!dt.ended&&(dt.length<dt.highWaterMark||dt.length===0)}function xe(ge,_e,Me,Ke){_e.flowing&&_e.length===0&&!_e.sync?(_e.awaitDrain=0,ge.emit("data",Me)):(_e.length+=_e.objectMode?1:Me.length,Ke?_e.buffer.unshift(Me):_e.buffer.push(Me),_e.needReadable&&ot(ge)),it(ge,_e)}function ke(ge,_e){var Me;return!Y(_e)&&typeof _e!="string"&&_e!==void 0&&!ge.objectMode&&(Me=new ie("chunk",["string","Buffer","Uint8Array"],_e)),Me}ye.prototype.isPaused=function(){return this._readableState.flowing===!1},ye.prototype.setEncoding=function(ge){se||(se=requireString_decoder().StringDecoder);var _e=new se(ge);this._readableState.decoder=_e,this._readableState.encoding=this._readableState.decoder.encoding;for(var Me=this._readableState.buffer.head,Ke="";Me!==null;)Ke+=_e.write(Me.data),Me=Me.next;return this._readableState.buffer.clear(),Ke!==""&&this._readableState.buffer.push(Ke),this._readableState.length=Ke.length,this};var De=1073741824;function Be(ge){return ge>=De?ge=De:(ge--,ge|=ge>>>1,ge|=ge>>>2,ge|=ge>>>4,ge|=ge>>>8,ge|=ge>>>16,ge++),ge}function Ve(ge,_e){return ge<=0||_e.length===0&&_e.ended?0:_e.objectMode?1:ge!==ge?_e.flowing&&_e.length?_e.buffer.head.data.length:_e.length:(ge>_e.highWaterMark&&(_e.highWaterMark=Be(ge)),ge<=_e.length?ge:_e.ended?_e.length:(_e.needReadable=!0,0))}ye.prototype.read=function(ge){X("read",ge),ge=parseInt(ge,10);var _e=this._readableState,Me=ge;if(ge!==0&&(_e.emittedReadable=!1),ge===0&&_e.needReadable&&((_e.highWaterMark!==0?_e.length>=_e.highWaterMark:_e.length>0)||_e.ended))return X("read: emitReadable",_e.length,_e.ended),_e.length===0&&_e.ended?Ae(this):ot(this),null;if(ge=Ve(ge,_e),ge===0&&_e.ended)return _e.length===0&&Ae(this),null;var Ke=_e.needReadable;X("need readable",Ke),(_e.length===0||_e.length-ge<_e.highWaterMark)&&(Ke=!0,X("length less than watermark",Ke)),_e.ended||_e.reading?(Ke=!1,X("reading or ended",Ke)):Ke&&(X("do read"),_e.reading=!0,_e.sync=!0,_e.length===0&&(_e.needReadable=!0),this._read(_e.highWaterMark),_e.sync=!1,_e.reading||(ge=Ve(Me,_e)));var st;return ge>0?st=ze(ge,_e):st=null,st===null?(_e.needReadable=_e.length<=_e.highWaterMark,ge=0):(_e.length-=ge,_e.awaitDrain=0),_e.length===0&&(_e.ended||(_e.needReadable=!0),Me!==ge&&_e.ended&&Ae(this)),st!==null&&this.emit("data",st),st};function nt(ge,_e){if(X("onEofChunk"),!_e.ended){if(_e.decoder){var Me=_e.decoder.end();Me&&Me.length&&(_e.buffer.push(Me),_e.length+=_e.objectMode?1:Me.length)}_e.ended=!0,_e.sync?ot(ge):(_e.needReadable=!1,_e.emittedReadable||(_e.emittedReadable=!0,ft(ge)))}}function ot(ge){var _e=ge._readableState;X("emitReadable",_e.needReadable,_e.emittedReadable),_e.needReadable=!1,_e.emittedReadable||(X("emitReadable",_e.flowing),_e.emittedReadable=!0,process.nextTick(ft,ge))}function ft(ge){var _e=ge._readableState;X("emitReadable_",_e.destroyed,_e.length,_e.ended),!_e.destroyed&&(_e.length||_e.ended)&&(ge.emit("readable"),_e.emittedReadable=!1),_e.needReadable=!_e.flowing&&!_e.ended&&_e.length<=_e.highWaterMark,je(ge)}function it(ge,_e){_e.readingMore||(_e.readingMore=!0,process.nextTick(ut,ge,_e))}function ut(ge,_e){for(;!_e.reading&&!_e.ended&&(_e.length<_e.highWaterMark||_e.flowing&&_e.length===0);){var Me=_e.length;if(X("maybeReadMore read 0"),ge.read(0),Me===_e.length)break}_e.readingMore=!1}ye.prototype._read=function(ge){pe(this,new ce("_read()"))},ye.prototype.pipe=function(ge,_e){var Me=this,Ke=this._readableState;switch(Ke.pipesCount){case 0:Ke.pipes=ge;break;case 1:Ke.pipes=[Ke.pipes,ge];break;default:Ke.pipes.push(ge);break}Ke.pipesCount+=1,X("pipe count=%d opts=%j",Ke.pipesCount,_e);var st=(!_e||_e.end!==!1)&&ge!==process.stdout&&ge!==process.stderr,dt=st?Et:Ut;Ke.endEmitted?process.nextTick(dt):Me.once("end",dt),ge.on("unpipe",$t);function $t(le,re){X("onunpipe"),le===Me&&re&&re.hasUnpiped===!1&&(re.hasUnpiped=!0,Gt())}function Et(){X("onend"),ge.end()}var rt=et(Me);ge.on("drain",rt);var jt=!1;function Gt(){X("cleanup"),ge.removeListener("close",nn),ge.removeListener("finish",St),ge.removeListener("drain",rt),ge.removeListener("error",zt),ge.removeListener("unpipe",$t),Me.removeListener("end",Et),Me.removeListener("end",Ut),Me.removeListener("data",At),jt=!0,Ke.awaitDrain&&(!ge._writableState||ge._writableState.needDrain)&&rt()}Me.on("data",At);function At(le){X("ondata");var re=ge.write(le);X("dest.write",re),re===!1&&((Ke.pipesCount===1&&Ke.pipes===ge||Ke.pipesCount>1&&Ce(Ke.pipes,ge)!==-1)&&!jt&&(X("false write response, pause",Ke.awaitDrain),Ke.awaitDrain++),Me.pause())}function zt(le){X("onerror",le),Ut(),ge.removeListener("error",zt),I(ge,"error")===0&&pe(ge,le)}me(ge,"error",zt);function nn(){ge.removeListener("finish",St),Ut()}ge.once("close",nn);function St(){X("onfinish"),ge.removeListener("close",nn),Ut()}ge.once("finish",St);function Ut(){X("unpipe"),Me.unpipe(ge)}return ge.emit("pipe",Me),Ke.flowing||(X("pipe resume"),Me.resume()),ge};function et(ge){return function(){var Me=ge._readableState;X("pipeOnDrain",Me.awaitDrain),Me.awaitDrain&&Me.awaitDrain--,Me.awaitDrain===0&&I(ge,"data")&&(Me.flowing=!0,je(ge))}}ye.prototype.unpipe=function(ge){var _e=this._readableState,Me={hasUnpiped:!1};if(_e.pipesCount===0)return this;if(_e.pipesCount===1)return ge&&ge!==_e.pipes?this:(ge||(ge=_e.pipes),_e.pipes=null,_e.pipesCount=0,_e.flowing=!1,ge&&ge.emit("unpipe",this,Me),this);if(!ge){var Ke=_e.pipes,st=_e.pipesCount;_e.pipes=null,_e.pipesCount=0,_e.flowing=!1;for(var dt=0;dt<st;dt++)Ke[dt].emit("unpipe",this,{hasUnpiped:!1});return this}var $t=Ce(_e.pipes,ge);return $t===-1?this:(_e.pipes.splice($t,1),_e.pipesCount-=1,_e.pipesCount===1&&(_e.pipes=_e.pipes[0]),ge.emit("unpipe",this,Me),this)},ye.prototype.on=function(ge,_e){var Me=U.prototype.on.call(this,ge,_e),Ke=this._readableState;return ge==="data"?(Ke.readableListening=this.listenerCount("readable")>0,Ke.flowing!==!1&&this.resume()):ge==="readable"&&!Ke.endEmitted&&!Ke.readableListening&&(Ke.readableListening=Ke.needReadable=!0,Ke.flowing=!1,Ke.emittedReadable=!1,X("on readable",Ke.length,Ke.reading),Ke.length?ot(this):Ke.reading||process.nextTick(We,this)),Me},ye.prototype.addListener=ye.prototype.on,ye.prototype.removeListener=function(ge,_e){var Me=U.prototype.removeListener.call(this,ge,_e);return ge==="readable"&&process.nextTick(Ue,this),Me},ye.prototype.removeAllListeners=function(ge){var _e=U.prototype.removeAllListeners.apply(this,arguments);return(ge==="readable"||ge===void 0)&&process.nextTick(Ue,this),_e};function Ue(ge){var _e=ge._readableState;_e.readableListening=ge.listenerCount("readable")>0,_e.resumeScheduled&&!_e.paused?_e.flowing=!0:ge.listenerCount("data")>0&&ge.resume()}function We(ge){X("readable nexttick read 0"),ge.read(0)}ye.prototype.resume=function(){var ge=this._readableState;return ge.flowing||(X("resume"),ge.flowing=!ge.readableListening,tt(this,ge)),ge.paused=!1,this};function tt(ge,_e){_e.resumeScheduled||(_e.resumeScheduled=!0,process.nextTick(vt,ge,_e))}function vt(ge,_e){X("resume",_e.reading),_e.reading||ge.read(0),_e.resumeScheduled=!1,ge.emit("resume"),je(ge),_e.flowing&&!_e.reading&&ge.read(0)}ye.prototype.pause=function(){return X("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(X("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function je(ge){var _e=ge._readableState;for(X("flow",_e.flowing);_e.flowing&&ge.read()!==null;);}ye.prototype.wrap=function(ge){var _e=this,Me=this._readableState,Ke=!1;ge.on("end",function(){if(X("wrapped end"),Me.decoder&&!Me.ended){var $t=Me.decoder.end();$t&&$t.length&&_e.push($t)}_e.push(null)}),ge.on("data",function($t){if(X("wrapped data"),Me.decoder&&($t=Me.decoder.write($t)),!(Me.objectMode&&$t==null)&&!(!Me.objectMode&&(!$t||!$t.length))){var Et=_e.push($t);Et||(Ke=!0,ge.pause())}});for(var st in ge)this[st]===void 0&&typeof ge[st]=="function"&&(this[st]=function(Et){return function(){return ge[Et].apply(ge,arguments)}}(st));for(var dt=0;dt<ve.length;dt++)ge.on(ve[dt],this.emit.bind(this,ve[dt]));return this._read=function($t){X("wrapped _read",$t),Ke&&(Ke=!1,ge.resume())},this},typeof Symbol=="function"&&(ye.prototype[Symbol.asyncIterator]=function(){return de===void 0&&(de=requireAsync_iterator()),de(this)}),Object.defineProperty(ye.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(ye.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(ye.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(_e){this._readableState&&(this._readableState.flowing=_e)}}),ye._fromList=ze,Object.defineProperty(ye.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function ze(ge,_e){if(_e.length===0)return null;var Me;return _e.objectMode?Me=_e.buffer.shift():!ge||ge>=_e.length?(_e.decoder?Me=_e.buffer.join(""):_e.buffer.length===1?Me=_e.buffer.first():Me=_e.buffer.concat(_e.length),_e.buffer.clear()):Me=_e.buffer.consume(ge,_e.decoder),Me}function Ae(ge){var _e=ge._readableState;X("endReadable",_e.endEmitted),_e.endEmitted||(_e.ended=!0,process.nextTick(Re,_e,ge))}function Re(ge,_e){if(X("endReadableNT",ge.endEmitted,ge.length),!ge.endEmitted&&ge.length===0&&(ge.endEmitted=!0,_e.readable=!1,_e.emit("end"),ge.autoDestroy)){var Me=_e._writableState;(!Me||Me.autoDestroy&&Me.finished)&&_e.destroy()}}typeof Symbol=="function"&&(ye.from=function(ge,_e){return ue===void 0&&(ue=requireFromBrowser()),ue(ye,ge,_e)});function Ce(ge,_e){for(var Me=0,Ke=ge.length;Me<Ke;Me++)if(ge[Me]===_e)return Me;return-1}return _stream_readable}var _stream_transform=Transform$1,_require$codes$1=errorsBrowser.codes,ERR_METHOD_NOT_IMPLEMENTED=_require$codes$1.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes$1.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0,Duplex=require_stream_duplex();inherits_browserExports(Transform$1,Duplex);function afterTransform($,I){var U=this._transformState;U.transforming=!1;var q=U.writecb;if(q===null)return this.emit("error",new ERR_MULTIPLE_CALLBACK);U.writechunk=null,U.writecb=null,I!=null&&this.push(I),q($);var G=this._readableState;G.reading=!1,(G.needReadable||G.length<G.highWaterMark)&&this._read(G.highWaterMark)}function Transform$1($){if(!(this instanceof Transform$1))return new Transform$1($);Duplex.call(this,$),this._transformState={afterTransform:afterTransform.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,$&&(typeof $.transform=="function"&&(this._transform=$.transform),typeof $.flush=="function"&&(this._flush=$.flush)),this.on("prefinish",prefinish)}function prefinish(){var $=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(I,U){done$1($,I,U)}):done$1(this,null,null)}Transform$1.prototype.push=function($,I){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,$,I)},Transform$1.prototype._transform=function($,I,U){U(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"))},Transform$1.prototype._write=function($,I,U){var q=this._transformState;if(q.writecb=U,q.writechunk=$,q.writeencoding=I,!q.transforming){var G=this._readableState;(q.needTransform||G.needReadable||G.length<G.highWaterMark)&&this._read(G.highWaterMark)}},Transform$1.prototype._read=function($){var I=this._transformState;I.writechunk!==null&&!I.transforming?(I.transforming=!0,this._transform(I.writechunk,I.writeencoding,I.afterTransform)):I.needTransform=!0},Transform$1.prototype._destroy=function($,I){Duplex.prototype._destroy.call(this,$,function(U){I(U)})};function done$1($,I,U){if(I)return $.emit("error",I);if(U!=null&&$.push(U),$._writableState.length)throw new ERR_TRANSFORM_WITH_LENGTH_0;if($._transformState.transforming)throw new ERR_TRANSFORM_ALREADY_TRANSFORMING;return $.push(null)}var _stream_passthrough=PassThrough,Transform=_stream_transform;inherits_browserExports(PassThrough,Transform);function PassThrough($){if(!(this instanceof PassThrough))return new PassThrough($);Transform.call(this,$)}PassThrough.prototype._transform=function($,I,U){U(null,$)};var eos;function once($){var I=!1;return function(){I||(I=!0,$.apply(void 0,arguments))}}var _require$codes=errorsBrowser.codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED;function noop$1($){if($)throw $}function isRequest($){return $.setHeader&&typeof $.abort=="function"}function destroyer($,I,U,q){q=once(q);var G=!1;$.on("close",function(){G=!0}),eos===void 0&&(eos=endOfStream),eos($,{readable:I,writable:U},function(Y){if(Y)return q(Y);G=!0,q()});var K=!1;return function(Y){if(!G&&!K){if(K=!0,isRequest($))return $.abort();if(typeof $.destroy=="function")return $.destroy();q(Y||new ERR_STREAM_DESTROYED("pipe"))}}}function call($){$()}function pipe($,I){return $.pipe(I)}function popCallback($){return!$.length||typeof $[$.length-1]!="function"?noop$1:$.pop()}function pipeline(){for(var $=arguments.length,I=new Array($),U=0;U<$;U++)I[U]=arguments[U];var q=popCallback(I);if(Array.isArray(I[0])&&(I=I[0]),I.length<2)throw new ERR_MISSING_ARGS("streams");var G,K=I.map(function(Y,J){var X=J<I.length-1,Z=J>0;return destroyer(Y,X,Z,function(Q){G||(G=Q),Q&&K.forEach(call),!X&&(K.forEach(call),q(G))})});return I.reduce(pipe)}var pipeline_1=pipeline;(function($,I){I=$.exports=require_stream_readable(),I.Stream=I,I.Readable=I,I.Writable=require_stream_writable(),I.Duplex=require_stream_duplex(),I.Transform=_stream_transform,I.PassThrough=_stream_passthrough,I.finished=endOfStream,I.pipeline=pipeline_1})(readableBrowser,readableBrowser.exports);var readableBrowserExports=readableBrowser.exports,createPromiseFromCallback=$=>new Promise((I,U)=>{$((q,G)=>{q?U(q):I(G)})}),TimeoutError=class extends Error{constructor($,I){super($?`Timeout [${$.toLocaleString()}ms]${I===void 0?"":`: ${I}`}`:"Timeout")}},sleep=$=>new Promise(I=>{const U=Date.now()+$,q=()=>{const G=U-Date.now();G>0?setTimeout(q,G):I()};q()}),asyncTimeout=async($,I,U)=>{let q;const G=U===void 0||typeof U=="string"?new TimeoutError(I,U):U,K=new Promise((J,X)=>{q=setTimeout(()=>{X(G)},I),unrefTimeout(q)}),Y=typeof $=="function"?createPromiseFromCallback($):$;return await Promise.race([Y,K]).finally(()=>{clearTimeout(q)})},unrefTimeout=$=>{typeof $=="object"&&"unref"in $&&$.unref()},Event$1=class hr{constructor(){this._listeners=new Set,this._effects=new Set}static wrap(I,U){const q=new hr;return q.addEffect(()=>{const G=K=>q.emit(K);return I.on(U,G),()=>I.off(U,G)}),q}emit(I){for(const U of this._listeners)U.trigger(I),U.once&&this._listeners.delete(U)}on(I,U,q){const[G,K]=I instanceof Context?[I,U]:[new Context,I],Y=!!(q!=null&&q.weak),J=!!(q!=null&&q.once),X=new EventListener(this,K,G,J,Y);return this._addListener(X),()=>{this._removeListener(X)}}off(I){for(const U of this._listeners)U.derefCallback()===I&&this._removeListener(U)}once(I,U){const[q,G]=I instanceof Context?[I,U]:[new Context,I],K=new EventListener(this,G,q,!0,!1);return this._addListener(K),()=>{this._removeListener(K)}}async*[Symbol.asyncIterator](){for(;;)yield await new Promise(I=>{this.once(I)})}waitFor(I){return new Promise(U=>{const q=this.on(G=>{I(G)&&(q(),U(G))})})}waitForCount(I){let U=0;return this.waitFor(()=>++U===I)}async waitForCondition(I){I()||await this.waitFor(I)}listenerCount(){return this._listeners.size}addEffect(I){const U={effect:I,cleanup:void 0};return this.listenerCount()>0&&(U.cleanup=U.effect()),this._effects.add(U),()=>{var q;(q=U.cleanup)==null||q.call(U),this._effects.delete(U)}}debounce(I=0){let U,q;const G=new hr;return G.addEffect(()=>{const K=this.on(()=>{if(!U){const Y=!q||Date.now()-q>I?I/8:I;U=setTimeout(()=>{q=Date.now(),U=void 0,G.emit()},Y)}});return()=>{K(),clearTimeout(U)}}),G}discardParameter(){return this}toJSON(){return{listenerCount:this.listenerCount()}}_addListener(I){this._listeners.add(I),this.listenerCount()===1&&this._runEffects()}_removeListener(I){this._listeners.delete(I),I.remove(),this.listenerCount()===0&&this._cleanupEffects()}_runEffects(){for(const I of this._effects)I.cleanup=I.effect()}_cleanupEffects(){var I;for(const U of this._effects)(I=U.cleanup)==null||I.call(U),U.cleanup=void 0}},EventListener=class{constructor($,I,U,q,G){this.ctx=U,this.once=q,this.weak=G,this._clearDispose=void 0,this._clearDispose=U.onDispose(()=>{$._removeListener(this)}),G?(this.callback=new WeakRef(I),weakListeners().registry.register(I,{event:new WeakRef($),listener:this},this)):this.callback=I}derefCallback(){return this.weak?this.callback.deref():this.callback}async trigger($){try{const I=this.derefCallback();await(I==null?void 0:I($))}catch(I){this.ctx.raise(I)}}remove(){var $;($=this._clearDispose)==null||$.call(this),weakListeners().registry.unregister(this)}},weakListenersState=null,weakListeners=()=>(weakListenersState??(weakListenersState=new FinalizationRegistry(({event:$,listener:I})=>{var U;(U=$.deref())==null||U._removeListener(I)})),{registry:weakListenersState}),Trigger=class{constructor($={autoReset:!1}){this._options=$,this.reset()}async wait({timeout:$}={}){return $?asyncTimeout(this._promise,$,new TimeoutError($)):this._promise}wake($){return this._wake($),this._options.autoReset?this.reset():this}reset(){return this._promise=new Promise($=>{this._wake=$}),this}throw($){return this._wake(Promise.reject($)),this._options.autoReset?this.reset():this}},MulticastObservable=class Jn extends Observable{constructor(I,U){super(q=>this._subscribe(q)),this._value=U,this._observers=new Set,this._completed=new Trigger,this._handlers={next:q=>{this._value=q,this._observers.forEach(G=>{var K;return(K=G.next)==null?void 0:K.call(G,q)})},error:q=>{this._observers.forEach(G=>{var K;return(K=G.error)==null?void 0:K.call(G,q)})},complete:()=>{this._completed.wake(),this._observers.forEach(q=>{var G;return(G=q.complete)==null?void 0:G.call(q)})}},this._observable=typeof I=="function"?new Observable(I):I,this._observable.subscribe(this._handlers)}static from(I,U){if("emit"in I)return new Jn(G=>{I.on(K=>{G.next(K)})},U);const q=Observable.from(I);return new Jn(q,U)}static of(...I){return new Jn(Observable.of(...I.slice(1)),I[0])}static empty(){return EMPTY_OBSERVABLE}get(){if(this._value===void 0)throw new Error("MulticastObservable is not initialized.");return this._value}async wait({timeout:I}={}){return await this._completed.wait({timeout:I}),this.get()}forEach(I){return this._observable.forEach(I)}map(I){return new Jn(this._observable.map(I),this._value&&I(this._value))}filter(I){return new Jn(this._observable.filter(I),this._value&&I(this._value)?this._value:void 0)}reduce(I,U){return new Jn(U?this._observable.reduce(I,U):this._observable.reduce(I),U??this._value)}flatMap(I){return new Jn(this._observable.flatMap(I),this._value&&I(this._value).get())}concat(...I){return new Jn(this._observable.concat(...I),this._value)}losslessConcat(I,...U){const q=U.filter(K=>K instanceof Jn),G=I(this._value,q.map(K=>K.get()));return new Jn(this._observable.concat(...U),G)}_subscribe(I){var U;return this._observers.has(I)||this._observers.add(I),this._value!==void 0&&((U=I.next)==null||U.call(I,this._value)),()=>{this._observers.delete(I)}}},EMPTY_OBSERVABLE=MulticastObservable.of(null),Mutex=class{constructor(){this._queue=Promise.resolve(),this._tag=null}get tag(){return this._tag}async acquire($){const I=this._queue;let U;return this._queue=new Promise(q=>{U=new MutexGuard(()=>{this._tag=null,q()})}),await I,$!==void 0&&(this._tag=$),U}async executeSynchronized($){const I=await this.acquire();try{return await $()}finally{I.release()}}},MutexGuard=class{constructor($){this._release=$}release(){this._release()}[Symbol.dispose](){this.release()}},classMutexSymbol=Symbol("class-mutex"),enableWarning=globalThis.mochaExecutor,synchronized=($,I,U)=>{const q=U.value;U.value=async function(...K){const Y=this[classMutexSymbol]??(this[classMutexSymbol]=new Mutex),J=`${$.constructor.name}.${I}`;let X;enableWarning?X=await warnAfterTimeout(1e4,`lock on ${J} (taken by ${Y.tag})`,()=>Y.acquire(J)):X=await Y.acquire(J);try{return await q.apply(this,K)}finally{X.release()}},Object.defineProperty(U.value,"name",{value:I+"$synchronized"})},__dxlog_file2$6="/home/runner/work/dxos/dxos/packages/common/async/src/track-leaks.ts",enabled=typeof process<"u"&&!!process.env.DX_TRACK_LEAKS,openResources=new Set,trackResource=$=>{if(!enabled)return()=>{};const I=$();return openResources.add(I),()=>{openResources.delete(I)}},dumpLeaks=()=>{if(enabled){log$2.info(`Leaked resources ${openResources.size}:`,void 0,{F:__dxlog_file2$6,L:82,S:void 0,C:($,I)=>$(...I)});for(const $ of openResources)log$2.info(`- ${$.name} at`,void 0,{F:__dxlog_file2$6,L:84,S:void 0,C:(I,U)=>I(...U)}),log$2.info($.openStack.getStack(1),void 0,{F:__dxlog_file2$6,L:85,S:void 0,C:(I,U)=>I(...U)}),log$2.info(`
|
|
851
|
+
*/(function($){const I=base64Js,U=ieee754,q=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;$.Buffer=J,$.SlowBuffer=se,$.INSPECT_MAX_BYTES=50;const G=2147483647;$.kMaxLength=G,J.TYPED_ARRAY_SUPPORT=K(),!J.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function K(){try{const le=new Uint8Array(1),re={foo:function(){return 42}};return Object.setPrototypeOf(re,Uint8Array.prototype),Object.setPrototypeOf(le,re),le.foo()===42}catch{return!1}}Object.defineProperty(J.prototype,"parent",{enumerable:!0,get:function(){if(J.isBuffer(this))return this.buffer}}),Object.defineProperty(J.prototype,"offset",{enumerable:!0,get:function(){if(J.isBuffer(this))return this.byteOffset}});function Y(le){if(le>G)throw new RangeError('The value "'+le+'" is invalid for option "size"');const re=new Uint8Array(le);return Object.setPrototypeOf(re,J.prototype),re}function J(le,re,ae){if(typeof le=="number"){if(typeof re=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return ee(le)}return X(le,re,ae)}J.poolSize=8192;function X(le,re,ae){if(typeof le=="string")return te(le,re);if(ArrayBuffer.isView(le))return ie(le);if(le==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof le);if(At(le,ArrayBuffer)||le&&At(le.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(At(le,SharedArrayBuffer)||le&&At(le.buffer,SharedArrayBuffer)))return oe(le,re,ae);if(typeof le=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const he=le.valueOf&&le.valueOf();if(he!=null&&he!==le)return J.from(he,re,ae);const we=ce(le);if(we)return we;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof le[Symbol.toPrimitive]=="function")return J.from(le[Symbol.toPrimitive]("string"),re,ae);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof le)}J.from=function(le,re,ae){return X(le,re,ae)},Object.setPrototypeOf(J.prototype,Uint8Array.prototype),Object.setPrototypeOf(J,Uint8Array);function Z(le){if(typeof le!="number")throw new TypeError('"size" argument must be of type number');if(le<0)throw new RangeError('The value "'+le+'" is invalid for option "size"')}function Q(le,re,ae){return Z(le),le<=0?Y(le):re!==void 0?typeof ae=="string"?Y(le).fill(re,ae):Y(le).fill(re):Y(le)}J.alloc=function(le,re,ae){return Q(le,re,ae)};function ee(le){return Z(le),Y(le<0?0:fe(le)|0)}J.allocUnsafe=function(le){return ee(le)},J.allocUnsafeSlow=function(le){return ee(le)};function te(le,re){if((typeof re!="string"||re==="")&&(re="utf8"),!J.isEncoding(re))throw new TypeError("Unknown encoding: "+re);const ae=de(le,re)|0;let he=Y(ae);const we=he.write(le,re);return we!==ae&&(he=he.slice(0,we)),he}function ne(le){const re=le.length<0?0:fe(le.length)|0,ae=Y(re);for(let he=0;he<re;he+=1)ae[he]=le[he]&255;return ae}function ie(le){if(At(le,Uint8Array)){const re=new Uint8Array(le);return oe(re.buffer,re.byteOffset,re.byteLength)}return ne(le)}function oe(le,re,ae){if(re<0||le.byteLength<re)throw new RangeError('"offset" is outside of buffer bounds');if(le.byteLength<re+(ae||0))throw new RangeError('"length" is outside of buffer bounds');let he;return re===void 0&&ae===void 0?he=new Uint8Array(le):ae===void 0?he=new Uint8Array(le,re):he=new Uint8Array(le,re,ae),Object.setPrototypeOf(he,J.prototype),he}function ce(le){if(J.isBuffer(le)){const re=fe(le.length)|0,ae=Y(re);return ae.length===0||le.copy(ae,0,0,re),ae}if(le.length!==void 0)return typeof le.length!="number"||zt(le.length)?Y(0):ne(le);if(le.type==="Buffer"&&Array.isArray(le.data))return ne(le.data)}function fe(le){if(le>=G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");return le|0}function se(le){return+le!=le&&(le=0),J.alloc(+le)}J.isBuffer=function(re){return re!=null&&re._isBuffer===!0&&re!==J.prototype},J.compare=function(re,ae){if(At(re,Uint8Array)&&(re=J.from(re,re.offset,re.byteLength)),At(ae,Uint8Array)&&(ae=J.from(ae,ae.offset,ae.byteLength)),!J.isBuffer(re)||!J.isBuffer(ae))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(re===ae)return 0;let he=re.length,we=ae.length;for(let Ee=0,Le=Math.min(he,we);Ee<Le;++Ee)if(re[Ee]!==ae[Ee]){he=re[Ee],we=ae[Ee];break}return he<we?-1:we<he?1:0},J.isEncoding=function(re){switch(String(re).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},J.concat=function(re,ae){if(!Array.isArray(re))throw new TypeError('"list" argument must be an Array of Buffers');if(re.length===0)return J.alloc(0);let he;if(ae===void 0)for(ae=0,he=0;he<re.length;++he)ae+=re[he].length;const we=J.allocUnsafe(ae);let Ee=0;for(he=0;he<re.length;++he){let Le=re[he];if(At(Le,Uint8Array))Ee+Le.length>we.length?(J.isBuffer(Le)||(Le=J.from(Le)),Le.copy(we,Ee)):Uint8Array.prototype.set.call(we,Le,Ee);else if(J.isBuffer(Le))Le.copy(we,Ee);else throw new TypeError('"list" argument must be an Array of Buffers');Ee+=Le.length}return we};function de(le,re){if(J.isBuffer(le))return le.length;if(ArrayBuffer.isView(le)||At(le,ArrayBuffer))return le.byteLength;if(typeof le!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof le);const ae=le.length,he=arguments.length>2&&arguments[2]===!0;if(!he&&ae===0)return 0;let we=!1;for(;;)switch(re){case"ascii":case"latin1":case"binary":return ae;case"utf8":case"utf-8":return $t(le).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ae*2;case"hex":return ae>>>1;case"base64":return jt(le).length;default:if(we)return he?-1:$t(le).length;re=(""+re).toLowerCase(),we=!0}}J.byteLength=de;function ue(le,re,ae){let he=!1;if((re===void 0||re<0)&&(re=0),re>this.length||((ae===void 0||ae>this.length)&&(ae=this.length),ae<=0)||(ae>>>=0,re>>>=0,ae<=re))return"";for(le||(le="utf8");;)switch(le){case"hex":return it(this,re,ae);case"utf8":case"utf-8":return Be(this,re,ae);case"ascii":return ot(this,re,ae);case"latin1":case"binary":return ft(this,re,ae);case"base64":return De(this,re,ae);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ut(this,re,ae);default:if(he)throw new TypeError("Unknown encoding: "+le);le=(le+"").toLowerCase(),he=!0}}J.prototype._isBuffer=!0;function pe(le,re,ae){const he=le[re];le[re]=le[ae],le[ae]=he}J.prototype.swap16=function(){const re=this.length;if(re%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let ae=0;ae<re;ae+=2)pe(this,ae,ae+1);return this},J.prototype.swap32=function(){const re=this.length;if(re%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let ae=0;ae<re;ae+=4)pe(this,ae,ae+3),pe(this,ae+1,ae+2);return this},J.prototype.swap64=function(){const re=this.length;if(re%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let ae=0;ae<re;ae+=8)pe(this,ae,ae+7),pe(this,ae+1,ae+6),pe(this,ae+2,ae+5),pe(this,ae+3,ae+4);return this},J.prototype.toString=function(){const re=this.length;return re===0?"":arguments.length===0?Be(this,0,re):ue.apply(this,arguments)},J.prototype.toLocaleString=J.prototype.toString,J.prototype.equals=function(re){if(!J.isBuffer(re))throw new TypeError("Argument must be a Buffer");return this===re?!0:J.compare(this,re)===0},J.prototype.inspect=function(){let re="";const ae=$.INSPECT_MAX_BYTES;return re=this.toString("hex",0,ae).replace(/(.{2})/g,"$1 ").trim(),this.length>ae&&(re+=" ... "),"<Buffer "+re+">"},q&&(J.prototype[q]=J.prototype.inspect),J.prototype.compare=function(re,ae,he,we,Ee){if(At(re,Uint8Array)&&(re=J.from(re,re.offset,re.byteLength)),!J.isBuffer(re))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof re);if(ae===void 0&&(ae=0),he===void 0&&(he=re?re.length:0),we===void 0&&(we=0),Ee===void 0&&(Ee=this.length),ae<0||he>re.length||we<0||Ee>this.length)throw new RangeError("out of range index");if(we>=Ee&&ae>=he)return 0;if(we>=Ee)return-1;if(ae>=he)return 1;if(ae>>>=0,he>>>=0,we>>>=0,Ee>>>=0,this===re)return 0;let Le=Ee-we,bt=he-ae;const Lt=Math.min(Le,bt),Ct=this.slice(we,Ee),It=re.slice(ae,he);for(let Tt=0;Tt<Lt;++Tt)if(Ct[Tt]!==It[Tt]){Le=Ct[Tt],bt=It[Tt];break}return Le<bt?-1:bt<Le?1:0};function ve(le,re,ae,he,we){if(le.length===0)return-1;if(typeof ae=="string"?(he=ae,ae=0):ae>2147483647?ae=2147483647:ae<-2147483648&&(ae=-2147483648),ae=+ae,zt(ae)&&(ae=we?0:le.length-1),ae<0&&(ae=le.length+ae),ae>=le.length){if(we)return-1;ae=le.length-1}else if(ae<0)if(we)ae=0;else return-1;if(typeof re=="string"&&(re=J.from(re,he)),J.isBuffer(re))return re.length===0?-1:me(le,re,ae,he,we);if(typeof re=="number")return re=re&255,typeof Uint8Array.prototype.indexOf=="function"?we?Uint8Array.prototype.indexOf.call(le,re,ae):Uint8Array.prototype.lastIndexOf.call(le,re,ae):me(le,[re],ae,he,we);throw new TypeError("val must be string, number or Buffer")}function me(le,re,ae,he,we){let Ee=1,Le=le.length,bt=re.length;if(he!==void 0&&(he=String(he).toLowerCase(),he==="ucs2"||he==="ucs-2"||he==="utf16le"||he==="utf-16le")){if(le.length<2||re.length<2)return-1;Ee=2,Le/=2,bt/=2,ae/=2}function Lt(It,Tt){return Ee===1?It[Tt]:It.readUInt16BE(Tt*Ee)}let Ct;if(we){let It=-1;for(Ct=ae;Ct<Le;Ct++)if(Lt(le,Ct)===Lt(re,It===-1?0:Ct-It)){if(It===-1&&(It=Ct),Ct-It+1===bt)return It*Ee}else It!==-1&&(Ct-=Ct-It),It=-1}else for(ae+bt>Le&&(ae=Le-bt),Ct=ae;Ct>=0;Ct--){let It=!0;for(let Tt=0;Tt<bt;Tt++)if(Lt(le,Ct+Tt)!==Lt(re,Tt)){It=!1;break}if(It)return Ct}return-1}J.prototype.includes=function(re,ae,he){return this.indexOf(re,ae,he)!==-1},J.prototype.indexOf=function(re,ae,he){return ve(this,re,ae,he,!0)},J.prototype.lastIndexOf=function(re,ae,he){return ve(this,re,ae,he,!1)};function be(le,re,ae,he){ae=Number(ae)||0;const we=le.length-ae;he?(he=Number(he),he>we&&(he=we)):he=we;const Ee=re.length;he>Ee/2&&(he=Ee/2);let Le;for(Le=0;Le<he;++Le){const bt=parseInt(re.substr(Le*2,2),16);if(zt(bt))return Le;le[ae+Le]=bt}return Le}function ye(le,re,ae,he){return Gt($t(re,le.length-ae),le,ae,he)}function Se(le,re,ae,he){return Gt(Et(re),le,ae,he)}function xe(le,re,ae,he){return Gt(jt(re),le,ae,he)}function ke(le,re,ae,he){return Gt(rt(re,le.length-ae),le,ae,he)}J.prototype.write=function(re,ae,he,we){if(ae===void 0)we="utf8",he=this.length,ae=0;else if(he===void 0&&typeof ae=="string")we=ae,he=this.length,ae=0;else if(isFinite(ae))ae=ae>>>0,isFinite(he)?(he=he>>>0,we===void 0&&(we="utf8")):(we=he,he=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const Ee=this.length-ae;if((he===void 0||he>Ee)&&(he=Ee),re.length>0&&(he<0||ae<0)||ae>this.length)throw new RangeError("Attempt to write outside buffer bounds");we||(we="utf8");let Le=!1;for(;;)switch(we){case"hex":return be(this,re,ae,he);case"utf8":case"utf-8":return ye(this,re,ae,he);case"ascii":case"latin1":case"binary":return Se(this,re,ae,he);case"base64":return xe(this,re,ae,he);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ke(this,re,ae,he);default:if(Le)throw new TypeError("Unknown encoding: "+we);we=(""+we).toLowerCase(),Le=!0}},J.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function De(le,re,ae){return re===0&&ae===le.length?I.fromByteArray(le):I.fromByteArray(le.slice(re,ae))}function Be(le,re,ae){ae=Math.min(le.length,ae);const he=[];let we=re;for(;we<ae;){const Ee=le[we];let Le=null,bt=Ee>239?4:Ee>223?3:Ee>191?2:1;if(we+bt<=ae){let Lt,Ct,It,Tt;switch(bt){case 1:Ee<128&&(Le=Ee);break;case 2:Lt=le[we+1],(Lt&192)===128&&(Tt=(Ee&31)<<6|Lt&63,Tt>127&&(Le=Tt));break;case 3:Lt=le[we+1],Ct=le[we+2],(Lt&192)===128&&(Ct&192)===128&&(Tt=(Ee&15)<<12|(Lt&63)<<6|Ct&63,Tt>2047&&(Tt<55296||Tt>57343)&&(Le=Tt));break;case 4:Lt=le[we+1],Ct=le[we+2],It=le[we+3],(Lt&192)===128&&(Ct&192)===128&&(It&192)===128&&(Tt=(Ee&15)<<18|(Lt&63)<<12|(Ct&63)<<6|It&63,Tt>65535&&Tt<1114112&&(Le=Tt))}}Le===null?(Le=65533,bt=1):Le>65535&&(Le-=65536,he.push(Le>>>10&1023|55296),Le=56320|Le&1023),he.push(Le),we+=bt}return nt(he)}const Ve=4096;function nt(le){const re=le.length;if(re<=Ve)return String.fromCharCode.apply(String,le);let ae="",he=0;for(;he<re;)ae+=String.fromCharCode.apply(String,le.slice(he,he+=Ve));return ae}function ot(le,re,ae){let he="";ae=Math.min(le.length,ae);for(let we=re;we<ae;++we)he+=String.fromCharCode(le[we]&127);return he}function ft(le,re,ae){let he="";ae=Math.min(le.length,ae);for(let we=re;we<ae;++we)he+=String.fromCharCode(le[we]);return he}function it(le,re,ae){const he=le.length;(!re||re<0)&&(re=0),(!ae||ae<0||ae>he)&&(ae=he);let we="";for(let Ee=re;Ee<ae;++Ee)we+=nn[le[Ee]];return we}function ut(le,re,ae){const he=le.slice(re,ae);let we="";for(let Ee=0;Ee<he.length-1;Ee+=2)we+=String.fromCharCode(he[Ee]+he[Ee+1]*256);return we}J.prototype.slice=function(re,ae){const he=this.length;re=~~re,ae=ae===void 0?he:~~ae,re<0?(re+=he,re<0&&(re=0)):re>he&&(re=he),ae<0?(ae+=he,ae<0&&(ae=0)):ae>he&&(ae=he),ae<re&&(ae=re);const we=this.subarray(re,ae);return Object.setPrototypeOf(we,J.prototype),we};function et(le,re,ae){if(le%1!==0||le<0)throw new RangeError("offset is not uint");if(le+re>ae)throw new RangeError("Trying to access beyond buffer length")}J.prototype.readUintLE=J.prototype.readUIntLE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=this[re],Ee=1,Le=0;for(;++Le<ae&&(Ee*=256);)we+=this[re+Le]*Ee;return we},J.prototype.readUintBE=J.prototype.readUIntBE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=this[re+--ae],Ee=1;for(;ae>0&&(Ee*=256);)we+=this[re+--ae]*Ee;return we},J.prototype.readUint8=J.prototype.readUInt8=function(re,ae){return re=re>>>0,ae||et(re,1,this.length),this[re]},J.prototype.readUint16LE=J.prototype.readUInt16LE=function(re,ae){return re=re>>>0,ae||et(re,2,this.length),this[re]|this[re+1]<<8},J.prototype.readUint16BE=J.prototype.readUInt16BE=function(re,ae){return re=re>>>0,ae||et(re,2,this.length),this[re]<<8|this[re+1]},J.prototype.readUint32LE=J.prototype.readUInt32LE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),(this[re]|this[re+1]<<8|this[re+2]<<16)+this[re+3]*16777216},J.prototype.readUint32BE=J.prototype.readUInt32BE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),this[re]*16777216+(this[re+1]<<16|this[re+2]<<8|this[re+3])},J.prototype.readBigUInt64LE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=ae+this[++re]*2**8+this[++re]*2**16+this[++re]*2**24,Ee=this[++re]+this[++re]*2**8+this[++re]*2**16+he*2**24;return BigInt(we)+(BigInt(Ee)<<BigInt(32))}),J.prototype.readBigUInt64BE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=ae*2**24+this[++re]*2**16+this[++re]*2**8+this[++re],Ee=this[++re]*2**24+this[++re]*2**16+this[++re]*2**8+he;return(BigInt(we)<<BigInt(32))+BigInt(Ee)}),J.prototype.readIntLE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=this[re],Ee=1,Le=0;for(;++Le<ae&&(Ee*=256);)we+=this[re+Le]*Ee;return Ee*=128,we>=Ee&&(we-=Math.pow(2,8*ae)),we},J.prototype.readIntBE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=ae,Ee=1,Le=this[re+--we];for(;we>0&&(Ee*=256);)Le+=this[re+--we]*Ee;return Ee*=128,Le>=Ee&&(Le-=Math.pow(2,8*ae)),Le},J.prototype.readInt8=function(re,ae){return re=re>>>0,ae||et(re,1,this.length),this[re]&128?(255-this[re]+1)*-1:this[re]},J.prototype.readInt16LE=function(re,ae){re=re>>>0,ae||et(re,2,this.length);const he=this[re]|this[re+1]<<8;return he&32768?he|4294901760:he},J.prototype.readInt16BE=function(re,ae){re=re>>>0,ae||et(re,2,this.length);const he=this[re+1]|this[re]<<8;return he&32768?he|4294901760:he},J.prototype.readInt32LE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),this[re]|this[re+1]<<8|this[re+2]<<16|this[re+3]<<24},J.prototype.readInt32BE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),this[re]<<24|this[re+1]<<16|this[re+2]<<8|this[re+3]},J.prototype.readBigInt64LE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=this[re+4]+this[re+5]*2**8+this[re+6]*2**16+(he<<24);return(BigInt(we)<<BigInt(32))+BigInt(ae+this[++re]*2**8+this[++re]*2**16+this[++re]*2**24)}),J.prototype.readBigInt64BE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=(ae<<24)+this[++re]*2**16+this[++re]*2**8+this[++re];return(BigInt(we)<<BigInt(32))+BigInt(this[++re]*2**24+this[++re]*2**16+this[++re]*2**8+he)}),J.prototype.readFloatLE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),U.read(this,re,!0,23,4)},J.prototype.readFloatBE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),U.read(this,re,!1,23,4)},J.prototype.readDoubleLE=function(re,ae){return re=re>>>0,ae||et(re,8,this.length),U.read(this,re,!0,52,8)},J.prototype.readDoubleBE=function(re,ae){return re=re>>>0,ae||et(re,8,this.length),U.read(this,re,!1,52,8)};function Ue(le,re,ae,he,we,Ee){if(!J.isBuffer(le))throw new TypeError('"buffer" argument must be a Buffer instance');if(re>we||re<Ee)throw new RangeError('"value" argument is out of bounds');if(ae+he>le.length)throw new RangeError("Index out of range")}J.prototype.writeUintLE=J.prototype.writeUIntLE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,he=he>>>0,!we){const bt=Math.pow(2,8*he)-1;Ue(this,re,ae,he,bt,0)}let Ee=1,Le=0;for(this[ae]=re&255;++Le<he&&(Ee*=256);)this[ae+Le]=re/Ee&255;return ae+he},J.prototype.writeUintBE=J.prototype.writeUIntBE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,he=he>>>0,!we){const bt=Math.pow(2,8*he)-1;Ue(this,re,ae,he,bt,0)}let Ee=he-1,Le=1;for(this[ae+Ee]=re&255;--Ee>=0&&(Le*=256);)this[ae+Ee]=re/Le&255;return ae+he},J.prototype.writeUint8=J.prototype.writeUInt8=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,1,255,0),this[ae]=re&255,ae+1},J.prototype.writeUint16LE=J.prototype.writeUInt16LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,65535,0),this[ae]=re&255,this[ae+1]=re>>>8,ae+2},J.prototype.writeUint16BE=J.prototype.writeUInt16BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,65535,0),this[ae]=re>>>8,this[ae+1]=re&255,ae+2},J.prototype.writeUint32LE=J.prototype.writeUInt32LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,4294967295,0),this[ae+3]=re>>>24,this[ae+2]=re>>>16,this[ae+1]=re>>>8,this[ae]=re&255,ae+4},J.prototype.writeUint32BE=J.prototype.writeUInt32BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,4294967295,0),this[ae]=re>>>24,this[ae+1]=re>>>16,this[ae+2]=re>>>8,this[ae+3]=re&255,ae+4};function We(le,re,ae,he,we){_e(re,he,we,le,ae,7);let Ee=Number(re&BigInt(4294967295));le[ae++]=Ee,Ee=Ee>>8,le[ae++]=Ee,Ee=Ee>>8,le[ae++]=Ee,Ee=Ee>>8,le[ae++]=Ee;let Le=Number(re>>BigInt(32)&BigInt(4294967295));return le[ae++]=Le,Le=Le>>8,le[ae++]=Le,Le=Le>>8,le[ae++]=Le,Le=Le>>8,le[ae++]=Le,ae}function tt(le,re,ae,he,we){_e(re,he,we,le,ae,7);let Ee=Number(re&BigInt(4294967295));le[ae+7]=Ee,Ee=Ee>>8,le[ae+6]=Ee,Ee=Ee>>8,le[ae+5]=Ee,Ee=Ee>>8,le[ae+4]=Ee;let Le=Number(re>>BigInt(32)&BigInt(4294967295));return le[ae+3]=Le,Le=Le>>8,le[ae+2]=Le,Le=Le>>8,le[ae+1]=Le,Le=Le>>8,le[ae]=Le,ae+8}J.prototype.writeBigUInt64LE=St(function(re,ae=0){return We(this,re,ae,BigInt(0),BigInt("0xffffffffffffffff"))}),J.prototype.writeBigUInt64BE=St(function(re,ae=0){return tt(this,re,ae,BigInt(0),BigInt("0xffffffffffffffff"))}),J.prototype.writeIntLE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,!we){const Lt=Math.pow(2,8*he-1);Ue(this,re,ae,he,Lt-1,-Lt)}let Ee=0,Le=1,bt=0;for(this[ae]=re&255;++Ee<he&&(Le*=256);)re<0&&bt===0&&this[ae+Ee-1]!==0&&(bt=1),this[ae+Ee]=(re/Le>>0)-bt&255;return ae+he},J.prototype.writeIntBE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,!we){const Lt=Math.pow(2,8*he-1);Ue(this,re,ae,he,Lt-1,-Lt)}let Ee=he-1,Le=1,bt=0;for(this[ae+Ee]=re&255;--Ee>=0&&(Le*=256);)re<0&&bt===0&&this[ae+Ee+1]!==0&&(bt=1),this[ae+Ee]=(re/Le>>0)-bt&255;return ae+he},J.prototype.writeInt8=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,1,127,-128),re<0&&(re=255+re+1),this[ae]=re&255,ae+1},J.prototype.writeInt16LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,32767,-32768),this[ae]=re&255,this[ae+1]=re>>>8,ae+2},J.prototype.writeInt16BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,32767,-32768),this[ae]=re>>>8,this[ae+1]=re&255,ae+2},J.prototype.writeInt32LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,2147483647,-2147483648),this[ae]=re&255,this[ae+1]=re>>>8,this[ae+2]=re>>>16,this[ae+3]=re>>>24,ae+4},J.prototype.writeInt32BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,2147483647,-2147483648),re<0&&(re=4294967295+re+1),this[ae]=re>>>24,this[ae+1]=re>>>16,this[ae+2]=re>>>8,this[ae+3]=re&255,ae+4},J.prototype.writeBigInt64LE=St(function(re,ae=0){return We(this,re,ae,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),J.prototype.writeBigInt64BE=St(function(re,ae=0){return tt(this,re,ae,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function vt(le,re,ae,he,we,Ee){if(ae+he>le.length)throw new RangeError("Index out of range");if(ae<0)throw new RangeError("Index out of range")}function je(le,re,ae,he,we){return re=+re,ae=ae>>>0,we||vt(le,re,ae,4),U.write(le,re,ae,he,23,4),ae+4}J.prototype.writeFloatLE=function(re,ae,he){return je(this,re,ae,!0,he)},J.prototype.writeFloatBE=function(re,ae,he){return je(this,re,ae,!1,he)};function ze(le,re,ae,he,we){return re=+re,ae=ae>>>0,we||vt(le,re,ae,8),U.write(le,re,ae,he,52,8),ae+8}J.prototype.writeDoubleLE=function(re,ae,he){return ze(this,re,ae,!0,he)},J.prototype.writeDoubleBE=function(re,ae,he){return ze(this,re,ae,!1,he)},J.prototype.copy=function(re,ae,he,we){if(!J.isBuffer(re))throw new TypeError("argument should be a Buffer");if(he||(he=0),!we&&we!==0&&(we=this.length),ae>=re.length&&(ae=re.length),ae||(ae=0),we>0&&we<he&&(we=he),we===he||re.length===0||this.length===0)return 0;if(ae<0)throw new RangeError("targetStart out of bounds");if(he<0||he>=this.length)throw new RangeError("Index out of range");if(we<0)throw new RangeError("sourceEnd out of bounds");we>this.length&&(we=this.length),re.length-ae<we-he&&(we=re.length-ae+he);const Ee=we-he;return this===re&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(ae,he,we):Uint8Array.prototype.set.call(re,this.subarray(he,we),ae),Ee},J.prototype.fill=function(re,ae,he,we){if(typeof re=="string"){if(typeof ae=="string"?(we=ae,ae=0,he=this.length):typeof he=="string"&&(we=he,he=this.length),we!==void 0&&typeof we!="string")throw new TypeError("encoding must be a string");if(typeof we=="string"&&!J.isEncoding(we))throw new TypeError("Unknown encoding: "+we);if(re.length===1){const Le=re.charCodeAt(0);(we==="utf8"&&Le<128||we==="latin1")&&(re=Le)}}else typeof re=="number"?re=re&255:typeof re=="boolean"&&(re=Number(re));if(ae<0||this.length<ae||this.length<he)throw new RangeError("Out of range index");if(he<=ae)return this;ae=ae>>>0,he=he===void 0?this.length:he>>>0,re||(re=0);let Ee;if(typeof re=="number")for(Ee=ae;Ee<he;++Ee)this[Ee]=re;else{const Le=J.isBuffer(re)?re:J.from(re,we),bt=Le.length;if(bt===0)throw new TypeError('The value "'+re+'" is invalid for argument "value"');for(Ee=0;Ee<he-ae;++Ee)this[Ee+ae]=Le[Ee%bt]}return this};const Ae={};function Re(le,re,ae){Ae[le]=class extends ae{constructor(){super(),Object.defineProperty(this,"message",{value:re.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${le}]`,this.stack,delete this.name}get code(){return le}set code(we){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:we,writable:!0})}toString(){return`${this.name} [${le}]: ${this.message}`}}}Re("ERR_BUFFER_OUT_OF_BOUNDS",function(le){return le?`${le} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Re("ERR_INVALID_ARG_TYPE",function(le,re){return`The "${le}" argument must be of type number. Received type ${typeof re}`},TypeError),Re("ERR_OUT_OF_RANGE",function(le,re,ae){let he=`The value of "${le}" is out of range.`,we=ae;return Number.isInteger(ae)&&Math.abs(ae)>2**32?we=Ce(String(ae)):typeof ae=="bigint"&&(we=String(ae),(ae>BigInt(2)**BigInt(32)||ae<-(BigInt(2)**BigInt(32)))&&(we=Ce(we)),we+="n"),he+=` It must be ${re}. Received ${we}`,he},RangeError);function Ce(le){let re="",ae=le.length;const he=le[0]==="-"?1:0;for(;ae>=he+4;ae-=3)re=`_${le.slice(ae-3,ae)}${re}`;return`${le.slice(0,ae)}${re}`}function ge(le,re,ae){Me(re,"offset"),(le[re]===void 0||le[re+ae]===void 0)&&Ke(re,le.length-(ae+1))}function _e(le,re,ae,he,we,Ee){if(le>ae||le<re){const Le=typeof re=="bigint"?"n":"";let bt;throw Ee>3?re===0||re===BigInt(0)?bt=`>= 0${Le} and < 2${Le} ** ${(Ee+1)*8}${Le}`:bt=`>= -(2${Le} ** ${(Ee+1)*8-1}${Le}) and < 2 ** ${(Ee+1)*8-1}${Le}`:bt=`>= ${re}${Le} and <= ${ae}${Le}`,new Ae.ERR_OUT_OF_RANGE("value",bt,le)}ge(he,we,Ee)}function Me(le,re){if(typeof le!="number")throw new Ae.ERR_INVALID_ARG_TYPE(re,"number",le)}function Ke(le,re,ae){throw Math.floor(le)!==le?(Me(le,ae),new Ae.ERR_OUT_OF_RANGE(ae||"offset","an integer",le)):re<0?new Ae.ERR_BUFFER_OUT_OF_BOUNDS:new Ae.ERR_OUT_OF_RANGE(ae||"offset",`>= ${ae?1:0} and <= ${re}`,le)}const st=/[^+/0-9A-Za-z-_]/g;function dt(le){if(le=le.split("=")[0],le=le.trim().replace(st,""),le.length<2)return"";for(;le.length%4!==0;)le=le+"=";return le}function $t(le,re){re=re||1/0;let ae;const he=le.length;let we=null;const Ee=[];for(let Le=0;Le<he;++Le){if(ae=le.charCodeAt(Le),ae>55295&&ae<57344){if(!we){if(ae>56319){(re-=3)>-1&&Ee.push(239,191,189);continue}else if(Le+1===he){(re-=3)>-1&&Ee.push(239,191,189);continue}we=ae;continue}if(ae<56320){(re-=3)>-1&&Ee.push(239,191,189),we=ae;continue}ae=(we-55296<<10|ae-56320)+65536}else we&&(re-=3)>-1&&Ee.push(239,191,189);if(we=null,ae<128){if((re-=1)<0)break;Ee.push(ae)}else if(ae<2048){if((re-=2)<0)break;Ee.push(ae>>6|192,ae&63|128)}else if(ae<65536){if((re-=3)<0)break;Ee.push(ae>>12|224,ae>>6&63|128,ae&63|128)}else if(ae<1114112){if((re-=4)<0)break;Ee.push(ae>>18|240,ae>>12&63|128,ae>>6&63|128,ae&63|128)}else throw new Error("Invalid code point")}return Ee}function Et(le){const re=[];for(let ae=0;ae<le.length;++ae)re.push(le.charCodeAt(ae)&255);return re}function rt(le,re){let ae,he,we;const Ee=[];for(let Le=0;Le<le.length&&!((re-=2)<0);++Le)ae=le.charCodeAt(Le),he=ae>>8,we=ae%256,Ee.push(we),Ee.push(he);return Ee}function jt(le){return I.toByteArray(dt(le))}function Gt(le,re,ae,he){let we;for(we=0;we<he&&!(we+ae>=re.length||we>=le.length);++we)re[we+ae]=le[we];return we}function At(le,re){return le instanceof re||le!=null&&le.constructor!=null&&le.constructor.name!=null&&le.constructor.name===re.name}function zt(le){return le!==le}const nn=function(){const le="0123456789abcdef",re=new Array(256);for(let ae=0;ae<16;++ae){const he=ae*16;for(let we=0;we<16;++we)re[he+we]=le[ae]+le[we]}return re}();function St(le){return typeof BigInt>"u"?Ut:le}function Ut(){throw new Error("BigInt not supported")}})(buffer);const __viteBrowserExternal={},__viteBrowserExternal$1=Object.freeze(Object.defineProperty({__proto__:null,default:__viteBrowserExternal},Symbol.toStringTag,{value:"Module"})),require$$3=getAugmentedNamespace(__viteBrowserExternal$1);var buffer_list,hasRequiredBuffer_list;function requireBuffer_list(){if(hasRequiredBuffer_list)return buffer_list;hasRequiredBuffer_list=1;function $(te,ne){var ie=Object.keys(te);if(Object.getOwnPropertySymbols){var oe=Object.getOwnPropertySymbols(te);ne&&(oe=oe.filter(function(ce){return Object.getOwnPropertyDescriptor(te,ce).enumerable})),ie.push.apply(ie,oe)}return ie}function I(te){for(var ne=1;ne<arguments.length;ne++){var ie=arguments[ne]!=null?arguments[ne]:{};ne%2?$(Object(ie),!0).forEach(function(oe){U(te,oe,ie[oe])}):Object.getOwnPropertyDescriptors?Object.defineProperties(te,Object.getOwnPropertyDescriptors(ie)):$(Object(ie)).forEach(function(oe){Object.defineProperty(te,oe,Object.getOwnPropertyDescriptor(ie,oe))})}return te}function U(te,ne,ie){return ne in te?Object.defineProperty(te,ne,{value:ie,enumerable:!0,configurable:!0,writable:!0}):te[ne]=ie,te}function q(te,ne){if(!(te instanceof ne))throw new TypeError("Cannot call a class as a function")}function G(te,ne){for(var ie=0;ie<ne.length;ie++){var oe=ne[ie];oe.enumerable=oe.enumerable||!1,oe.configurable=!0,"value"in oe&&(oe.writable=!0),Object.defineProperty(te,oe.key,oe)}}function K(te,ne,ie){return ne&&G(te.prototype,ne),ie&&G(te,ie),te}var Y=buffer,J=Y.Buffer,X=require$$3,Z=X.inspect,Q=Z&&Z.custom||"inspect";function ee(te,ne,ie){J.prototype.copy.call(te,ne,ie)}return buffer_list=function(){function te(){q(this,te),this.head=null,this.tail=null,this.length=0}return K(te,[{key:"push",value:function(ie){var oe={data:ie,next:null};this.length>0?this.tail.next=oe:this.head=oe,this.tail=oe,++this.length}},{key:"unshift",value:function(ie){var oe={data:ie,next:this.head};this.length===0&&(this.tail=oe),this.head=oe,++this.length}},{key:"shift",value:function(){if(this.length!==0){var ie=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,ie}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(ie){if(this.length===0)return"";for(var oe=this.head,ce=""+oe.data;oe=oe.next;)ce+=ie+oe.data;return ce}},{key:"concat",value:function(ie){if(this.length===0)return J.alloc(0);for(var oe=J.allocUnsafe(ie>>>0),ce=this.head,fe=0;ce;)ee(ce.data,oe,fe),fe+=ce.data.length,ce=ce.next;return oe}},{key:"consume",value:function(ie,oe){var ce;return ie<this.head.data.length?(ce=this.head.data.slice(0,ie),this.head.data=this.head.data.slice(ie)):ie===this.head.data.length?ce=this.shift():ce=oe?this._getString(ie):this._getBuffer(ie),ce}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(ie){var oe=this.head,ce=1,fe=oe.data;for(ie-=fe.length;oe=oe.next;){var se=oe.data,de=ie>se.length?se.length:ie;if(de===se.length?fe+=se:fe+=se.slice(0,ie),ie-=de,ie===0){de===se.length?(++ce,oe.next?this.head=oe.next:this.head=this.tail=null):(this.head=oe,oe.data=se.slice(de));break}++ce}return this.length-=ce,fe}},{key:"_getBuffer",value:function(ie){var oe=J.allocUnsafe(ie),ce=this.head,fe=1;for(ce.data.copy(oe),ie-=ce.data.length;ce=ce.next;){var se=ce.data,de=ie>se.length?se.length:ie;if(se.copy(oe,oe.length-ie,0,de),ie-=de,ie===0){de===se.length?(++fe,ce.next?this.head=ce.next:this.head=this.tail=null):(this.head=ce,ce.data=se.slice(de));break}++fe}return this.length-=fe,oe}},{key:Q,value:function(ie,oe){return Z(this,I({},oe,{depth:0,customInspect:!1}))}}]),te}(),buffer_list}function destroy($,I){var U=this,q=this._readableState&&this._readableState.destroyed,G=this._writableState&&this._writableState.destroyed;return q||G?(I?I($):$&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,$)):process.nextTick(emitErrorNT,this,$)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy($||null,function(K){!I&&K?U._writableState?U._writableState.errorEmitted?process.nextTick(emitCloseNT,U):(U._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,U,K)):process.nextTick(emitErrorAndCloseNT,U,K):I?(process.nextTick(emitCloseNT,U),I(K)):process.nextTick(emitCloseNT,U)}),this)}function emitErrorAndCloseNT($,I){emitErrorNT($,I),emitCloseNT($)}function emitCloseNT($){$._writableState&&!$._writableState.emitClose||$._readableState&&!$._readableState.emitClose||$.emit("close")}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT($,I){$.emit("error",I)}function errorOrDestroy($,I){var U=$._readableState,q=$._writableState;U&&U.autoDestroy||q&&q.autoDestroy?$.destroy(I):$.emit("error",I)}var destroy_1={destroy,undestroy,errorOrDestroy},errorsBrowser={};function _inheritsLoose($,I){$.prototype=Object.create(I.prototype),$.prototype.constructor=$,$.__proto__=I}var codes={};function createErrorType($,I,U){U||(U=Error);function q(K,Y,J){return typeof I=="string"?I:I(K,Y,J)}var G=function(K){_inheritsLoose(Y,K);function Y(J,X,Z){return K.call(this,q(J,X,Z))||this}return Y}(U);G.prototype.name=U.name,G.prototype.code=$,codes[$]=G}function oneOf($,I){if(Array.isArray($)){var U=$.length;return $=$.map(function(q){return String(q)}),U>2?"one of ".concat(I," ").concat($.slice(0,U-1).join(", "),", or ")+$[U-1]:U===2?"one of ".concat(I," ").concat($[0]," or ").concat($[1]):"of ".concat(I," ").concat($[0])}else return"of ".concat(I," ").concat(String($))}function startsWith($,I,U){return $.substr(!U||U<0?0:+U,I.length)===I}function endsWith($,I,U){return(U===void 0||U>$.length)&&(U=$.length),$.substring(U-I.length,U)===I}function includes($,I,U){return typeof U!="number"&&(U=0),U+I.length>$.length?!1:$.indexOf(I,U)!==-1}createErrorType("ERR_INVALID_OPT_VALUE",function($,I){return'The value "'+I+'" is invalid for option "'+$+'"'},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function($,I,U){var q;typeof I=="string"&&startsWith(I,"not ")?(q="must not be",I=I.replace(/^not /,"")):q="must be";var G;if(endsWith($," argument"))G="The ".concat($," ").concat(q," ").concat(oneOf(I,"type"));else{var K=includes($,".")?"property":"argument";G='The "'.concat($,'" ').concat(K," ").concat(q," ").concat(oneOf(I,"type"))}return G+=". Received type ".concat(typeof U),G},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function($){return"The "+$+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function($){return"Cannot call "+$+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function($){return"Unknown encoding: "+$},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),errorsBrowser.codes=codes;var ERR_INVALID_OPT_VALUE=errorsBrowser.codes.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom($,I,U){return $.highWaterMark!=null?$.highWaterMark:I?$[U]:null}function getHighWaterMark($,I,U,q){var G=highWaterMarkFrom(I,q,U);if(G!=null){if(!(isFinite(G)&&Math.floor(G)===G)||G<0){var K=q?U:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(K,G)}return Math.floor(G)}return $.objectMode?16:16*1024}var state={getHighWaterMark},inherits_browser={exports:{}};typeof Object.create=="function"?inherits_browser.exports=function(I,U){U&&(I.super_=U,I.prototype=Object.create(U.prototype,{constructor:{value:I,enumerable:!1,writable:!0,configurable:!0}}))}:inherits_browser.exports=function(I,U){if(U){I.super_=U;var q=function(){};q.prototype=U.prototype,I.prototype=new q,I.prototype.constructor=I}};var inherits_browserExports=inherits_browser.exports,browser$4=deprecate;function deprecate($,I){if(config$1("noDeprecation"))return $;var U=!1;function q(){if(!U){if(config$1("throwDeprecation"))throw new Error(I);config$1("traceDeprecation")?console.trace(I):console.warn(I),U=!0}return $.apply(this,arguments)}return q}function config$1($){try{if(!commonjsGlobal.localStorage)return!1}catch{return!1}var I=commonjsGlobal.localStorage[$];return I==null?!1:String(I).toLowerCase()==="true"}var _stream_writable,hasRequired_stream_writable;function require_stream_writable(){if(hasRequired_stream_writable)return _stream_writable;hasRequired_stream_writable=1,_stream_writable=be;function $(je){var ze=this;this.next=null,this.entry=null,this.finish=function(){vt(ze,je)}}var I;be.WritableState=ve;var U={deprecate:browser$4},q=streamBrowser,G=buffer.Buffer,K=commonjsGlobal.Uint8Array||function(){};function Y(je){return G.from(je)}function J(je){return G.isBuffer(je)||je instanceof K}var X=destroy_1,Z=state,Q=Z.getHighWaterMark,ee=errorsBrowser.codes,te=ee.ERR_INVALID_ARG_TYPE,ne=ee.ERR_METHOD_NOT_IMPLEMENTED,ie=ee.ERR_MULTIPLE_CALLBACK,oe=ee.ERR_STREAM_CANNOT_PIPE,ce=ee.ERR_STREAM_DESTROYED,fe=ee.ERR_STREAM_NULL_VALUES,se=ee.ERR_STREAM_WRITE_AFTER_END,de=ee.ERR_UNKNOWN_ENCODING,ue=X.errorOrDestroy;inherits_browserExports(be,q);function pe(){}function ve(je,ze,Ae){I=I||require_stream_duplex(),je=je||{},typeof Ae!="boolean"&&(Ae=ze instanceof I),this.objectMode=!!je.objectMode,Ae&&(this.objectMode=this.objectMode||!!je.writableObjectMode),this.highWaterMark=Q(this,je,"writableHighWaterMark",Ae),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var Re=je.decodeStrings===!1;this.decodeStrings=!Re,this.defaultEncoding=je.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(Ce){nt(ze,Ce)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=je.emitClose!==!1,this.autoDestroy=!!je.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new $(this)}ve.prototype.getBuffer=function(){for(var ze=this.bufferedRequest,Ae=[];ze;)Ae.push(ze),ze=ze.next;return Ae},function(){try{Object.defineProperty(ve.prototype,"buffer",{get:U.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}}();var me;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(me=Function.prototype[Symbol.hasInstance],Object.defineProperty(be,Symbol.hasInstance,{value:function(ze){return me.call(this,ze)?!0:this!==be?!1:ze&&ze._writableState instanceof ve}})):me=function(ze){return ze instanceof this};function be(je){I=I||require_stream_duplex();var ze=this instanceof I;if(!ze&&!me.call(be,this))return new be(je);this._writableState=new ve(je,this,ze),this.writable=!0,je&&(typeof je.write=="function"&&(this._write=je.write),typeof je.writev=="function"&&(this._writev=je.writev),typeof je.destroy=="function"&&(this._destroy=je.destroy),typeof je.final=="function"&&(this._final=je.final)),q.call(this)}be.prototype.pipe=function(){ue(this,new oe)};function ye(je,ze){var Ae=new se;ue(je,Ae),process.nextTick(ze,Ae)}function Se(je,ze,Ae,Re){var Ce;return Ae===null?Ce=new fe:typeof Ae!="string"&&!ze.objectMode&&(Ce=new te("chunk",["string","Buffer"],Ae)),Ce?(ue(je,Ce),process.nextTick(Re,Ce),!1):!0}be.prototype.write=function(je,ze,Ae){var Re=this._writableState,Ce=!1,ge=!Re.objectMode&&J(je);return ge&&!G.isBuffer(je)&&(je=Y(je)),typeof ze=="function"&&(Ae=ze,ze=null),ge?ze="buffer":ze||(ze=Re.defaultEncoding),typeof Ae!="function"&&(Ae=pe),Re.ending?ye(this,Ae):(ge||Se(this,Re,je,Ae))&&(Re.pendingcb++,Ce=ke(this,Re,ge,je,ze,Ae)),Ce},be.prototype.cork=function(){this._writableState.corked++},be.prototype.uncork=function(){var je=this._writableState;je.corked&&(je.corked--,!je.writing&&!je.corked&&!je.bufferProcessing&&je.bufferedRequest&&it(this,je))},be.prototype.setDefaultEncoding=function(ze){if(typeof ze=="string"&&(ze=ze.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((ze+"").toLowerCase())>-1))throw new de(ze);return this._writableState.defaultEncoding=ze,this},Object.defineProperty(be.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function xe(je,ze,Ae){return!je.objectMode&&je.decodeStrings!==!1&&typeof ze=="string"&&(ze=G.from(ze,Ae)),ze}Object.defineProperty(be.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function ke(je,ze,Ae,Re,Ce,ge){if(!Ae){var _e=xe(ze,Re,Ce);Re!==_e&&(Ae=!0,Ce="buffer",Re=_e)}var Me=ze.objectMode?1:Re.length;ze.length+=Me;var Ke=ze.length<ze.highWaterMark;if(Ke||(ze.needDrain=!0),ze.writing||ze.corked){var st=ze.lastBufferedRequest;ze.lastBufferedRequest={chunk:Re,encoding:Ce,isBuf:Ae,callback:ge,next:null},st?st.next=ze.lastBufferedRequest:ze.bufferedRequest=ze.lastBufferedRequest,ze.bufferedRequestCount+=1}else De(je,ze,!1,Me,Re,Ce,ge);return Ke}function De(je,ze,Ae,Re,Ce,ge,_e){ze.writelen=Re,ze.writecb=_e,ze.writing=!0,ze.sync=!0,ze.destroyed?ze.onwrite(new ce("write")):Ae?je._writev(Ce,ze.onwrite):je._write(Ce,ge,ze.onwrite),ze.sync=!1}function Be(je,ze,Ae,Re,Ce){--ze.pendingcb,Ae?(process.nextTick(Ce,Re),process.nextTick(We,je,ze),je._writableState.errorEmitted=!0,ue(je,Re)):(Ce(Re),je._writableState.errorEmitted=!0,ue(je,Re),We(je,ze))}function Ve(je){je.writing=!1,je.writecb=null,je.length-=je.writelen,je.writelen=0}function nt(je,ze){var Ae=je._writableState,Re=Ae.sync,Ce=Ae.writecb;if(typeof Ce!="function")throw new ie;if(Ve(Ae),ze)Be(je,Ae,Re,ze,Ce);else{var ge=ut(Ae)||je.destroyed;!ge&&!Ae.corked&&!Ae.bufferProcessing&&Ae.bufferedRequest&&it(je,Ae),Re?process.nextTick(ot,je,Ae,ge,Ce):ot(je,Ae,ge,Ce)}}function ot(je,ze,Ae,Re){Ae||ft(je,ze),ze.pendingcb--,Re(),We(je,ze)}function ft(je,ze){ze.length===0&&ze.needDrain&&(ze.needDrain=!1,je.emit("drain"))}function it(je,ze){ze.bufferProcessing=!0;var Ae=ze.bufferedRequest;if(je._writev&&Ae&&Ae.next){var Re=ze.bufferedRequestCount,Ce=new Array(Re),ge=ze.corkedRequestsFree;ge.entry=Ae;for(var _e=0,Me=!0;Ae;)Ce[_e]=Ae,Ae.isBuf||(Me=!1),Ae=Ae.next,_e+=1;Ce.allBuffers=Me,De(je,ze,!0,ze.length,Ce,"",ge.finish),ze.pendingcb++,ze.lastBufferedRequest=null,ge.next?(ze.corkedRequestsFree=ge.next,ge.next=null):ze.corkedRequestsFree=new $(ze),ze.bufferedRequestCount=0}else{for(;Ae;){var Ke=Ae.chunk,st=Ae.encoding,dt=Ae.callback,$t=ze.objectMode?1:Ke.length;if(De(je,ze,!1,$t,Ke,st,dt),Ae=Ae.next,ze.bufferedRequestCount--,ze.writing)break}Ae===null&&(ze.lastBufferedRequest=null)}ze.bufferedRequest=Ae,ze.bufferProcessing=!1}be.prototype._write=function(je,ze,Ae){Ae(new ne("_write()"))},be.prototype._writev=null,be.prototype.end=function(je,ze,Ae){var Re=this._writableState;return typeof je=="function"?(Ae=je,je=null,ze=null):typeof ze=="function"&&(Ae=ze,ze=null),je!=null&&this.write(je,ze),Re.corked&&(Re.corked=1,this.uncork()),Re.ending||tt(this,Re,Ae),this},Object.defineProperty(be.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function ut(je){return je.ending&&je.length===0&&je.bufferedRequest===null&&!je.finished&&!je.writing}function et(je,ze){je._final(function(Ae){ze.pendingcb--,Ae&&ue(je,Ae),ze.prefinished=!0,je.emit("prefinish"),We(je,ze)})}function Ue(je,ze){!ze.prefinished&&!ze.finalCalled&&(typeof je._final=="function"&&!ze.destroyed?(ze.pendingcb++,ze.finalCalled=!0,process.nextTick(et,je,ze)):(ze.prefinished=!0,je.emit("prefinish")))}function We(je,ze){var Ae=ut(ze);if(Ae&&(Ue(je,ze),ze.pendingcb===0&&(ze.finished=!0,je.emit("finish"),ze.autoDestroy))){var Re=je._readableState;(!Re||Re.autoDestroy&&Re.endEmitted)&&je.destroy()}return Ae}function tt(je,ze,Ae){ze.ending=!0,We(je,ze),Ae&&(ze.finished?process.nextTick(Ae):je.once("finish",Ae)),ze.ended=!0,je.writable=!1}function vt(je,ze,Ae){var Re=je.entry;for(je.entry=null;Re;){var Ce=Re.callback;ze.pendingcb--,Ce(Ae),Re=Re.next}ze.corkedRequestsFree.next=je}return Object.defineProperty(be.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(ze){this._writableState&&(this._writableState.destroyed=ze)}}),be.prototype.destroy=X.destroy,be.prototype._undestroy=X.undestroy,be.prototype._destroy=function(je,ze){ze(je)},_stream_writable}var _stream_duplex,hasRequired_stream_duplex;function require_stream_duplex(){if(hasRequired_stream_duplex)return _stream_duplex;hasRequired_stream_duplex=1;var $=Object.keys||function(Z){var Q=[];for(var ee in Z)Q.push(ee);return Q};_stream_duplex=Y;var I=require_stream_readable(),U=require_stream_writable();inherits_browserExports(Y,I);for(var q=$(U.prototype),G=0;G<q.length;G++){var K=q[G];Y.prototype[K]||(Y.prototype[K]=U.prototype[K])}function Y(Z){if(!(this instanceof Y))return new Y(Z);I.call(this,Z),U.call(this,Z),this.allowHalfOpen=!0,Z&&(Z.readable===!1&&(this.readable=!1),Z.writable===!1&&(this.writable=!1),Z.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",J)))}Object.defineProperty(Y.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(Y.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Y.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function J(){this._writableState.ended||process.nextTick(X,this)}function X(Z){Z.end()}return Object.defineProperty(Y.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(Q){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=Q,this._writableState.destroyed=Q)}}),_stream_duplex}var string_decoder={},safeBuffer={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var hasRequiredSafeBuffer;function requireSafeBuffer(){return hasRequiredSafeBuffer||(hasRequiredSafeBuffer=1,function($,I){var U=buffer,q=U.Buffer;function G(Y,J){for(var X in Y)J[X]=Y[X]}q.from&&q.alloc&&q.allocUnsafe&&q.allocUnsafeSlow?$.exports=U:(G(U,I),I.Buffer=K);function K(Y,J,X){return q(Y,J,X)}K.prototype=Object.create(q.prototype),G(q,K),K.from=function(Y,J,X){if(typeof Y=="number")throw new TypeError("Argument must not be a number");return q(Y,J,X)},K.alloc=function(Y,J,X){if(typeof Y!="number")throw new TypeError("Argument must be a number");var Z=q(Y);return J!==void 0?typeof X=="string"?Z.fill(J,X):Z.fill(J):Z.fill(0),Z},K.allocUnsafe=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return q(Y)},K.allocUnsafeSlow=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return U.SlowBuffer(Y)}}(safeBuffer,safeBuffer.exports)),safeBuffer.exports}var hasRequiredString_decoder;function requireString_decoder(){if(hasRequiredString_decoder)return string_decoder;hasRequiredString_decoder=1;var $=requireSafeBuffer().Buffer,I=$.isEncoding||function(fe){switch(fe=""+fe,fe&&fe.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function U(fe){if(!fe)return"utf8";for(var se;;)switch(fe){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return fe;default:if(se)return;fe=(""+fe).toLowerCase(),se=!0}}function q(fe){var se=U(fe);if(typeof se!="string"&&($.isEncoding===I||!I(fe)))throw new Error("Unknown encoding: "+fe);return se||fe}string_decoder.StringDecoder=G;function G(fe){this.encoding=q(fe);var se;switch(this.encoding){case"utf16le":this.text=ee,this.end=te,se=4;break;case"utf8":this.fillLast=X,se=4;break;case"base64":this.text=ne,this.end=ie,se=3;break;default:this.write=oe,this.end=ce;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=$.allocUnsafe(se)}G.prototype.write=function(fe){if(fe.length===0)return"";var se,de;if(this.lastNeed){if(se=this.fillLast(fe),se===void 0)return"";de=this.lastNeed,this.lastNeed=0}else de=0;return de<fe.length?se?se+this.text(fe,de):this.text(fe,de):se||""},G.prototype.end=Q,G.prototype.text=Z,G.prototype.fillLast=function(fe){if(this.lastNeed<=fe.length)return fe.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);fe.copy(this.lastChar,this.lastTotal-this.lastNeed,0,fe.length),this.lastNeed-=fe.length};function K(fe){return fe<=127?0:fe>>5===6?2:fe>>4===14?3:fe>>3===30?4:fe>>6===2?-1:-2}function Y(fe,se,de){var ue=se.length-1;if(ue<de)return 0;var pe=K(se[ue]);return pe>=0?(pe>0&&(fe.lastNeed=pe-1),pe):--ue<de||pe===-2?0:(pe=K(se[ue]),pe>=0?(pe>0&&(fe.lastNeed=pe-2),pe):--ue<de||pe===-2?0:(pe=K(se[ue]),pe>=0?(pe>0&&(pe===2?pe=0:fe.lastNeed=pe-3),pe):0))}function J(fe,se,de){if((se[0]&192)!==128)return fe.lastNeed=0,"�";if(fe.lastNeed>1&&se.length>1){if((se[1]&192)!==128)return fe.lastNeed=1,"�";if(fe.lastNeed>2&&se.length>2&&(se[2]&192)!==128)return fe.lastNeed=2,"�"}}function X(fe){var se=this.lastTotal-this.lastNeed,de=J(this,fe);if(de!==void 0)return de;if(this.lastNeed<=fe.length)return fe.copy(this.lastChar,se,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);fe.copy(this.lastChar,se,0,fe.length),this.lastNeed-=fe.length}function Z(fe,se){var de=Y(this,fe,se);if(!this.lastNeed)return fe.toString("utf8",se);this.lastTotal=de;var ue=fe.length-(de-this.lastNeed);return fe.copy(this.lastChar,0,ue),fe.toString("utf8",se,ue)}function Q(fe){var se=fe&&fe.length?this.write(fe):"";return this.lastNeed?se+"�":se}function ee(fe,se){if((fe.length-se)%2===0){var de=fe.toString("utf16le",se);if(de){var ue=de.charCodeAt(de.length-1);if(ue>=55296&&ue<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=fe[fe.length-2],this.lastChar[1]=fe[fe.length-1],de.slice(0,-1)}return de}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=fe[fe.length-1],fe.toString("utf16le",se,fe.length-1)}function te(fe){var se=fe&&fe.length?this.write(fe):"";if(this.lastNeed){var de=this.lastTotal-this.lastNeed;return se+this.lastChar.toString("utf16le",0,de)}return se}function ne(fe,se){var de=(fe.length-se)%3;return de===0?fe.toString("base64",se):(this.lastNeed=3-de,this.lastTotal=3,de===1?this.lastChar[0]=fe[fe.length-1]:(this.lastChar[0]=fe[fe.length-2],this.lastChar[1]=fe[fe.length-1]),fe.toString("base64",se,fe.length-de))}function ie(fe){var se=fe&&fe.length?this.write(fe):"";return this.lastNeed?se+this.lastChar.toString("base64",0,3-this.lastNeed):se}function oe(fe){return fe.toString(this.encoding)}function ce(fe){return fe&&fe.length?this.write(fe):""}return string_decoder}var ERR_STREAM_PREMATURE_CLOSE=errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE;function once$1($){var I=!1;return function(){if(!I){I=!0;for(var U=arguments.length,q=new Array(U),G=0;G<U;G++)q[G]=arguments[G];$.apply(this,q)}}}function noop$2(){}function isRequest$1($){return $.setHeader&&typeof $.abort=="function"}function eos$1($,I,U){if(typeof I=="function")return eos$1($,null,I);I||(I={}),U=once$1(U||noop$2);var q=I.readable||I.readable!==!1&&$.readable,G=I.writable||I.writable!==!1&&$.writable,K=function(){$.writable||J()},Y=$._writableState&&$._writableState.finished,J=function(){G=!1,Y=!0,q||U.call($)},X=$._readableState&&$._readableState.endEmitted,Z=function(){q=!1,X=!0,G||U.call($)},Q=function(ie){U.call($,ie)},ee=function(){var ie;if(q&&!X)return(!$._readableState||!$._readableState.ended)&&(ie=new ERR_STREAM_PREMATURE_CLOSE),U.call($,ie);if(G&&!Y)return(!$._writableState||!$._writableState.ended)&&(ie=new ERR_STREAM_PREMATURE_CLOSE),U.call($,ie)},te=function(){$.req.on("finish",J)};return isRequest$1($)?($.on("complete",J),$.on("abort",ee),$.req?te():$.on("request",te)):G&&!$._writableState&&($.on("end",K),$.on("close",K)),$.on("end",Z),$.on("finish",J),I.error!==!1&&$.on("error",Q),$.on("close",ee),function(){$.removeListener("complete",J),$.removeListener("abort",ee),$.removeListener("request",te),$.req&&$.req.removeListener("finish",J),$.removeListener("end",K),$.removeListener("close",K),$.removeListener("finish",J),$.removeListener("end",Z),$.removeListener("error",Q),$.removeListener("close",ee)}}var endOfStream=eos$1,async_iterator,hasRequiredAsync_iterator;function requireAsync_iterator(){if(hasRequiredAsync_iterator)return async_iterator;hasRequiredAsync_iterator=1;var $;function I(fe,se,de){return se in fe?Object.defineProperty(fe,se,{value:de,enumerable:!0,configurable:!0,writable:!0}):fe[se]=de,fe}var U=endOfStream,q=Symbol("lastResolve"),G=Symbol("lastReject"),K=Symbol("error"),Y=Symbol("ended"),J=Symbol("lastPromise"),X=Symbol("handlePromise"),Z=Symbol("stream");function Q(fe,se){return{value:fe,done:se}}function ee(fe){var se=fe[q];if(se!==null){var de=fe[Z].read();de!==null&&(fe[J]=null,fe[q]=null,fe[G]=null,se(Q(de,!1)))}}function te(fe){process.nextTick(ee,fe)}function ne(fe,se){return function(de,ue){fe.then(function(){if(se[Y]){de(Q(void 0,!0));return}se[X](de,ue)},ue)}}var ie=Object.getPrototypeOf(function(){}),oe=Object.setPrototypeOf(($={get stream(){return this[Z]},next:function(){var se=this,de=this[K];if(de!==null)return Promise.reject(de);if(this[Y])return Promise.resolve(Q(void 0,!0));if(this[Z].destroyed)return new Promise(function(me,be){process.nextTick(function(){se[K]?be(se[K]):me(Q(void 0,!0))})});var ue=this[J],pe;if(ue)pe=new Promise(ne(ue,this));else{var ve=this[Z].read();if(ve!==null)return Promise.resolve(Q(ve,!1));pe=new Promise(this[X])}return this[J]=pe,pe}},I($,Symbol.asyncIterator,function(){return this}),I($,"return",function(){var se=this;return new Promise(function(de,ue){se[Z].destroy(null,function(pe){if(pe){ue(pe);return}de(Q(void 0,!0))})})}),$),ie),ce=function(se){var de,ue=Object.create(oe,(de={},I(de,Z,{value:se,writable:!0}),I(de,q,{value:null,writable:!0}),I(de,G,{value:null,writable:!0}),I(de,K,{value:null,writable:!0}),I(de,Y,{value:se._readableState.endEmitted,writable:!0}),I(de,X,{value:function(ve,me){var be=ue[Z].read();be?(ue[J]=null,ue[q]=null,ue[G]=null,ve(Q(be,!1))):(ue[q]=ve,ue[G]=me)},writable:!0}),de));return ue[J]=null,U(se,function(pe){if(pe&&pe.code!=="ERR_STREAM_PREMATURE_CLOSE"){var ve=ue[G];ve!==null&&(ue[J]=null,ue[q]=null,ue[G]=null,ve(pe)),ue[K]=pe;return}var me=ue[q];me!==null&&(ue[J]=null,ue[q]=null,ue[G]=null,me(Q(void 0,!0))),ue[Y]=!0}),se.on("readable",te.bind(null,ue)),ue};return async_iterator=ce,async_iterator}var fromBrowser,hasRequiredFromBrowser;function requireFromBrowser(){return hasRequiredFromBrowser||(hasRequiredFromBrowser=1,fromBrowser=function(){throw new Error("Readable.from is not available in the browser")}),fromBrowser}var _stream_readable,hasRequired_stream_readable;function require_stream_readable(){if(hasRequired_stream_readable)return _stream_readable;hasRequired_stream_readable=1,_stream_readable=ye;var $;ye.ReadableState=be,eventsExports.EventEmitter;var I=function(_e,Me){return _e.listeners(Me).length},U=streamBrowser,q=buffer.Buffer,G=commonjsGlobal.Uint8Array||function(){};function K(ge){return q.from(ge)}function Y(ge){return q.isBuffer(ge)||ge instanceof G}var J=require$$3,X;J&&J.debuglog?X=J.debuglog("stream"):X=function(){};var Z=requireBuffer_list(),Q=destroy_1,ee=state,te=ee.getHighWaterMark,ne=errorsBrowser.codes,ie=ne.ERR_INVALID_ARG_TYPE,oe=ne.ERR_STREAM_PUSH_AFTER_EOF,ce=ne.ERR_METHOD_NOT_IMPLEMENTED,fe=ne.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,se,de,ue;inherits_browserExports(ye,U);var pe=Q.errorOrDestroy,ve=["error","close","destroy","pause","resume"];function me(ge,_e,Me){if(typeof ge.prependListener=="function")return ge.prependListener(_e,Me);!ge._events||!ge._events[_e]?ge.on(_e,Me):Array.isArray(ge._events[_e])?ge._events[_e].unshift(Me):ge._events[_e]=[Me,ge._events[_e]]}function be(ge,_e,Me){$=$||require_stream_duplex(),ge=ge||{},typeof Me!="boolean"&&(Me=_e instanceof $),this.objectMode=!!ge.objectMode,Me&&(this.objectMode=this.objectMode||!!ge.readableObjectMode),this.highWaterMark=te(this,ge,"readableHighWaterMark",Me),this.buffer=new Z,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=ge.emitClose!==!1,this.autoDestroy=!!ge.autoDestroy,this.destroyed=!1,this.defaultEncoding=ge.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,ge.encoding&&(se||(se=requireString_decoder().StringDecoder),this.decoder=new se(ge.encoding),this.encoding=ge.encoding)}function ye(ge){if($=$||require_stream_duplex(),!(this instanceof ye))return new ye(ge);var _e=this instanceof $;this._readableState=new be(ge,this,_e),this.readable=!0,ge&&(typeof ge.read=="function"&&(this._read=ge.read),typeof ge.destroy=="function"&&(this._destroy=ge.destroy)),U.call(this)}Object.defineProperty(ye.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(_e){this._readableState&&(this._readableState.destroyed=_e)}}),ye.prototype.destroy=Q.destroy,ye.prototype._undestroy=Q.undestroy,ye.prototype._destroy=function(ge,_e){_e(ge)},ye.prototype.push=function(ge,_e){var Me=this._readableState,Ke;return Me.objectMode?Ke=!0:typeof ge=="string"&&(_e=_e||Me.defaultEncoding,_e!==Me.encoding&&(ge=q.from(ge,_e),_e=""),Ke=!0),Se(this,ge,_e,!1,Ke)},ye.prototype.unshift=function(ge){return Se(this,ge,null,!0,!1)};function Se(ge,_e,Me,Ke,st){X("readableAddChunk",_e);var dt=ge._readableState;if(_e===null)dt.reading=!1,nt(ge,dt);else{var $t;if(st||($t=ke(dt,_e)),$t)pe(ge,$t);else if(dt.objectMode||_e&&_e.length>0)if(typeof _e!="string"&&!dt.objectMode&&Object.getPrototypeOf(_e)!==q.prototype&&(_e=K(_e)),Ke)dt.endEmitted?pe(ge,new fe):xe(ge,dt,_e,!0);else if(dt.ended)pe(ge,new oe);else{if(dt.destroyed)return!1;dt.reading=!1,dt.decoder&&!Me?(_e=dt.decoder.write(_e),dt.objectMode||_e.length!==0?xe(ge,dt,_e,!1):it(ge,dt)):xe(ge,dt,_e,!1)}else Ke||(dt.reading=!1,it(ge,dt))}return!dt.ended&&(dt.length<dt.highWaterMark||dt.length===0)}function xe(ge,_e,Me,Ke){_e.flowing&&_e.length===0&&!_e.sync?(_e.awaitDrain=0,ge.emit("data",Me)):(_e.length+=_e.objectMode?1:Me.length,Ke?_e.buffer.unshift(Me):_e.buffer.push(Me),_e.needReadable&&ot(ge)),it(ge,_e)}function ke(ge,_e){var Me;return!Y(_e)&&typeof _e!="string"&&_e!==void 0&&!ge.objectMode&&(Me=new ie("chunk",["string","Buffer","Uint8Array"],_e)),Me}ye.prototype.isPaused=function(){return this._readableState.flowing===!1},ye.prototype.setEncoding=function(ge){se||(se=requireString_decoder().StringDecoder);var _e=new se(ge);this._readableState.decoder=_e,this._readableState.encoding=this._readableState.decoder.encoding;for(var Me=this._readableState.buffer.head,Ke="";Me!==null;)Ke+=_e.write(Me.data),Me=Me.next;return this._readableState.buffer.clear(),Ke!==""&&this._readableState.buffer.push(Ke),this._readableState.length=Ke.length,this};var De=1073741824;function Be(ge){return ge>=De?ge=De:(ge--,ge|=ge>>>1,ge|=ge>>>2,ge|=ge>>>4,ge|=ge>>>8,ge|=ge>>>16,ge++),ge}function Ve(ge,_e){return ge<=0||_e.length===0&&_e.ended?0:_e.objectMode?1:ge!==ge?_e.flowing&&_e.length?_e.buffer.head.data.length:_e.length:(ge>_e.highWaterMark&&(_e.highWaterMark=Be(ge)),ge<=_e.length?ge:_e.ended?_e.length:(_e.needReadable=!0,0))}ye.prototype.read=function(ge){X("read",ge),ge=parseInt(ge,10);var _e=this._readableState,Me=ge;if(ge!==0&&(_e.emittedReadable=!1),ge===0&&_e.needReadable&&((_e.highWaterMark!==0?_e.length>=_e.highWaterMark:_e.length>0)||_e.ended))return X("read: emitReadable",_e.length,_e.ended),_e.length===0&&_e.ended?Ae(this):ot(this),null;if(ge=Ve(ge,_e),ge===0&&_e.ended)return _e.length===0&&Ae(this),null;var Ke=_e.needReadable;X("need readable",Ke),(_e.length===0||_e.length-ge<_e.highWaterMark)&&(Ke=!0,X("length less than watermark",Ke)),_e.ended||_e.reading?(Ke=!1,X("reading or ended",Ke)):Ke&&(X("do read"),_e.reading=!0,_e.sync=!0,_e.length===0&&(_e.needReadable=!0),this._read(_e.highWaterMark),_e.sync=!1,_e.reading||(ge=Ve(Me,_e)));var st;return ge>0?st=ze(ge,_e):st=null,st===null?(_e.needReadable=_e.length<=_e.highWaterMark,ge=0):(_e.length-=ge,_e.awaitDrain=0),_e.length===0&&(_e.ended||(_e.needReadable=!0),Me!==ge&&_e.ended&&Ae(this)),st!==null&&this.emit("data",st),st};function nt(ge,_e){if(X("onEofChunk"),!_e.ended){if(_e.decoder){var Me=_e.decoder.end();Me&&Me.length&&(_e.buffer.push(Me),_e.length+=_e.objectMode?1:Me.length)}_e.ended=!0,_e.sync?ot(ge):(_e.needReadable=!1,_e.emittedReadable||(_e.emittedReadable=!0,ft(ge)))}}function ot(ge){var _e=ge._readableState;X("emitReadable",_e.needReadable,_e.emittedReadable),_e.needReadable=!1,_e.emittedReadable||(X("emitReadable",_e.flowing),_e.emittedReadable=!0,process.nextTick(ft,ge))}function ft(ge){var _e=ge._readableState;X("emitReadable_",_e.destroyed,_e.length,_e.ended),!_e.destroyed&&(_e.length||_e.ended)&&(ge.emit("readable"),_e.emittedReadable=!1),_e.needReadable=!_e.flowing&&!_e.ended&&_e.length<=_e.highWaterMark,je(ge)}function it(ge,_e){_e.readingMore||(_e.readingMore=!0,process.nextTick(ut,ge,_e))}function ut(ge,_e){for(;!_e.reading&&!_e.ended&&(_e.length<_e.highWaterMark||_e.flowing&&_e.length===0);){var Me=_e.length;if(X("maybeReadMore read 0"),ge.read(0),Me===_e.length)break}_e.readingMore=!1}ye.prototype._read=function(ge){pe(this,new ce("_read()"))},ye.prototype.pipe=function(ge,_e){var Me=this,Ke=this._readableState;switch(Ke.pipesCount){case 0:Ke.pipes=ge;break;case 1:Ke.pipes=[Ke.pipes,ge];break;default:Ke.pipes.push(ge);break}Ke.pipesCount+=1,X("pipe count=%d opts=%j",Ke.pipesCount,_e);var st=(!_e||_e.end!==!1)&&ge!==process.stdout&&ge!==process.stderr,dt=st?Et:Ut;Ke.endEmitted?process.nextTick(dt):Me.once("end",dt),ge.on("unpipe",$t);function $t(le,re){X("onunpipe"),le===Me&&re&&re.hasUnpiped===!1&&(re.hasUnpiped=!0,Gt())}function Et(){X("onend"),ge.end()}var rt=et(Me);ge.on("drain",rt);var jt=!1;function Gt(){X("cleanup"),ge.removeListener("close",nn),ge.removeListener("finish",St),ge.removeListener("drain",rt),ge.removeListener("error",zt),ge.removeListener("unpipe",$t),Me.removeListener("end",Et),Me.removeListener("end",Ut),Me.removeListener("data",At),jt=!0,Ke.awaitDrain&&(!ge._writableState||ge._writableState.needDrain)&&rt()}Me.on("data",At);function At(le){X("ondata");var re=ge.write(le);X("dest.write",re),re===!1&&((Ke.pipesCount===1&&Ke.pipes===ge||Ke.pipesCount>1&&Ce(Ke.pipes,ge)!==-1)&&!jt&&(X("false write response, pause",Ke.awaitDrain),Ke.awaitDrain++),Me.pause())}function zt(le){X("onerror",le),Ut(),ge.removeListener("error",zt),I(ge,"error")===0&&pe(ge,le)}me(ge,"error",zt);function nn(){ge.removeListener("finish",St),Ut()}ge.once("close",nn);function St(){X("onfinish"),ge.removeListener("close",nn),Ut()}ge.once("finish",St);function Ut(){X("unpipe"),Me.unpipe(ge)}return ge.emit("pipe",Me),Ke.flowing||(X("pipe resume"),Me.resume()),ge};function et(ge){return function(){var Me=ge._readableState;X("pipeOnDrain",Me.awaitDrain),Me.awaitDrain&&Me.awaitDrain--,Me.awaitDrain===0&&I(ge,"data")&&(Me.flowing=!0,je(ge))}}ye.prototype.unpipe=function(ge){var _e=this._readableState,Me={hasUnpiped:!1};if(_e.pipesCount===0)return this;if(_e.pipesCount===1)return ge&&ge!==_e.pipes?this:(ge||(ge=_e.pipes),_e.pipes=null,_e.pipesCount=0,_e.flowing=!1,ge&&ge.emit("unpipe",this,Me),this);if(!ge){var Ke=_e.pipes,st=_e.pipesCount;_e.pipes=null,_e.pipesCount=0,_e.flowing=!1;for(var dt=0;dt<st;dt++)Ke[dt].emit("unpipe",this,{hasUnpiped:!1});return this}var $t=Ce(_e.pipes,ge);return $t===-1?this:(_e.pipes.splice($t,1),_e.pipesCount-=1,_e.pipesCount===1&&(_e.pipes=_e.pipes[0]),ge.emit("unpipe",this,Me),this)},ye.prototype.on=function(ge,_e){var Me=U.prototype.on.call(this,ge,_e),Ke=this._readableState;return ge==="data"?(Ke.readableListening=this.listenerCount("readable")>0,Ke.flowing!==!1&&this.resume()):ge==="readable"&&!Ke.endEmitted&&!Ke.readableListening&&(Ke.readableListening=Ke.needReadable=!0,Ke.flowing=!1,Ke.emittedReadable=!1,X("on readable",Ke.length,Ke.reading),Ke.length?ot(this):Ke.reading||process.nextTick(We,this)),Me},ye.prototype.addListener=ye.prototype.on,ye.prototype.removeListener=function(ge,_e){var Me=U.prototype.removeListener.call(this,ge,_e);return ge==="readable"&&process.nextTick(Ue,this),Me},ye.prototype.removeAllListeners=function(ge){var _e=U.prototype.removeAllListeners.apply(this,arguments);return(ge==="readable"||ge===void 0)&&process.nextTick(Ue,this),_e};function Ue(ge){var _e=ge._readableState;_e.readableListening=ge.listenerCount("readable")>0,_e.resumeScheduled&&!_e.paused?_e.flowing=!0:ge.listenerCount("data")>0&&ge.resume()}function We(ge){X("readable nexttick read 0"),ge.read(0)}ye.prototype.resume=function(){var ge=this._readableState;return ge.flowing||(X("resume"),ge.flowing=!ge.readableListening,tt(this,ge)),ge.paused=!1,this};function tt(ge,_e){_e.resumeScheduled||(_e.resumeScheduled=!0,process.nextTick(vt,ge,_e))}function vt(ge,_e){X("resume",_e.reading),_e.reading||ge.read(0),_e.resumeScheduled=!1,ge.emit("resume"),je(ge),_e.flowing&&!_e.reading&&ge.read(0)}ye.prototype.pause=function(){return X("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(X("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function je(ge){var _e=ge._readableState;for(X("flow",_e.flowing);_e.flowing&&ge.read()!==null;);}ye.prototype.wrap=function(ge){var _e=this,Me=this._readableState,Ke=!1;ge.on("end",function(){if(X("wrapped end"),Me.decoder&&!Me.ended){var $t=Me.decoder.end();$t&&$t.length&&_e.push($t)}_e.push(null)}),ge.on("data",function($t){if(X("wrapped data"),Me.decoder&&($t=Me.decoder.write($t)),!(Me.objectMode&&$t==null)&&!(!Me.objectMode&&(!$t||!$t.length))){var Et=_e.push($t);Et||(Ke=!0,ge.pause())}});for(var st in ge)this[st]===void 0&&typeof ge[st]=="function"&&(this[st]=function(Et){return function(){return ge[Et].apply(ge,arguments)}}(st));for(var dt=0;dt<ve.length;dt++)ge.on(ve[dt],this.emit.bind(this,ve[dt]));return this._read=function($t){X("wrapped _read",$t),Ke&&(Ke=!1,ge.resume())},this},typeof Symbol=="function"&&(ye.prototype[Symbol.asyncIterator]=function(){return de===void 0&&(de=requireAsync_iterator()),de(this)}),Object.defineProperty(ye.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(ye.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(ye.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(_e){this._readableState&&(this._readableState.flowing=_e)}}),ye._fromList=ze,Object.defineProperty(ye.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function ze(ge,_e){if(_e.length===0)return null;var Me;return _e.objectMode?Me=_e.buffer.shift():!ge||ge>=_e.length?(_e.decoder?Me=_e.buffer.join(""):_e.buffer.length===1?Me=_e.buffer.first():Me=_e.buffer.concat(_e.length),_e.buffer.clear()):Me=_e.buffer.consume(ge,_e.decoder),Me}function Ae(ge){var _e=ge._readableState;X("endReadable",_e.endEmitted),_e.endEmitted||(_e.ended=!0,process.nextTick(Re,_e,ge))}function Re(ge,_e){if(X("endReadableNT",ge.endEmitted,ge.length),!ge.endEmitted&&ge.length===0&&(ge.endEmitted=!0,_e.readable=!1,_e.emit("end"),ge.autoDestroy)){var Me=_e._writableState;(!Me||Me.autoDestroy&&Me.finished)&&_e.destroy()}}typeof Symbol=="function"&&(ye.from=function(ge,_e){return ue===void 0&&(ue=requireFromBrowser()),ue(ye,ge,_e)});function Ce(ge,_e){for(var Me=0,Ke=ge.length;Me<Ke;Me++)if(ge[Me]===_e)return Me;return-1}return _stream_readable}var _stream_transform=Transform$1,_require$codes$1=errorsBrowser.codes,ERR_METHOD_NOT_IMPLEMENTED=_require$codes$1.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes$1.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0,Duplex=require_stream_duplex();inherits_browserExports(Transform$1,Duplex);function afterTransform($,I){var U=this._transformState;U.transforming=!1;var q=U.writecb;if(q===null)return this.emit("error",new ERR_MULTIPLE_CALLBACK);U.writechunk=null,U.writecb=null,I!=null&&this.push(I),q($);var G=this._readableState;G.reading=!1,(G.needReadable||G.length<G.highWaterMark)&&this._read(G.highWaterMark)}function Transform$1($){if(!(this instanceof Transform$1))return new Transform$1($);Duplex.call(this,$),this._transformState={afterTransform:afterTransform.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,$&&(typeof $.transform=="function"&&(this._transform=$.transform),typeof $.flush=="function"&&(this._flush=$.flush)),this.on("prefinish",prefinish)}function prefinish(){var $=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(I,U){done$1($,I,U)}):done$1(this,null,null)}Transform$1.prototype.push=function($,I){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,$,I)},Transform$1.prototype._transform=function($,I,U){U(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"))},Transform$1.prototype._write=function($,I,U){var q=this._transformState;if(q.writecb=U,q.writechunk=$,q.writeencoding=I,!q.transforming){var G=this._readableState;(q.needTransform||G.needReadable||G.length<G.highWaterMark)&&this._read(G.highWaterMark)}},Transform$1.prototype._read=function($){var I=this._transformState;I.writechunk!==null&&!I.transforming?(I.transforming=!0,this._transform(I.writechunk,I.writeencoding,I.afterTransform)):I.needTransform=!0},Transform$1.prototype._destroy=function($,I){Duplex.prototype._destroy.call(this,$,function(U){I(U)})};function done$1($,I,U){if(I)return $.emit("error",I);if(U!=null&&$.push(U),$._writableState.length)throw new ERR_TRANSFORM_WITH_LENGTH_0;if($._transformState.transforming)throw new ERR_TRANSFORM_ALREADY_TRANSFORMING;return $.push(null)}var _stream_passthrough=PassThrough,Transform=_stream_transform;inherits_browserExports(PassThrough,Transform);function PassThrough($){if(!(this instanceof PassThrough))return new PassThrough($);Transform.call(this,$)}PassThrough.prototype._transform=function($,I,U){U(null,$)};var eos;function once($){var I=!1;return function(){I||(I=!0,$.apply(void 0,arguments))}}var _require$codes=errorsBrowser.codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED;function noop$1($){if($)throw $}function isRequest($){return $.setHeader&&typeof $.abort=="function"}function destroyer($,I,U,q){q=once(q);var G=!1;$.on("close",function(){G=!0}),eos===void 0&&(eos=endOfStream),eos($,{readable:I,writable:U},function(Y){if(Y)return q(Y);G=!0,q()});var K=!1;return function(Y){if(!G&&!K){if(K=!0,isRequest($))return $.abort();if(typeof $.destroy=="function")return $.destroy();q(Y||new ERR_STREAM_DESTROYED("pipe"))}}}function call($){$()}function pipe($,I){return $.pipe(I)}function popCallback($){return!$.length||typeof $[$.length-1]!="function"?noop$1:$.pop()}function pipeline(){for(var $=arguments.length,I=new Array($),U=0;U<$;U++)I[U]=arguments[U];var q=popCallback(I);if(Array.isArray(I[0])&&(I=I[0]),I.length<2)throw new ERR_MISSING_ARGS("streams");var G,K=I.map(function(Y,J){var X=J<I.length-1,Z=J>0;return destroyer(Y,X,Z,function(Q){G||(G=Q),Q&&K.forEach(call),!X&&(K.forEach(call),q(G))})});return I.reduce(pipe)}var pipeline_1=pipeline;(function($,I){I=$.exports=require_stream_readable(),I.Stream=I,I.Readable=I,I.Writable=require_stream_writable(),I.Duplex=require_stream_duplex(),I.Transform=_stream_transform,I.PassThrough=_stream_passthrough,I.finished=endOfStream,I.pipeline=pipeline_1})(readableBrowser,readableBrowser.exports);var readableBrowserExports=readableBrowser.exports,createPromiseFromCallback=$=>new Promise((I,U)=>{$((q,G)=>{q?U(q):I(G)})}),TimeoutError=class extends Error{constructor($,I){super($?`Timeout [${$.toLocaleString()}ms]${I===void 0?"":`: ${I}`}`:"Timeout")}},sleep=$=>new Promise(I=>{const U=Date.now()+$,q=()=>{const G=U-Date.now();G>0?setTimeout(q,G):I()};q()}),asyncTimeout=async($,I,U)=>{let q;const G=U===void 0||typeof U=="string"?new TimeoutError(I,U):U,K=new Promise((J,X)=>{q=setTimeout(()=>{X(G)},I),unrefTimeout(q)}),Y=typeof $=="function"?createPromiseFromCallback($):$;return await Promise.race([Y,K]).finally(()=>{clearTimeout(q)})},unrefTimeout=$=>{typeof $=="object"&&"unref"in $&&$.unref()},Event$1=class hr{constructor(){this._listeners=new Set,this._effects=new Set}static wrap(I,U){const q=new hr;return q.addEffect(()=>{const G=K=>q.emit(K);return I.on(U,G),()=>I.off(U,G)}),q}emit(I){for(const U of this._listeners)U.trigger(I),U.once&&this._listeners.delete(U)}on(I,U,q){const[G,K]=I instanceof Context?[I,U]:[new Context,I],Y=!!(q!=null&&q.weak),J=!!(q!=null&&q.once),X=new EventListener(this,K,G,J,Y);return this._addListener(X),()=>{this._removeListener(X)}}off(I){for(const U of this._listeners)U.derefCallback()===I&&this._removeListener(U)}once(I,U){const[q,G]=I instanceof Context?[I,U]:[new Context,I],K=new EventListener(this,G,q,!0,!1);return this._addListener(K),()=>{this._removeListener(K)}}async*[Symbol.asyncIterator](){for(;;)yield await new Promise(I=>{this.once(I)})}waitFor(I){return new Promise(U=>{const q=this.on(G=>{I(G)&&(q(),U(G))})})}waitForCount(I){let U=0;return this.waitFor(()=>++U===I)}async waitForCondition(I){I()||await this.waitFor(I)}listenerCount(){return this._listeners.size}addEffect(I){const U={effect:I,cleanup:void 0};return this.listenerCount()>0&&(U.cleanup=U.effect()),this._effects.add(U),()=>{var q;(q=U.cleanup)==null||q.call(U),this._effects.delete(U)}}debounce(I=0){let U,q;const G=new hr;return G.addEffect(()=>{const K=this.on(()=>{if(!U){const Y=!q||Date.now()-q>I?I/8:I;U=setTimeout(()=>{q=Date.now(),U=void 0,G.emit()},Y)}});return()=>{K(),clearTimeout(U)}}),G}discardParameter(){return this}toJSON(){return{listenerCount:this.listenerCount()}}_addListener(I){this._listeners.add(I),this.listenerCount()===1&&this._runEffects()}_removeListener(I){this._listeners.delete(I),I.remove(),this.listenerCount()===0&&this._cleanupEffects()}_runEffects(){for(const I of this._effects)I.cleanup=I.effect()}_cleanupEffects(){var I;for(const U of this._effects)(I=U.cleanup)==null||I.call(U),U.cleanup=void 0}},EventListener=class{constructor($,I,U,q,G){this.ctx=U,this.once=q,this.weak=G,this._clearDispose=void 0,this._clearDispose=U.onDispose(()=>{$._removeListener(this)}),G?(this.callback=new WeakRef(I),weakListeners().registry.register(I,{event:new WeakRef($),listener:this},this)):this.callback=I}derefCallback(){return this.weak?this.callback.deref():this.callback}async trigger($){try{const I=this.derefCallback();await(I==null?void 0:I($))}catch(I){this.ctx.raise(I)}}remove(){var $;($=this._clearDispose)==null||$.call(this),weakListeners().registry.unregister(this)}},weakListenersState=null,weakListeners=()=>(weakListenersState??(weakListenersState=new FinalizationRegistry(({event:$,listener:I})=>{var U;(U=$.deref())==null||U._removeListener(I)})),{registry:weakListenersState}),Trigger=class{constructor($={autoReset:!1}){this._options=$,this.reset()}async wait({timeout:$}={}){return $?asyncTimeout(this._promise,$,new TimeoutError($)):this._promise}wake($){return this._resolve($),this._options.autoReset?this.reset():this}reset(){return this._promise=new Promise(($,I)=>{this._resolve=$,this._reject=I}),this._promise.catch(()=>{}),this}throw($){return this._reject($),this._options.autoReset?this.reset():this}},MulticastObservable=class Jn extends Observable{constructor(I,U){super(q=>this._subscribe(q)),this._value=U,this._observers=new Set,this._completed=new Trigger,this._handlers={next:q=>{this._value=q,this._observers.forEach(G=>{var K;return(K=G.next)==null?void 0:K.call(G,q)})},error:q=>{this._observers.forEach(G=>{var K;return(K=G.error)==null?void 0:K.call(G,q)})},complete:()=>{this._completed.wake(),this._observers.forEach(q=>{var G;return(G=q.complete)==null?void 0:G.call(q)})}},this._observable=typeof I=="function"?new Observable(I):I,this._observable.subscribe(this._handlers)}static from(I,U){if("emit"in I)return new Jn(G=>{I.on(K=>{G.next(K)})},U);const q=Observable.from(I);return new Jn(q,U)}static of(...I){return new Jn(Observable.of(...I.slice(1)),I[0])}static empty(){return EMPTY_OBSERVABLE}get(){if(this._value===void 0)throw new Error("MulticastObservable is not initialized.");return this._value}async wait({timeout:I}={}){return await this._completed.wait({timeout:I}),this.get()}forEach(I){return this._observable.forEach(I)}map(I){return new Jn(this._observable.map(I),this._value&&I(this._value))}filter(I){return new Jn(this._observable.filter(I),this._value&&I(this._value)?this._value:void 0)}reduce(I,U){return new Jn(U?this._observable.reduce(I,U):this._observable.reduce(I),U??this._value)}flatMap(I){return new Jn(this._observable.flatMap(I),this._value&&I(this._value).get())}concat(...I){return new Jn(this._observable.concat(...I),this._value)}losslessConcat(I,...U){const q=U.filter(K=>K instanceof Jn),G=I(this._value,q.map(K=>K.get()));return new Jn(this._observable.concat(...U),G)}_subscribe(I){var U;return this._observers.has(I)||this._observers.add(I),this._value!==void 0&&((U=I.next)==null||U.call(I,this._value)),()=>{this._observers.delete(I)}}},EMPTY_OBSERVABLE=MulticastObservable.of(null),Mutex=class{constructor(){this._queue=Promise.resolve(),this._tag=null}get tag(){return this._tag}async acquire($){const I=this._queue;let U;return this._queue=new Promise(q=>{U=new MutexGuard(()=>{this._tag=null,q()})}),await I,$!==void 0&&(this._tag=$),U}async executeSynchronized($){const I=await this.acquire();try{return await $()}finally{I.release()}}},MutexGuard=class{constructor($){this._release=$}release(){this._release()}[Symbol.dispose](){this.release()}},classMutexSymbol=Symbol("class-mutex"),enableWarning=globalThis.mochaExecutor,synchronized=($,I,U)=>{const q=U.value;U.value=async function(...K){const Y=this[classMutexSymbol]??(this[classMutexSymbol]=new Mutex),J=`${$.constructor.name}.${I}`;let X;enableWarning?X=await warnAfterTimeout(1e4,`lock on ${J} (taken by ${Y.tag})`,()=>Y.acquire(J)):X=await Y.acquire(J);try{return await q.apply(this,K)}finally{X.release()}},Object.defineProperty(U.value,"name",{value:I+"$synchronized"})},__dxlog_file2$6="/home/runner/work/dxos/dxos/packages/common/async/src/track-leaks.ts",enabled=typeof process<"u"&&!!process.env.DX_TRACK_LEAKS,openResources=new Set,trackResource=$=>{if(!enabled)return()=>{};const I=$();return openResources.add(I),()=>{openResources.delete(I)}},dumpLeaks=()=>{if(enabled){log$2.info(`Leaked resources ${openResources.size}:`,void 0,{F:__dxlog_file2$6,L:82,S:void 0,C:($,I)=>$(...I)});for(const $ of openResources)log$2.info(`- ${$.name} at`,void 0,{F:__dxlog_file2$6,L:84,S:void 0,C:(I,U)=>I(...U)}),log$2.info($.openStack.getStack(1),void 0,{F:__dxlog_file2$6,L:85,S:void 0,C:(I,U)=>I(...U)}),log$2.info(`
|
|
852
852
|
`,void 0,{F:__dxlog_file2$6,L:86,S:void 0,C:(I,U)=>I(...U)})}};enabled&&(global.dxDumpLeaks=dumpLeaks);var DeferredTask=class{constructor($,I){this._ctx=$,this._callback=I,this._scheduled=!1,this._promise=null}schedule(){this._scheduled||(scheduleTask(this._ctx,async()=>{await this._promise,this._scheduled=!1,this._promise=runInContextAsync(this._ctx,()=>this._callback())}),this._scheduled=!0)}},runInContextAsync=async($,I)=>{try{await I()}catch(U){$.raise(U)}},scheduleTask=($,I,U)=>{const q=trackResource(()=>({name:`task (${I.name||"anonymous"})`,openStack:new StackTrace})),G=setTimeout(async()=>{K(),await runInContextAsync($,I),q()},U),K=$.onDispose(()=>{q(),clearTimeout(G)})},scheduleTaskInterval=($,I,U)=>{const q=trackResource(()=>({name:`repeating task (${I.name||"anonymous"})`,openStack:new StackTrace}));let G;const K=async()=>{await runInContextAsync($,I),!$.disposed&&(G=setTimeout(K,U))};G=setTimeout(K,U),$.onDispose(()=>{q(),clearTimeout(G)})},__dxlog_file$7="/home/runner/work/dxos/dxos/packages/sdk/react-client/src/invitations/useInvitationStatus.ts",useInvitationStatus=$=>{const[I,U]=React.useReducer((Y,J)=>(log$2("useInvitationStatus",{action:J},{F:__dxlog_file$7,L:81,S:void 0,C:(X,Z)=>X(...Z)}),{...Y,status:J.status,result:J.status===Invitation.State.SUCCESS?J.result:Y.result,...J.status===Invitation.State.ERROR&&{error:J.error},...(J.status===Invitation.State.ERROR||J.status===Invitation.State.CANCELLED||J.status===Invitation.State.TIMEOUT)&&{haltedAt:typeof Y.haltedAt>"u"?J.haltedAt:Y.haltedAt},observable:J.status===Invitation.State.CONNECTING?J.observable??Y.observable:Y.observable}),null,Y=>({status:Invitation.State.INIT,result:{spaceKey:null,identityKey:null,swarmKey:null,target:null},observable:$}));React.useEffect(()=>{var Z,Q;const Y=ee=>{switch(ee.state){case Invitation.State.CONNECTED:case Invitation.State.READY_FOR_AUTHENTICATION:case Invitation.State.AUTHENTICATING:{U({status:ee.state});break}case Invitation.State.SUCCESS:{U({status:ee.state,result:{spaceKey:ee.spaceKey||null,identityKey:ee.identityKey||null,swarmKey:ee.swarmKey||null,target:ee.target||null}});break}case Invitation.State.CANCELLED:case Invitation.State.TIMEOUT:{U({status:ee.state,haltedAt:I.status});break}}},J=(Z=I.observable)==null?void 0:Z.subscribe(Y,ee=>{U({status:Invitation.State.ERROR,error:ee,haltedAt:I.status})}),X=(Q=I.observable)==null?void 0:Q.get();return X&&Y(X),()=>J==null?void 0:J.unsubscribe()},[I.observable,I.status]);const q=React.useCallback(Y=>{U({status:Invitation.State.CONNECTING,observable:Y})},[]),G=React.useCallback(Y=>(log$2("authenticating...",{authCode:Y},{F:__dxlog_file$7,L:165,S:void 0,C:(J,X)=>J(...X)}),I.observable.authenticate(Y)),[I.observable]),K=React.useCallback(async()=>{var Y;return(Y=I.observable)==null?void 0:Y.cancel()},[I.observable]);return React.useMemo(()=>{var X;const Y=(X=I.observable)==null?void 0:X.get();return{status:I.status,haltedAt:I.haltedAt,result:I.result,error:I.error,cancel:K,connect:q,authenticate:G,id:Y==null?void 0:Y.invitationId,multiUse:Y==null?void 0:Y.multiUse,invitationCode:Y?clientProtocol.InvitationEncoder.encode(Y):void 0,authCode:Y==null?void 0:Y.authCode,authMethod:Y==null?void 0:Y.authMethod,type:Y==null?void 0:Y.type}},[I,K,q,G])};const AuthCode=$=>{const{code:I,large:U,classNames:q}=$,G=(I==null?void 0:I.length)??0,K=I==null?void 0:I.slice(0,G/2),Y=I==null?void 0:I.slice(G/2),J=()=>{navigator.clipboard.writeText(I??"")};return React.createElement("span",{className:mx(U?"text-6xl":"text-2xl","font-mono pli-2.5 flex gap-1.5 rounded cursor-pointer",q),onClick:J},React.createElement("span",null,K),React.createElement("span",null,Y))},InvitationListItem=$=>{const{invitation:I}=$,U=useInvitationStatus(I);return React.createElement(InvitationListItemImpl,{...$,invitationStatus:U})},avatarProps={size:10,variant:"circle"},AvatarStackEffect=({animation:$,status:I,reverseEffects:U})=>{const{tx:q}=useThemeContext();return React.createElement(React.Fragment,null,React.createElement("span",{role:"none",className:mx("absolute inline-end-auto opacity-20",U?"inline-start-3":"inline-start-1",getSize(avatarProps.size))},React.createElement("span",{role:"none",className:q("avatar.ring","avatar__ring",{...avatarProps,status:I,animation:$}),style:{animationDelay:"400ms"}})),React.createElement("span",{role:"none",className:mx("absolute inline-end-auto opacity-50","inline-start-2",getSize(avatarProps.size))},React.createElement("span",{role:"none",className:q("avatar.ring","avatar__ring",{...avatarProps,status:I,animation:$}),style:{animationDelay:"200ms"}})))},InvitationListItemImpl=({invitation:$,invitationStatus:I,send:U,onClickRemove:q,createInvitationUrl:G,reverseEffects:K,...Y})=>{const{t:J}=useTranslation("os"),{cancel:X,status:Z,invitationCode:Q,authCode:ee,multiUse:te}=I,ne=!([Invitation.State.ERROR,Invitation.State.TIMEOUT,Invitation.State.CANCELLED].indexOf(Z)>=0),ie=te||[Invitation.State.INIT,Invitation.State.CONNECTING,Invitation.State.CONNECTED].indexOf(Z)>=0,oe=Z===Invitation.State.READY_FOR_AUTHENTICATION,ce=React.useCallback(()=>q==null?void 0:q($),[$,q]),fe=Q&&G(Q),se=$==null?void 0:$.get().invitationId,de=$==null?void 0:$.get().lifetime,ue=$!=null&&$.expiry?formatDistanceToNow($==null?void 0:$.expiry,{addSuffix:!0}):void 0,pe=[Invitation.State.INIT,Invitation.State.CONNECTING,Invitation.State.CONNECTED,Invitation.State.READY_FOR_AUTHENTICATION,Invitation.State.AUTHENTICATING].includes(Z)?"pulse":"none",ve=[Invitation.State.ERROR,Invitation.State.TIMEOUT,Invitation.State.CANCELLED].includes(Z),me=[Invitation.State.CONNECTED,Invitation.State.READY_FOR_AUTHENTICATION,Invitation.State.AUTHENTICATING,Invitation.State.SUCCESS].includes(Z),be=ve?"error":me?"active":"inactive";return React.createElement(ListItem.Root,{id:Q,...Y,classNames:["flex gap-2 pis-3 pie-1 items-center relative",Y.classNames]},React.createElement(ListItem.Heading,{classNames:"sr-only"},J(te?"invite many list item label":"invite one list item label")),te&&React.createElement(AvatarStackEffect,{status:be,animation:pe,reverseEffects:K}),React.createElement(Tooltip.Root,null,React.createElement(Avatar.Root,{...avatarProps,animation:pe,status:be},React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Avatar.Frame,{tabIndex:0,classNames:[focusRing,"relative rounded-full place-self-center"]},React.createElement(Avatar.Fallback,{text:hexToEmoji(se)})))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"left",classNames:"z-[70]"},J(te?"invite many qr label":"invite one qr label"),React.createElement(Tooltip.Arrow,null)))),ie&&fe?React.createElement(Tooltip.Root,null,React.createElement(React.Fragment,null,React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Button,{variant:"ghost",classNames:"grow justify-start font-medium",onClick:()=>U({type:"selectInvitation",invitation:$}),"data-testid":"show-qrcode"},React.createElement("span",null,J("open share panel label")))),React.createElement(CopyButtonIconOnly,{variant:"ghost",value:fe})),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"left",classNames:"z-[70]"},de&&React.createElement("span",null,"Expires ",ue)))):oe?React.createElement(AuthCode,{code:ee,classNames:"grow"}):Z===Invitation.State.CONNECTING?React.createElement("span",{className:"pli-2 grow text-neutral-500"},"Connecting..."):Z===Invitation.State.AUTHENTICATING?React.createElement("span",{className:"pli-2 grow text-neutral-500"},"Authenticating..."):Z===Invitation.State.ERROR||Z===Invitation.State.TIMEOUT?React.createElement("span",{className:"pli-2 grow text-neutral-500"},"Failed"):Z===Invitation.State.CANCELLED?React.createElement("span",{className:"pli-2 grow text-neutral-500"},"Cancelled"):Z===Invitation.State.SUCCESS?React.createElement("span",{className:"pli-2 grow truncate"},"User joined"):React.createElement("span",{className:"grow"}," "),ne?React.createElement(Button,{variant:"ghost",classNames:"flex gap-1 pli-0",onClick:X,"data-testid":"cancel-invitation"},React.createElement("span",{className:"sr-only"},J("cancel invitation label")),React.createElement(react.X,{className:getSize(4)})):React.createElement(Button,{variant:"ghost",classNames:"flex gap-1 pli-0",onClick:ce,"data-testid":"remove-invitation"},React.createElement("span",{className:"sr-only"},J("remove invitation label")),React.createElement(react.X,{className:getSize(4)})))},InvitationList=({invitations:$,send:I,...U})=>{const{className:q,InvitationListItem:G=InvitationListItem}=U;return React.createElement(List,{classNames:mx("flex flex-col gap-2",q)},$.map(K=>{const Y=K.get().invitationId;return React.createElement(G,{key:Y,send:I,invitation:K,...U})}))},defaultActions={noopAction:{label:"No-op",description:"",icon:react.Placeholder,onClick:()=>{}}},BifurcatedAction=React.forwardRef(($,I)=>{const{classNames:U,variant:q,isFull:G=!0,actions:K=defaultActions,activeAction:Y,onChangeActiveAction:J,defaultActiveAction:X,...Z}=$,[Q=Object.keys(K)[0],ee]=$71cd76cc60e0454e$export$6f32135080cb4c3({prop:Y,onChange:J,defaultProp:X}),te=K[Q]??{},{t:ne}=useTranslation("os");return React.createElement("div",{role:"none",className:mx("mbs-2 flex gap-px items-center",G&&"is-full")},React.createElement(Button,{...Z,classNames:["bs-11 flex-1 min-is-0 flex gap-2 rounded-ie-none",U],ref:I,variant:q,onClick:te.onClick},te.icon&&React.createElement(te.icon,{className:getSize(5)}),React.createElement("span",null,te.label)),React.createElement(DropdownMenu2.Root,null,React.createElement(DropdownMenu2.Trigger,{asChild:!0},React.createElement(Button,{classNames:["bs-11 flex-none rounded-is-none",U]},React.createElement("span",{className:"sr-only"},ne("invite options label")),React.createElement(react.CaretDown,{className:getSize(4)}))),React.createElement(DropdownMenu2.Content,null,React.createElement(DropdownMenu2.Viewport,null,Object.entries(K).map(([ie,oe])=>React.createElement(DropdownMenu2.CheckboxItem,{key:ie,"aria-labelledby":`${ie}__label`,"aria-describedby":`${ie}__description`,checked:Q===ie,onCheckedChange:ce=>ce&&ee(ie),classNames:"gap-2"},oe.icon&&React.createElement(oe.icon,{className:getSize(5)}),React.createElement("div",{role:"none",className:"flex-1 min-is-0 space-b-1"},React.createElement("p",{id:`${ie}__label`},oe.label),oe.description&&React.createElement("p",{id:`${ie}__description`,className:descriptionText},oe.description)),React.createElement(DropdownMenu2.ItemIndicator,{asChild:!0},React.createElement(react.Check,{weight:"bold",className:getSize(4)}))))),React.createElement(DropdownMenu2.Arrow,null))))}),Action=React.forwardRef(($,I)=>{const{children:U,classNames:q,variant:G,isFull:K=!0,...Y}=$;return React.createElement(Button,{...Y,classNames:[K&&"is-full","bs-11 flex gap-2 mbs-2",q],ref:I,variant:G},U)}),Actions=React.forwardRef(({classNames:$,children:I,...U},q)=>React.createElement("div",{...U,className:mx("flex flex-col gap-2 mbs-2",Array.isArray(I)&&I.length>1?"justify-between":"justify-center",$),ref:q},I)),CloseButton=({onDone:$,...I})=>{const{t:U}=useTranslation("os");return React.createElement(Button,{variant:"ghost",classNames:mx("plb-0 pli-2 absolute block-start-0 inline-end-0 z-[1]"),onClick:()=>$==null?void 0:$(),...I},React.createElement(react.X,{weight:"bold",className:getSize(4)}),React.createElement("span",{className:"sr-only"},U("exit label")))},Emoji=({text:$,className:I})=>React.createElement("div",{role:"none",className:mx(getSize(14),"rounded relative pointer-events-none",I)},React.createElement("svg",{viewBox:`0 0 ${14*4} ${14*4}`,width:14*4,height:14*4},React.createElement("text",{x:"50%",y:"50%",textAnchor:"middle",dominantBaseline:"middle",baselineShift:"-0.25rem",fontSize:"2.25rem"},$))),Centered=$=>{const{children:I}=$;return React.createElement("div",{role:"none",className:"absolute inset-0 flex items-center justify-center"},I)},Heading=React.forwardRef(({titleId:$,title:I,titleSrOnly:U,children:q,corner:G},K)=>React.createElement("div",{role:"none",className:"pbe-2 relative",ref:K},G,React.createElement("h1",{...!U&&{id:$},className:mx(descriptionText,"text-center mlb-2",U&&"invisible")},I),U&&React.createElement("span",{id:$},I),q)),Label=$=>{const{children:I}=$;return React.createElement("span",{className:mx(descriptionText,"text-center mli-6 whitespace-normal")},I)},Input=({validationMessage:$,label:I,...U})=>React.createElement(Input$1.Root,null,React.createElement(Input$1.Label,null,I),React.createElement(Input$1.TextInput,{...U,classNames:"plb-3 mbs-2 text-center"}),React.createElement(Input$1.DescriptionAndValidation,null,$&&React.createElement(Input$1.Validation,null,$))),StepHeading=React.forwardRef(({children:$,className:I,...U},q)=>React.createElement("h2",{...U,className:mx("font-normal text-sm mbe-4 mli-1 text-center",I),ref:q},$));/*!
|
|
853
853
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
854
854
|
* Licensed under the MIT License.
|
|
@@ -920,7 +920,7 @@ ${(G=K.stack)==null?void 0:G.split(`
|
|
|
920
920
|
|
|
921
921
|
Error happened in the stream at:
|
|
922
922
|
${X.getStack()}`,Y(Q)):Y()};return this._outgoingRequests.set(q,new PendingRpcRequest(J,Z,!0)),this._sendMessage({request:{id:q,method:$,payload:I,stream:!0}}).catch(Q=>{Y(Q)}),()=>{this._sendMessage({streamClose:{id:q}}).catch(Q=>{log$2.catch(Q,void 0,{F:__dxlog_file$5,L:465,S:this,C:(ee,te)=>ee(...te)})})}})}async _sendMessage($,I){log$2("sending message",{type:Object.keys($)[0]},{F:__dxlog_file$5,L:472,S:this,C:(U,q)=>U(...q)}),await this._params.port.send(RpcMessage.encode($,{preserveAny:!0}),I)}async _callHandler($){try{invariant(typeof $.id=="number",void 0,{F:__dxlog_file$5,L:478,S:this,A:["typeof req.id === 'number'",""]}),invariant($.payload,void 0,{F:__dxlog_file$5,L:479,S:this,A:["req.payload",""]}),invariant($.method,void 0,{F:__dxlog_file$5,L:480,S:this,A:["req.method",""]});const I=await this._params.callHandler($.method,$.payload);return{id:$.id,payload:I}}catch(I){return{id:$.id,error:protocols.encodeError(I)}}}_callStreamHandler($,I){try{invariant(this._params.streamHandler,"Requests with streaming responses are not supported.",{F:__dxlog_file$5,L:497,S:this,A:["this._params.streamHandler","'Requests with streaming responses are not supported.'"]}),invariant(typeof $.id=="number",void 0,{F:__dxlog_file$5,L:498,S:this,A:["typeof req.id === 'number'",""]}),invariant($.payload,void 0,{F:__dxlog_file$5,L:499,S:this,A:["req.payload",""]}),invariant($.method,void 0,{F:__dxlog_file$5,L:500,S:this,A:["req.method",""]});const U=this._params.streamHandler($.method,$.payload);U.onReady(()=>{I({id:$.id,streamReady:!0})}),U.subscribe(q=>{I({id:$.id,payload:q})},q=>{I(q?{id:$.id,error:protocols.encodeError(q)}:{id:$.id,close:!0})}),this._localStreams.set($.id,U)}catch(U){I({id:$.id,error:protocols.encodeError(U)})}}};_ts_decorate$5([synchronized],RpcPeer.prototype,"open",null);var throwIfNotOpen=$=>{switch($){case"OPENED":return;case"INITIAL":throw new protocols.RpcNotOpenError;case"CLOSED":throw new protocols.RpcClosedError}},__dxlog_file2$5="/home/runner/work/dxos/dxos/packages/core/mesh/rpc/src/service.ts",ProtoRpcPeer=class{constructor($,I){this.rpc=$,this._peer=I}async open(){await this._peer.open()}async close(){await this._peer.close()}async abort(){await this._peer.abort()}},createProtoRpcPeer=({requested:$,exposed:I,handlers:U,encodingOptions:q,...G})=>{const K={};if(I){invariant(U,void 0,{F:__dxlog_file2$5,L:93,S:void 0,A:["handlers",""]});for(const X of Object.keys(I)){const Z=I[X].serviceProto.fullName.slice(1),Q=U[X];K[Z]=I[X].createServer(Q,q)}}const Y=new RpcPeer({...G,callHandler:(X,Z)=>{const[Q,ee]=parseMethodName(X);if(!K[Q])throw new Error(`Service not supported: ${Q}`);return K[Q].call(ee,Z)},streamHandler:(X,Z)=>{const[Q,ee]=parseMethodName(X);if(!K[Q])throw new Error(`Service not supported: ${Q}`);return K[Q].callStream(ee,Z)}}),J={};if($)for(const X of Object.keys($)){const Z=$[X].serviceProto.fullName.slice(1);J[X]=$[X].createClient({call:(Q,ee,te)=>Y.call(`${Z}.${Q}`,ee,te),callStream:(Q,ee,te)=>Y.callStream(`${Z}.${Q}`,ee,te)},q)}return new ProtoRpcPeer(J,Y)},parseMethodName=$=>{const I=$.lastIndexOf("."),U=$.slice(0,I),q=$.slice(I+1);if(U.length===0||q.length===0)throw new Error(`Invalid method: ${$}`);return[U,q]},createBundledRpcServer=({services:$,handlers:I,...U})=>{const q={};for(const G of Object.keys($)){const K=$[G].serviceProto.fullName.slice(1);q[K]=$[G].createServer(I[G])}return new RpcPeer({...U,callHandler:(G,K)=>{const[Y,J]=parseMethodName(G);if(!q[Y])throw new Error(`Service not supported: ${Y}`);return q[Y].call(J,K)},streamHandler:(G,K)=>{const[Y,J]=parseMethodName(G);if(!q[Y])throw new Error(`Service not supported: ${Y}`);return q[Y].callStream(J,K)}})};protocols.schema.getCodecForType("dxos.mesh.messaging.ReliablePayload"),protocols.schema.getCodecForType("dxos.mesh.messaging.Acknowledgement");var __dxlog_file2$4="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-rpc-client.ts",SIGNAL_KEEPALIVE_INTERVAL=1e4,SignalRPCClient=class{constructor({url:$,callbacks:I={}}){this._connectTrigger=new Trigger,this._closed=!1,this._closeComplete=new Trigger;const U=PublicKey.random().toHex();log$2.trace("dxos.mesh.signal-rpc-client.constructor",protocols.trace.begin({id:U}),{F:__dxlog_file2$4,L:55,S:this,C:(q,G)=>q(...G)}),this._url=$,this._callbacks=I,this._socket=new WebSocket3(this._url),this._rpc=createProtoRpcPeer({requested:{Signal:protocols.schema.getService("dxos.mesh.signal.Signal")},noHandshake:!0,port:{send:q=>{if(!this._closed)try{this._socket.send(q)}catch(G){log$2.warn("send error",G,{F:__dxlog_file2$4,L:74,S:this,C:(K,Y)=>K(...Y)})}},subscribe:q=>{this._socket.onmessage=async G=>{typeof Blob<"u"&&G.data instanceof Blob?q(export_Buffer.from(await G.data.arrayBuffer())):q(G.data)}}},encodingOptions:{preserveAny:!0}}),this._socket.onopen=async()=>{var q,G,K,Y;try{await this._rpc.open(),log$2(`RPC open ${this._url}`,void 0,{F:__dxlog_file2$4,L:95,S:this,C:(J,X)=>J(...X)}),(G=(q=this._callbacks).onConnected)==null||G.call(q),this._connectTrigger.wake(),this._keepaliveCtx=new Context,scheduleTaskInterval(this._keepaliveCtx,async()=>{var J;(J=this._socket)==null||J.send("__ping__")},SIGNAL_KEEPALIVE_INTERVAL)}catch(J){(Y=(K=this._callbacks).onError)==null||Y.call(K,J)}},this._socket.onclose=async()=>{var q,G;log$2(`Disconnected ${this._url}`,void 0,{F:__dxlog_file2$4,L:116,S:this,C:(K,Y)=>K(...Y)}),(G=(q=this._callbacks).onDisconnected)==null||G.call(q),this._closeComplete.wake(),await this.close()},this._socket.onerror=async q=>{var G,K,Y;if(!this._closed){(K=(G=this._callbacks).onError)==null||K.call(G,q.error??new Error(q.message)),this._connectTrigger.reset();try{await((Y=this._rpc)==null?void 0:Y.close())}catch(J){log$2.catch(J,void 0,{F:__dxlog_file2$4,L:134,S:this,C:(X,Z)=>X(...Z)})}this._closed=!0,log$2.warn(q.message??"Socket error",{url:this._url},{F:__dxlog_file2$4,L:138,S:this,C:(J,X)=>J(...X)})}},log$2.trace("dxos.mesh.signal-rpc-client.constructor",protocols.trace.end({id:U}),{F:__dxlog_file2$4,L:141,S:this,C:(q,G)=>q(...G)})}async close(){var $,I,U,q;await(($=this._keepaliveCtx)==null?void 0:$.dispose()),this._closed=!0;try{await((I=this._rpc)==null?void 0:I.close()),(((U=this._socket)==null?void 0:U.readyState)===WebSocket3.OPEN||((q=this._socket)==null?void 0:q.readyState)===WebSocket3.CONNECTING)&&this._socket.close(),await this._closeComplete.wait({timeout:1e3})}catch(G){log$2.warn("close error",G,{F:__dxlog_file2$4,L:156,S:this,C:(K,Y)=>K(...Y)})}}async join({topic:$,peerId:I}){var q,G;log$2("join",{topic:$,peerId:I},{F:__dxlog_file2$4,L:161,S:this,C:(K,Y)=>K(...Y)}),await this._connectTrigger.wait(),invariant(!this._closed,"SignalRPCClient is closed",{F:__dxlog_file2$4,L:163,S:this,A:["!this._closed","'SignalRPCClient is closed'"]}),invariant(this._rpc,"Rpc is not initialized",{F:__dxlog_file2$4,L:164,S:this,A:["this._rpc","'Rpc is not initialized'"]});const U=this._rpc.rpc.Signal.join({swarm:$.asUint8Array(),peer:I.asUint8Array(),metadata:(G=(q=this._callbacks)==null?void 0:q.getMetadata)==null?void 0:G.call(q)});return await U.waitUntilReady(),U}async receiveMessages($){log$2("receiveMessages",{peerId:$},{F:__dxlog_file2$4,L:175,S:this,C:(U,q)=>U(...q)}),invariant(!this._closed,"SignalRPCClient is closed",{F:__dxlog_file2$4,L:176,S:this,A:["!this._closed","'SignalRPCClient is closed'"]}),await this._connectTrigger.wait(),invariant(this._rpc,"Rpc is not initialized",{F:__dxlog_file2$4,L:178,S:this,A:["this._rpc","'Rpc is not initialized'"]});const I=this._rpc.rpc.Signal.receiveMessages({peer:$.asUint8Array()});return await I.waitUntilReady(),I}async sendMessage({author:$,recipient:I,payload:U}){var q,G;log$2("sendMessage",{author:$,recipient:I,payload:U},{F:__dxlog_file2$4,L:187,S:this,C:(K,Y)=>K(...Y)}),invariant(!this._closed,"SignalRPCClient is closed",{F:__dxlog_file2$4,L:188,S:this,A:["!this._closed","'SignalRPCClient is closed'"]}),await this._connectTrigger.wait(),invariant(this._rpc,"Rpc is not initialized",{F:__dxlog_file2$4,L:190,S:this,A:["this._rpc","'Rpc is not initialized'"]}),await this._rpc.rpc.Signal.sendMessage({author:$.asUint8Array(),recipient:I.asUint8Array(),payload:U,metadata:(G=(q=this._callbacks)==null?void 0:q.getMetadata)==null?void 0:G.call(q)})}},__dxlog_file3$2="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-client.ts",DEFAULT_RECONNECT_TIMEOUT=100,MAX_RECONNECT_TIMEOUT=5e3,ERROR_RECONCILE_DELAY=1e3,RECONCILE_INTERVAL=5e3,SignalClient=class{constructor($,I,U,q){if(this._host=$,this._onMessage=I,this._onSwarmEvent=U,this._getMetadata=q,this._state=SignalState.CLOSED,this._reconnectAfter=DEFAULT_RECONNECT_TIMEOUT,this._connectionStarted=new Date,this._lastStateChange=new Date,this._clientReady=new Trigger,this.statusChanged=new Event$1,this.commandTrace=new Event$1,this._swarmStreams=new ComplexMap(({topic:G,peerId:K})=>G.toHex()+K.toHex()),this._joinedTopics=new ComplexSet(({topic:G,peerId:K})=>G.toHex()+K.toHex()),this._messageStreams=new ComplexMap(G=>G.toHex()),this._subscribedMessages=new ComplexSet(({peerId:G})=>G.toHex()),this._reconciled=new Event$1,this._instanceId=PublicKey.random().toHex(),this._performance={sentMessages:0,receivedMessages:0,reconnectCounter:0,joinCounter:0,leaveCounter:0},!this._host.startsWith("wss://")&&!this._host.startsWith("ws://"))throw new Error(`Signal server requires a websocket URL. Provided: ${this._host}`)}async open(){log$2.trace("dxos.mesh.signal-client.open",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file3$2,L:128,S:this,C:($,I)=>$(...I)}),![SignalState.CONNECTED,SignalState.CONNECTING].includes(this._state)&&(this._ctx=new Context({onError:$=>{var I;this._state===SignalState.CLOSED||(I=this._ctx)!=null&&I.disposed||(this._state===SignalState.CONNECTED&&log$2.warn("SignalClient error:",$,{F:__dxlog_file3$2,L:140,S:this,C:(U,q)=>U(...q)}),this._scheduleReconcileAfterError())}}),this._reconcileTask=new DeferredTask(this._ctx,async()=>{await this._reconcileSwarmSubscriptions(),await this._reconcileMessageSubscriptions(),this._reconciled.emit()}),scheduleTaskInterval(this._ctx,async()=>{this._state===SignalState.CONNECTED&&this._reconcileTask.schedule()},RECONCILE_INTERVAL),this._reconnectTask=new DeferredTask(this._ctx,async()=>{await this._reconnect()}),this._setState(SignalState.CONNECTING),this._createClient(),log$2.trace("dxos.mesh.signal-client.open",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file3$2,L:169,S:this,C:($,I)=>$(...I)}))}async close(){var $,I;log$2("closing...",void 0,{F:__dxlog_file3$2,L:173,S:this,C:(U,q)=>U(...q)}),![SignalState.CLOSED].includes(this._state)&&(await(($=this._ctx)==null?void 0:$.dispose()),this._clientReady.reset(),await((I=this._client)==null?void 0:I.close()),this._client=void 0,this._setState(SignalState.CLOSED),log$2("closed",void 0,{F:__dxlog_file3$2,L:184,S:this,C:(U,q)=>U(...q)}))}getStatus(){var $;return{host:this._host,state:this._state,error:($=this._lastError)==null?void 0:$.message,reconnectIn:this._reconnectAfter,connectionStarted:this._connectionStarted,lastStateChange:this._lastStateChange}}async join({topic:$,peerId:I}){log$2("joining",{topic:$,peerId:I},{F:__dxlog_file3$2,L:199,S:this,C:(U,q)=>U(...q)}),this._performance.joinCounter++,this._joinedTopics.add({topic:$,peerId:I}),this._reconcileTask.schedule()}async leave({topic:$,peerId:I}){var U;this._performance.leaveCounter++,log$2("leaving",{topic:$,peerId:I},{F:__dxlog_file3$2,L:207,S:this,C:(q,G)=>q(...G)}),(U=this._swarmStreams.get({topic:$,peerId:I}))==null||U.close(),this._swarmStreams.delete({topic:$,peerId:I}),this._joinedTopics.delete({topic:$,peerId:I})}async sendMessage($){this._performance.sentMessages++,await this._clientReady.wait(),invariant(this._state===SignalState.CONNECTED,"Not connected to Signal Server",{F:__dxlog_file3$2,L:216,S:this,A:["this._state === SignalState.CONNECTED","'Not connected to Signal Server'"]}),await this._client.sendMessage($)}async subscribeMessages($){log$2("subscribing to messages",{peerId:$},{F:__dxlog_file3$2,L:221,S:this,C:(I,U)=>I(...U)}),this._subscribedMessages.add({peerId:$}),this._reconcileTask.schedule()}async unsubscribeMessages($){var I;log$2("unsubscribing from messages",{peerId:$},{F:__dxlog_file3$2,L:227,S:this,C:(U,q)=>U(...q)}),this._subscribedMessages.delete({peerId:$}),(I=this._messageStreams.get($))==null||I.close(),this._messageStreams.delete($)}_scheduleReconcileAfterError(){scheduleTask(this._ctx,()=>{this._reconcileTask.schedule()},ERROR_RECONCILE_DELAY)}_setState($){this._state=$,this._lastStateChange=new Date,log$2("signal state changed",{status:this.getStatus()},{F:__dxlog_file3$2,L:246,S:this,C:(I,U)=>I(...U)}),this.statusChanged.emit(this.getStatus())}_createClient(){log$2("creating client",{host:this._host,state:this._state},{F:__dxlog_file3$2,L:251,S:this,C:($,I)=>$(...I)}),invariant(!this._client,"Client already created",{F:__dxlog_file3$2,L:252,S:this,A:["!this._client","'Client already created'"]}),this._connectionStarted=new Date,this._connectionCtx=this._ctx.derive(),this._connectionCtx.onDispose(async()=>{log$2("connection context disposed",void 0,{F:__dxlog_file3$2,L:259,S:this,C:($,I)=>$(...I)}),await Promise.all(Array.from(this._swarmStreams.values()).map($=>$.close())),await Promise.all(Array.from(this._messageStreams.values()).map($=>$.close())),this._swarmStreams.clear(),this._messageStreams.clear()});try{this._client=new SignalRPCClient({url:this._host,callbacks:{onConnected:()=>{log$2("socket connected",void 0,{F:__dxlog_file3$2,L:271,S:this,C:($,I)=>$(...I)}),this._lastError=void 0,this._reconnectAfter=DEFAULT_RECONNECT_TIMEOUT,this._setState(SignalState.CONNECTED),this._clientReady.wake(),this._reconcileTask.schedule()},onDisconnected:()=>{if(log$2("socket disconnected",{state:this._state},{F:__dxlog_file3$2,L:280,S:this,C:($,I)=>$(...I)}),this._state===SignalState.ERROR){this._setState(SignalState.DISCONNECTED);return}this._state!==SignalState.CONNECTED&&this._state!==SignalState.CONNECTING&&this._incrementReconnectTimeout(),this._setState(SignalState.DISCONNECTED),this._reconnectTask.schedule()},onError:$=>{log$2("socket error",{error:$,state:this._state},{F:__dxlog_file3$2,L:295,S:this,C:(I,U)=>I(...U)}),this._lastError=$,this._state!==SignalState.CONNECTED&&this._state!==SignalState.CONNECTING&&this._incrementReconnectTimeout(),this._setState(SignalState.ERROR),this._reconnectTask.schedule()},getMetadata:this._getMetadata}})}catch($){this._state!==SignalState.CONNECTED&&this._state!==SignalState.CONNECTING&&this._incrementReconnectTimeout(),this._lastError=$,this._setState(SignalState.DISCONNECTED),this._reconnectTask.schedule()}}_incrementReconnectTimeout(){this._reconnectAfter*=2,this._reconnectAfter=Math.min(this._reconnectAfter,MAX_RECONNECT_TIMEOUT)}async _reconnect(){var $,I;if(log$2(`reconnecting in ${this._reconnectAfter}ms`,{state:this._state},{F:__dxlog_file3$2,L:323,S:this,C:(U,q)=>U(...q)}),this._performance.reconnectCounter++,this._state===SignalState.RECONNECTING){log$2.warn("Signal api already reconnecting.",void 0,{F:__dxlog_file3$2,L:327,S:this,C:(U,q)=>U(...q)});return}this._state!==SignalState.CLOSED&&(this._clientReady.reset(),await(($=this._connectionCtx)==null?void 0:$.dispose()),(I=this._client)==null||I.close().catch(()=>{}),this._client=void 0,await cancelWithContext(this._ctx,sleep(this._reconnectAfter)),this._setState(SignalState.RECONNECTING),this._createClient())}async _reconcileSwarmSubscriptions(){var I;await asyncTimeout(cancelWithContext(this._connectionCtx,this._clientReady.wait()),5e3);const $=this._client;invariant(this._state===SignalState.CONNECTED,"Not connected to Signal Server",{F:__dxlog_file3$2,L:352,S:this,A:["this._state === SignalState.CONNECTED","'Not connected to Signal Server'"]});for(const{topic:U,peerId:q}of this._swarmStreams.keys())this._joinedTopics.has({topic:U,peerId:q})||((I=this._swarmStreams.get({topic:U,peerId:q}))==null||I.close(),this._swarmStreams.delete({topic:U,peerId:q}));for(const{topic:U,peerId:q}of this._joinedTopics.values()){if(this._swarmStreams.has({topic:U,peerId:q}))continue;const G=await asyncTimeout(cancelWithContext(this._connectionCtx,$.join({topic:U,peerId:q})),5e3);G.subscribe(async K=>{log$2("swarm event",{swarmEvent:K},{F:__dxlog_file3$2,L:379,S:this,C:(Y,J)=>Y(...J)}),await this._onSwarmEvent({topic:U,swarmEvent:K})}),this._swarmStreams.set({topic:U,peerId:q},G)}}async _reconcileMessageSubscriptions(){var I;await asyncTimeout(cancelWithContext(this._connectionCtx,this._clientReady.wait()),5e3);const $=this._client;invariant(this._state===SignalState.CONNECTED,"Not connected to Signal Server",{F:__dxlog_file3$2,L:392,S:this,A:["this._state === SignalState.CONNECTED","'Not connected to Signal Server'"]});for(const U of this._messageStreams.keys())this._subscribedMessages.has({peerId:U})||((I=this._messageStreams.get(U))==null||I.close(),this._messageStreams.delete(U));for(const{peerId:U}of this._subscribedMessages.values()){if(this._messageStreams.has(U))continue;const q=await asyncTimeout(cancelWithContext(this._connectionCtx,$.receiveMessages(U)),5e3);q.subscribe(async G=>{this._performance.receivedMessages++,await this._onMessage({author:PublicKey.from(G.author),recipient:PublicKey.from(G.recipient),payload:G.payload})}),this._messageStreams.set(U,q)}}};function _ts_decorate$4($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5$2="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/websocket-signal-manager.ts",MAX_SERVER_FAILURES=5,WSS_SIGNAL_SERVER_REBOOT_DELAY=3e3,WebsocketSignalManager=class{constructor($,I){this._hosts=$,this._getMetadata=I,this._servers=new Map,this._opened=!1,this.failureCount=new Map,this.statusChanged=new Event$1,this.commandTrace=new Event$1,this.swarmEvent=new Event$1,this.onMessage=new Event$1,this._instanceId=PublicKey.random().toHex(),log$2("Created WebsocketSignalManager",{hosts:this._hosts},{F:__dxlog_file5$2,L:51,S:this,C:(U,q)=>U(...q)});for(const U of this._hosts){if(this._servers.has(U.server))continue;const q=new SignalClient(U.server,async G=>this.onMessage.emit(G),async G=>this.swarmEvent.emit(G),this._getMetadata);q.statusChanged.on(()=>this.statusChanged.emit(this.getStatus())),this._servers.set(U.server,q),this.failureCount.set(U.server,0),q.commandTrace.on(G=>this.commandTrace.emit(G))}}async open(){this._opened||(log$2("open signal manager",{hosts:this._hosts},{F:__dxlog_file5$2,L:78,S:this,C:($,I)=>$(...I)}),log$2.trace("dxos.mesh.websocket-signal-manager.open",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file5$2,L:79,S:this,C:($,I)=>$(...I)}),this._initContext(),[...this._servers.values()].forEach($=>$.open()),this._opened=!0,log$2.trace("dxos.mesh.websocket-signal-manager.open",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file5$2,L:87,S:this,C:($,I)=>$(...I)}))}async close(){this._opened&&(this._opened=!1,await this._ctx.dispose(),await Promise.all(Array.from(this._servers.values()).map($=>$.close())))}async restartServer($){log$2("restarting server",{serverName:$},{F:__dxlog_file5$2,L:103,S:this,C:(U,q)=>U(...q)}),invariant(this._opened,"server already closed",{F:__dxlog_file5$2,L:104,S:this,A:["this._opened","'server already closed'"]});const I=this._servers.get($);invariant(I,"server not found",{F:__dxlog_file5$2,L:107,S:this,A:["server","'server not found'"]}),await I.close(),await sleep(WSS_SIGNAL_SERVER_REBOOT_DELAY),await I.open()}getStatus(){return Array.from(this._servers.values()).map($=>$.getStatus())}async join({topic:$,peerId:I}){log$2("join",{topic:$,peerId:I},{F:__dxlog_file5$2,L:120,S:this,C:(U,q)=>U(...q)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:121,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(U=>U.join({topic:$,peerId:I}))}async leave({topic:$,peerId:I}){log$2("leaving",{topic:$,peerId:I},{F:__dxlog_file5$2,L:127,S:this,C:(U,q)=>U(...q)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:128,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(U=>U.leave({topic:$,peerId:I}))}async sendMessage({author:$,recipient:I,payload:U}){log$2("signal",{recipient:I},{F:__dxlog_file5$2,L:142,S:this,C:(q,G)=>q(...G)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:143,S:this,A:["this._opened","'Closed'"]}),this._forEachServer(async(q,G)=>{q.sendMessage({author:$,recipient:I,payload:U}).catch(K=>{K instanceof protocols.RateLimitExceededError?log$2.info("WSS rate limit exceeded",{err:K},{F:__dxlog_file5$2,L:148,S:this,C:(Y,J)=>Y(...J)}):K instanceof protocols.TimeoutError||K.constructor.name==="TimeoutError"?(log$2.info("WSS sendMessage timeout",{err:K},{F:__dxlog_file5$2,L:150,S:this,C:(Y,J)=>Y(...J)}),this.checkServerFailure(G)):(log$2.info(`error sending to ${G}`,{err:K},{F:__dxlog_file5$2,L:153,S:this,C:(Y,J)=>Y(...J)}),this.checkServerFailure(G))})})}async checkServerFailure($){const I=this.failureCount.get($)??0;if(I>MAX_SERVER_FAILURES){log$2.warn(`too many failures sending to ${$} (${I} > ${MAX_SERVER_FAILURES}), restarting`,void 0,{F:__dxlog_file5$2,L:164,S:this,C:(U,q)=>U(...q)}),await this.restartServer($),this.failureCount.set($,0);return}this.failureCount.set($,(this.failureCount.get($)??0)+1)}async subscribeMessages($){log$2("subscribed for message stream",{peerId:$},{F:__dxlog_file5$2,L:174,S:this,C:(I,U)=>I(...U)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:175,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(async I=>I.subscribeMessages($))}async unsubscribeMessages($){log$2("subscribed for message stream",{peerId:$},{F:__dxlog_file5$2,L:181,S:this,C:(I,U)=>I(...U)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:182,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(async I=>I.unsubscribeMessages($))}_initContext(){this._ctx=new Context({onError:$=>log$2.catch($,void 0,{F:__dxlog_file5$2,L:189,S:this,C:(I,U)=>I(...U)})})}async _forEachServer($){return Promise.all(Array.from(this._servers.entries()).map(([I,U])=>$(U,I)))}};_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"open",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"close",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"join",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"leave",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"checkServerFailure",null);var __dxlog_file6$1="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/utils.ts",setIdentityTags=({identityService:$,devicesService:I,setTag:U})=>{$.queryIdentity().subscribe(q=>{var G;if(!((G=q==null?void 0:q.identity)!=null&&G.identityKey)){log$2("empty response from identity service",{idqr:q},{F:__dxlog_file6$1,L:21,S:void 0,C:(K,Y)=>K(...Y)});return}U("identityKey",q.identity.identityKey.truncate())}),I.queryDevices().subscribe(q=>{if(!q||!q.devices||q.devices.length===0){log$2("empty response from device service",{device:q},{F:__dxlog_file6$1,L:30,S:void 0,C:(K,Y)=>K(...Y)});return}invariant(q,"empty response from device service",{F:__dxlog_file6$1,L:33,S:void 0,A:["dqr","'empty response from device service'"]});const G=q.devices.find(K=>K.kind===DeviceKind.CURRENT);if(!G){log$2("no current device",{device:q},{F:__dxlog_file6$1,L:37,S:void 0,C:(K,Y)=>K(...Y)});return}U("deviceKey",G.deviceKey.truncate())})};function dist($,I){if($.length!==I.length)throw new Error("Inputs should have the same length");for(var U=Buffer.allocUnsafe($.length),q=0;q<$.length;q++)U[q]=$[q]^I[q];return U}dist.compare=function $(I,U){if(I.length!==U.length)throw new Error("Inputs should have the same length");for(var q=0;q<I.length;q++)if(I[q]!==U[q])return I[q]<U[q]?-1:1;return 0},dist.gt=function $(I,U){return dist.compare(I,U)===1},dist.lt=function $(I,U){return dist.compare(I,U)===-1},dist.eq=function $(I,U){return dist.compare(I,U)===0};var browser$2={exports:{}},ms,hasRequiredMs;function requireMs(){if(hasRequiredMs)return ms;hasRequiredMs=1;var $=1e3,I=$*60,U=I*60,q=U*24,G=q*7,K=q*365.25;ms=function(Q,ee){ee=ee||{};var te=typeof Q;if(te==="string"&&Q.length>0)return Y(Q);if(te==="number"&&isFinite(Q))return ee.long?X(Q):J(Q);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(Q))};function Y(Q){if(Q=String(Q),!(Q.length>100)){var ee=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(Q);if(ee){var te=parseFloat(ee[1]),ne=(ee[2]||"ms").toLowerCase();switch(ne){case"years":case"year":case"yrs":case"yr":case"y":return te*K;case"weeks":case"week":case"w":return te*G;case"days":case"day":case"d":return te*q;case"hours":case"hour":case"hrs":case"hr":case"h":return te*U;case"minutes":case"minute":case"mins":case"min":case"m":return te*I;case"seconds":case"second":case"secs":case"sec":case"s":return te*$;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return te;default:return}}}}function J(Q){var ee=Math.abs(Q);return ee>=q?Math.round(Q/q)+"d":ee>=U?Math.round(Q/U)+"h":ee>=I?Math.round(Q/I)+"m":ee>=$?Math.round(Q/$)+"s":Q+"ms"}function X(Q){var ee=Math.abs(Q);return ee>=q?Z(Q,ee,q,"day"):ee>=U?Z(Q,ee,U,"hour"):ee>=I?Z(Q,ee,I,"minute"):ee>=$?Z(Q,ee,$,"second"):Q+" ms"}function Z(Q,ee,te,ne){var ie=ee>=te*1.5;return Math.round(Q/te)+" "+ne+(ie?"s":"")}return ms}function setup($){U.debug=U,U.default=U,U.coerce=X,U.disable=K,U.enable=G,U.enabled=Y,U.humanize=requireMs(),U.destroy=Z,Object.keys($).forEach(Q=>{U[Q]=$[Q]}),U.names=[],U.skips=[],U.formatters={};function I(Q){let ee=0;for(let te=0;te<Q.length;te++)ee=(ee<<5)-ee+Q.charCodeAt(te),ee|=0;return U.colors[Math.abs(ee)%U.colors.length]}U.selectColor=I;function U(Q){let ee,te=null,ne,ie;function oe(...ce){if(!oe.enabled)return;const fe=oe,se=Number(new Date),de=se-(ee||se);fe.diff=de,fe.prev=ee,fe.curr=se,ee=se,ce[0]=U.coerce(ce[0]),typeof ce[0]!="string"&&ce.unshift("%O");let ue=0;ce[0]=ce[0].replace(/%([a-zA-Z%])/g,(ve,me)=>{if(ve==="%%")return"%";ue++;const be=U.formatters[me];if(typeof be=="function"){const ye=ce[ue];ve=be.call(fe,ye),ce.splice(ue,1),ue--}return ve}),U.formatArgs.call(fe,ce),(fe.log||U.log).apply(fe,ce)}return oe.namespace=Q,oe.useColors=U.useColors(),oe.color=U.selectColor(Q),oe.extend=q,oe.destroy=U.destroy,Object.defineProperty(oe,"enabled",{enumerable:!0,configurable:!1,get:()=>te!==null?te:(ne!==U.namespaces&&(ne=U.namespaces,ie=U.enabled(Q)),ie),set:ce=>{te=ce}}),typeof U.init=="function"&&U.init(oe),oe}function q(Q,ee){const te=U(this.namespace+(typeof ee>"u"?":":ee)+Q);return te.log=this.log,te}function G(Q){U.save(Q),U.namespaces=Q,U.names=[],U.skips=[];let ee;const te=(typeof Q=="string"?Q:"").split(/[\s,]+/),ne=te.length;for(ee=0;ee<ne;ee++)te[ee]&&(Q=te[ee].replace(/\*/g,".*?"),Q[0]==="-"?U.skips.push(new RegExp("^"+Q.slice(1)+"$")):U.names.push(new RegExp("^"+Q+"$")))}function K(){const Q=[...U.names.map(J),...U.skips.map(J).map(ee=>"-"+ee)].join(",");return U.enable(""),Q}function Y(Q){if(Q[Q.length-1]==="*")return!0;let ee,te;for(ee=0,te=U.skips.length;ee<te;ee++)if(U.skips[ee].test(Q))return!1;for(ee=0,te=U.names.length;ee<te;ee++)if(U.names[ee].test(Q))return!0;return!1}function J(Q){return Q.toString().substring(2,Q.toString().length-2).replace(/\.\*\?$/,"*")}function X(Q){return Q instanceof Error?Q.stack||Q.message:Q}function Z(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return U.enable(U.load()),U}var common=setup;(function($,I){I.formatArgs=q,I.save=G,I.load=K,I.useColors=U,I.storage=Y(),I.destroy=(()=>{let X=!1;return()=>{X||(X=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),I.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function U(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function q(X){if(X[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+X[0]+(this.useColors?"%c ":" ")+"+"+$.exports.humanize(this.diff),!this.useColors)return;const Z="color: "+this.color;X.splice(1,0,Z,"color: inherit");let Q=0,ee=0;X[0].replace(/%[a-zA-Z%]/g,te=>{te!=="%%"&&(Q++,te==="%c"&&(ee=Q))}),X.splice(ee,0,Z)}I.log=console.debug||console.log||(()=>{});function G(X){try{X?I.storage.setItem("debug",X):I.storage.removeItem("debug")}catch{}}function K(){let X;try{X=I.storage.getItem("debug")}catch{}return!X&&typeof process<"u"&&"env"in process&&(X=process.env.DEBUG),X}function Y(){try{return localStorage}catch{}}$.exports=common(I);const{formatters:J}=$.exports;J.j=function(X){try{return JSON.stringify(X)}catch(Z){return"[UnexpectedJSONParseError]: "+Z.message}}})(browser$2,browser$2.exports);var browserExports$1=browser$2.exports,getBrowserRtc=function $(){if(typeof globalThis>"u")return null;var I={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return I.RTCPeerConnection?I:null},browser$1={exports:{}},MAX_BYTES=65536,MAX_UINT32=4294967295;function oldBrowser(){throw new Error(`Secure random number generation is not supported by this browser.
|
|
923
|
-
Use Chrome, Firefox or Internet Explorer 11`)}var Buffer$2=requireSafeBuffer().Buffer,crypto=commonjsGlobal.crypto||commonjsGlobal.msCrypto;crypto&&crypto.getRandomValues?browser$1.exports=randomBytes:browser$1.exports=oldBrowser;function randomBytes($,I){if($>MAX_UINT32)throw new RangeError("requested too many random bytes");var U=Buffer$2.allocUnsafe($);if($>0)if($>MAX_BYTES)for(var q=0;q<$;q+=MAX_BYTES)crypto.getRandomValues(U.slice(q,q+MAX_BYTES));else crypto.getRandomValues(U);return typeof I=="function"?process.nextTick(function(){I(null,U)}):U}var browserExports=browser$1.exports;/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */let promise;var queueMicrotask_1=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:commonjsGlobal):$=>(promise||(promise=Promise.resolve())).then($).catch(I=>setTimeout(()=>{throw I},0));function assign$3($,I){for(const U in I)Object.defineProperty($,U,{value:I[U],enumerable:!0,configurable:!0});return $}function createError($,I,U){if(!$||typeof $=="string")throw new TypeError("Please pass an Error to err-code");U||(U={}),typeof I=="object"&&(U=I,I=""),I&&(U.code=I);try{return assign$3($,U)}catch{U.message=$.message,U.stack=$.stack;const G=function(){};return G.prototype=Object.create(Object.getPrototypeOf($)),assign$3(new G,U)}}var errCode$1=createError;/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const debug=browserExports$1("simple-peer"),getBrowserRTC=getBrowserRtc,randombytes=browserExports,stream$1=readableBrowserExports,queueMicrotask$1=queueMicrotask_1,errCode=errCode$1,{Buffer:Buffer$1}=buffer,MAX_BUFFERED_AMOUNT$1=64*1024,ICECOMPLETE_TIMEOUT=5*1e3,CHANNEL_CLOSING_TIMEOUT=5*1e3;function filterTrickle($){return $.replace(/a=ice-options:trickle\s\n/g,"")}function warn$1($){console.warn($)}let Peer$1=class pr extends stream$1.Duplex{constructor(I){if(I=Object.assign({allowHalfOpen:!1},I),super(I),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",I),this.channelName=I.initiator?I.channelName||randombytes(20).toString("hex"):null,this.initiator=I.initiator||!1,this.channelConfig=I.channelConfig||pr.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},pr.config,I.config),this.offerOptions=I.offerOptions||{},this.answerOptions=I.answerOptions||{},this.sdpTransform=I.sdpTransform||(U=>U),this.streams=I.streams||(I.stream?[I.stream]:[]),this.trickle=I.trickle!==void 0?I.trickle:!0,this.allowHalfTrickle=I.allowHalfTrickle!==void 0?I.allowHalfTrickle:!1,this.iceCompleteTimeout=I.iceCompleteTimeout||ICECOMPLETE_TIMEOUT,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=I.wrtc&&typeof I.wrtc=="object"?I.wrtc:getBrowserRTC(),!this._wrtc)throw errCode(typeof window>"u"?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(U){this.destroy(errCode(U,"ERR_PC_CONSTRUCTOR"));return}this._isReactNativeWebrtc=typeof this._pc._peerConnectionId=="number",this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=U=>{this._onIceCandidate(U)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(U=>{this.destroy(errCode(U,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=U=>{this._setupData(U)},this.streams&&this.streams.forEach(U=>{this.addStream(U)}),this._pc.ontrack=U=>{this._onTrack(U)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&this._channel.readyState==="open"}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof I=="string")try{I=JSON.parse(I)}catch{I={}}this._debug("signal()"),I.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),I.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(I.transceiverRequest.kind,I.transceiverRequest.init)),I.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(I.candidate):this._pendingCandidates.push(I.candidate)),I.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(I)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(U=>{this._addIceCandidate(U)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(U=>{this.destroy(errCode(U,"ERR_SET_REMOTE_DESCRIPTION"))}),!I.sdp&&!I.candidate&&!I.renegotiate&&!I.transceiverRequest&&this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(I){const U=new this._wrtc.RTCIceCandidate(I);this._pc.addIceCandidate(U).catch(q=>{!U.address||U.address.endsWith(".local")?warn$1("Ignoring unsupported ICE candidate."):this.destroy(errCode(q,"ERR_ADD_ICE_CANDIDATE"))})}send(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(I)}}addTransceiver(I,U){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(I,U),this._needsNegotiation()}catch(q){this.destroy(errCode(q,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:I,init:U}})}}addStream(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),I.getTracks().forEach(U=>{this.addTrack(U,I)})}}addTrack(I,U){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const q=this._senderMap.get(I)||new Map;let G=q.get(U);if(!G)G=this._pc.addTrack(I,U),q.set(U,G),this._senderMap.set(I,q),this._needsNegotiation();else throw G.removed?errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(I,U,q){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const G=this._senderMap.get(I),K=G?G.get(q):null;if(!K)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");U&&this._senderMap.set(U,G),K.replaceTrack!=null?K.replaceTrack(U):this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(I,U){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const q=this._senderMap.get(I),G=q?q.get(U):null;if(!G)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{G.removed=!0,this._pc.removeTrack(G)}catch(K){K.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(G):this.destroy(errCode(K,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),I.getTracks().forEach(U=>{this.removeTrack(U,I)})}}_needsNegotiation(){this._debug("_needsNegotiation"),!this._batchedNegotiation&&(this._batchedNegotiation=!0,queueMicrotask$1(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(I){this._destroy(I,()=>{})}_destroy(I,U){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",I&&(I.message||I)),queueMicrotask$1(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",I&&(I.message||I)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch{}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch{}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,I&&this.emit("error",I),this.emit("close"),U()}))}_setupData(I){if(!I.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=I.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT$1),this.channelName=this._channel.label,this._channel.onmessage=q=>{this._onChannelMessage(q)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=q=>{const G=q.error instanceof Error?q.error:new Error(`Datachannel error: ${q.message} ${q.filename}:${q.lineno}:${q.colno}`);this.destroy(errCode(G,"ERR_DATA_CHANNEL"))};let U=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(U&&this._onChannelClose(),U=!0):U=!1},CHANNEL_CLOSING_TIMEOUT)}_read(){}_write(I,U,q){if(this.destroyed)return q(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(I)}catch(G){return this.destroy(errCode(G,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT$1?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=q):q(null)}else this._debug("write before connect"),this._chunk=I,this._cb=q}_onFinish(){if(this.destroyed)return;const I=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?I():this.once("connect",I)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(I=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(I.sdp=filterTrickle(I.sdp)),I.sdp=this.sdpTransform(I.sdp);const U=()=>{if(this.destroyed)return;const K=this._pc.localDescription||I;this._debug("signal"),this.emit("signal",{type:K.type,sdp:K.sdp})},q=()=>{this._debug("createOffer success"),!this.destroyed&&(this.trickle||this._iceComplete?U():this.once("_iceComplete",U))},G=K=>{this.destroy(errCode(K,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(I).then(q).catch(G)}).catch(I=>{this.destroy(errCode(I,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(I=>{!I.mid&&I.sender.track&&!I.requested&&(I.requested=!0,this.addTransceiver(I.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(I=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(I.sdp=filterTrickle(I.sdp)),I.sdp=this.sdpTransform(I.sdp);const U=()=>{if(this.destroyed)return;const K=this._pc.localDescription||I;this._debug("signal"),this.emit("signal",{type:K.type,sdp:K.sdp}),this.initiator||this._requestMissingTransceivers()},q=()=>{this.destroyed||(this.trickle||this._iceComplete?U():this.once("_iceComplete",U))},G=K=>{this.destroy(errCode(K,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(I).then(q).catch(G)}).catch(I=>{this.destroy(errCode(I,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._pc.connectionState==="failed"&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const I=this._pc.iceConnectionState,U=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",I,U),this.emit("iceStateChange",I,U),(I==="connected"||I==="completed")&&(this._pcReady=!0,this._maybeReady()),I==="failed"&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),I==="closed"&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(I){const U=q=>(Object.prototype.toString.call(q.values)==="[object Array]"&&q.values.forEach(G=>{Object.assign(q,G)}),q);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(q=>{const G=[];q.forEach(K=>{G.push(U(K))}),I(null,G)},q=>I(q)):this._pc.getStats.length>0?this._pc.getStats(q=>{if(this.destroyed)return;const G=[];q.result().forEach(K=>{const Y={};K.names().forEach(J=>{Y[J]=K.stat(J)}),Y.id=K.id,Y.type=K.type,Y.timestamp=K.timestamp,G.push(U(Y))}),I(null,G)},q=>I(q)):I(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const I=()=>{this.destroyed||this.getStats((U,q)=>{if(this.destroyed)return;U&&(q=[]);const G={},K={},Y={};let J=!1;q.forEach(Z=>{(Z.type==="remotecandidate"||Z.type==="remote-candidate")&&(G[Z.id]=Z),(Z.type==="localcandidate"||Z.type==="local-candidate")&&(K[Z.id]=Z),(Z.type==="candidatepair"||Z.type==="candidate-pair")&&(Y[Z.id]=Z)});const X=Z=>{J=!0;let Q=K[Z.localCandidateId];Q&&(Q.ip||Q.address)?(this.localAddress=Q.ip||Q.address,this.localPort=Number(Q.port)):Q&&Q.ipAddress?(this.localAddress=Q.ipAddress,this.localPort=Number(Q.portNumber)):typeof Z.googLocalAddress=="string"&&(Q=Z.googLocalAddress.split(":"),this.localAddress=Q[0],this.localPort=Number(Q[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let ee=G[Z.remoteCandidateId];ee&&(ee.ip||ee.address)?(this.remoteAddress=ee.ip||ee.address,this.remotePort=Number(ee.port)):ee&&ee.ipAddress?(this.remoteAddress=ee.ipAddress,this.remotePort=Number(ee.portNumber)):typeof Z.googRemoteAddress=="string"&&(ee=Z.googRemoteAddress.split(":"),this.remoteAddress=ee[0],this.remotePort=Number(ee[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(q.forEach(Z=>{Z.type==="transport"&&Z.selectedCandidatePairId&&X(Y[Z.selectedCandidatePairId]),(Z.type==="googCandidatePair"&&Z.googActiveConnection==="true"||(Z.type==="candidatepair"||Z.type==="candidate-pair")&&Z.selected)&&X(Z)}),!J&&(!Object.keys(Y).length||Object.keys(K).length)){setTimeout(I,100);return}else this._connecting=!1,this._connected=!0;if(this._chunk){try{this.send(this._chunk)}catch(Q){return this.destroy(errCode(Q,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const Z=this._cb;this._cb=null,Z(null)}typeof this._channel.bufferedAmountLowThreshold!="number"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};I()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT$1||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(I=>{this._pc.removeTrack(I),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(I){this.destroyed||(I.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:I.candidate.candidate,sdpMLineIndex:I.candidate.sdpMLineIndex,sdpMid:I.candidate.sdpMid}}):!I.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),I.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(I){if(this.destroyed)return;let U=I.data;U instanceof ArrayBuffer&&(U=Buffer$1.from(U)),this.push(U)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const I=this._cb;this._cb=null,I(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(I){this.destroyed||I.streams.forEach(U=>{this._debug("on track"),this.emit("track",I.track,U),this._remoteTracks.push({track:I.track,stream:U}),!this._remoteStreams.some(q=>q.id===U.id)&&(this._remoteStreams.push(U),queueMicrotask$1(()=>{this._debug("on stream"),this.emit("stream",U)}))})}_debug(){const I=[].slice.call(arguments);I[0]="["+this._id+"] "+I[0],debug.apply(null,I)}};Peer$1.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer$1.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer$1.channelConfig={};var ConnectionState$1;(function($){$[$.INVALID=0]="INVALID",$[$.CONNECTING=1]="CONNECTING",$[$.CONNECTED=2]="CONNECTED",$[$.CLOSED=3]="CLOSED"})(ConnectionState$1||(ConnectionState$1={}));var emitterComponent=Emitter$1;function Emitter$1($){if($)return mixin($)}function mixin($){for(var I in Emitter$1.prototype)$[I]=Emitter$1.prototype[I];return $}Emitter$1.prototype.on=Emitter$1.prototype.addEventListener=function($,I){return this._callbacks=this._callbacks||{},(this._callbacks[$]=this._callbacks[$]||[]).push(I),this},Emitter$1.prototype.once=function($,I){var U=this;this._callbacks=this._callbacks||{};function q(){U.off($,q),I.apply(this,arguments)}return q.fn=I,this.on($,q),this},Emitter$1.prototype.off=Emitter$1.prototype.removeListener=Emitter$1.prototype.removeAllListeners=Emitter$1.prototype.removeEventListener=function($,I){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var U=this._callbacks[$];if(!U)return this;if(arguments.length==1)return delete this._callbacks[$],this;for(var q,G=0;G<U.length;G++)if(q=U[G],q===I||q.fn===I){U.splice(G,1);break}return this},Emitter$1.prototype.emit=function($){this._callbacks=this._callbacks||{};var I=[].slice.call(arguments,1),U=this._callbacks[$];if(U){U=U.slice(0);for(var q=0,G=U.length;q<G;++q)U[q].apply(this,I)}return this},Emitter$1.prototype.listeners=function($){return this._callbacks=this._callbacks||{},this._callbacks[$]||[]},Emitter$1.prototype.hasListeners=function($){return!!this.listeners($).length};var Emitter=emitterComponent;function Stream(){Emitter.call(this)}Stream.prototype=new Emitter;var stream=Stream;Stream.Stream=Stream,Stream.prototype.pipe=function($,I){var U=this;function q(Q){$.writable&&$.write(Q)===!1&&U.pause&&U.pause()}U.on("data",q);function G(){U.readable&&U.resume&&U.resume()}$.on("drain",G),!$._isStdio&&(!I||I.end!==!1)&&(U.on("end",Y),U.on("close",J));var K=!1;function Y(){K||(K=!0,$.end())}function J(){K||(K=!0,typeof $.destroy=="function"&&$.destroy())}function X(Q){if(Z(),!this.hasListeners("error"))throw Q}U.on("error",X),$.on("error",X);function Z(){U.off("data",q),$.off("drain",G),U.off("end",Y),U.off("close",J),U.off("error",X),$.off("error",X),U.off("end",Z),U.off("close",Z),$.off("end",Z),$.off("close",Z)}return U.on("end",Z),U.on("close",Z),$.on("end",Z),$.on("close",Z),$.emit("pipe",U),$};var encode_1=encode,MSB$1=128,REST$1=127,MSBALL=~REST$1,INT=Math.pow(2,31);function encode($,I,U){if(Number.MAX_SAFE_INTEGER&&$>Number.MAX_SAFE_INTEGER)throw encode.bytes=0,new RangeError("Could not encode varint");I=I||[],U=U||0;for(var q=U;$>=INT;)I[U++]=$&255|MSB$1,$/=128;for(;$&MSBALL;)I[U++]=$&255|MSB$1,$>>>=7;return I[U]=$|0,encode.bytes=U-q+1,I}var decode=read,MSB=128,REST=127;function read($,q){var U=0,q=q||0,G=0,K=q,Y,J=$.length;do{if(K>=J||G>49)throw read.bytes=0,new RangeError("Could not decode varint");Y=$[K++],U+=G<28?(Y&REST)<<G:(Y&REST)*Math.pow(2,G),G+=7}while(Y>=MSB);return read.bytes=K-q,U}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length=function($){return $<N1?1:$<N2?2:$<N3?3:$<N4?4:$<N5?5:$<N6?6:$<N7?7:$<N8?8:$<N9?9:10},varint={encode:encode_1,decode,encodingLength:length},__dxlog_file$4="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/control-extension.ts",HEARTBEAT_RTT_WARN_THRESH=1e4,ControlExtension=class{constructor($,I,U){this.opts=$,this.localPeerId=I,this.remotePeerId=U,this._ctx=new Context({onError:q=>{this._extensionContext.close(q)}}),this.onExtensionRegistered=new Callback}async registerExtension($){await this._rpc.rpc.Control.registerExtension({name:$})}async onOpen($){this._extensionContext=$,this._rpc=createProtoRpcPeer({requested:{Control:protocols.schema.getService("dxos.mesh.teleport.control.ControlService")},exposed:{Control:protocols.schema.getService("dxos.mesh.teleport.control.ControlService")},handlers:{Control:{registerExtension:async I=>{this.onExtensionRegistered.call(I.name)},heartbeat:async I=>(log$2("received heartbeat request",{ts:I.requestTimestamp,localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:66,S:this,C:(U,q)=>U(...q)}),{requestTimestamp:I.requestTimestamp})}},port:await $.createPort("rpc",{contentType:'application/x-protobuf; messageType="dxos.rpc.Message"'}),timeout:this.opts.heartbeatTimeout}),await this._rpc.open(),scheduleTaskInterval(this._ctx,async()=>{const I=new Date;try{const U=await asyncTimeout(this._rpc.rpc.Control.heartbeat({requestTimestamp:I}),this.opts.heartbeatTimeout),q=Date.now();U.requestTimestamp instanceof Date&&(q-U.requestTimestamp.getTime()>(HEARTBEAT_RTT_WARN_THRESH<this.opts.heartbeatTimeout?HEARTBEAT_RTT_WARN_THRESH:this.opts.heartbeatTimeout/2)?log$2.warn(`heartbeat RTT for Teleport > ${HEARTBEAT_RTT_WARN_THRESH/1e3}s`,{rtt:q-U.requestTimestamp.getTime(),localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:103,S:this,C:(G,K)=>G(...K)}):log$2("heartbeat RTT",{rtt:q-U.requestTimestamp.getTime(),localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:109,S:this,C:(G,K)=>G(...K)}))}catch(U){const q=Date.now();if(U instanceof protocols.RpcClosedError){log$2("ignoring RpcClosedError in heartbeat",void 0,{F:__dxlog_file$4,L:119,S:this,C:(G,K)=>G(...K)});return}U instanceof TimeoutError?(log$2("timeout waiting for heartbeat response",{err:U,delay:q-I.getTime()},{F:__dxlog_file$4,L:123,S:this,C:(G,K)=>G(...K)}),this.opts.onTimeout(U)):(log$2.info("other error waiting for heartbeat response",{err:U,delay:q-I.getTime()},{F:__dxlog_file$4,L:126,S:this,C:(G,K)=>G(...K)}),this.opts.onTimeout(U))}},this.opts.heartbeatInterval)}async onClose($){await this._ctx.dispose(),await this._rpc.close()}async onAbort($){await this._ctx.dispose(),await this._rpc.abort()}},__dxlog_file2$3="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/framer.ts",FRAME_LENGTH_SIZE=2,Framer=class{constructor(){this._messageCb=void 0,this._subscribeCb=void 0,this._buffer=void 0,this._sendCallbacks=[],this._bytesSent=0,this._bytesReceived=0,this._writable=!0,this.drain=new Event$1,this._stream=new readableBrowserExports.Duplex({objectMode:!1,read:()=>{this._processResponseQueue()},write:($,I,U)=>{invariant(!this._subscribeCb,"Internal Framer bug. Concurrent writes detected.",{F:__dxlog_file2$3,L:40,S:this,A:["!this._subscribeCb","'Internal Framer bug. Concurrent writes detected.'"]}),this._bytesReceived+=$.length,this._buffer&&this._buffer.length>0?this._buffer=export_Buffer.concat([this._buffer,$]):this._buffer=$,this._messageCb?(this._popFrames(),U()):this._subscribeCb=()=>{this._popFrames(),this._subscribeCb=void 0,U()}}}),this.port={send:$=>new Promise(I=>{const U=encodeFrame($);this._bytesSent+=U.length,this._writable=this._stream.push(U),this._writable?I():this._sendCallbacks.push(I)}),subscribe:$=>{var I;return invariant(!this._messageCb,"Rpc port already has a message listener.",{F:__dxlog_file2$3,L:79,S:this,A:["!this._messageCb","'Rpc port already has a message listener.'"]}),this._messageCb=$,(I=this._subscribeCb)==null||I.call(this),()=>{this._messageCb=void 0}}}}get stream(){return this._stream}get bytesSent(){return this._bytesSent}get bytesReceived(){return this._bytesReceived}get writable(){return this._writable}_processResponseQueue(){const $=this._sendCallbacks;this._sendCallbacks=[],this._writable=!0,this.drain.emit(),$.forEach(I=>I())}_popFrames(){let $=0;for(;$<this._buffer.length;){const I=decodeFrame(this._buffer,$);if(!I)break;$+=I.bytesConsumed,this._messageCb(I.payload)}$<this._buffer.length?this._buffer=this._buffer.subarray($):this._buffer=void 0}destroy(){this._stream.readableLength>0&&log$2.info("framer destroyed while there are still read bytes in the buffer.",void 0,{F:__dxlog_file2$3,L:140,S:this,C:($,I)=>$(...I)}),this._stream.writableLength>0&&log$2.warn("framer destroyed while there are still write bytes in the buffer.",void 0,{F:__dxlog_file2$3,L:143,S:this,C:($,I)=>$(...I)}),this._stream.destroy()}},decodeFrame=($,I)=>{if($.length<I+FRAME_LENGTH_SIZE)return;const U=$.readUInt16BE(I),q=FRAME_LENGTH_SIZE+U;return $.length<I+q?void 0:{payload:$.subarray(I+FRAME_LENGTH_SIZE,I+q),bytesConsumed:q}},encodeFrame=$=>{const I=export_Buffer.allocUnsafe(FRAME_LENGTH_SIZE+$.length);return I.writeUInt16BE($.length,0),I.set($,FRAME_LENGTH_SIZE),I},__dxlog_file3$1="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/balancer.ts",MAX_CHUNK_SIZE=8192,Balancer=class{constructor($){this._sysChannelId=$,this._lastCallerIndex=0,this._channels=[],this._framer=new Framer,this._sendBuffers=new Map,this._receiveBuffers=new Map,this._sending=!1,this.incomingData=new Event$1,this.stream=this._framer.stream,this._channels.push($),this._framer.port.subscribe(this._processIncomingMessage.bind(this))}get bytesSent(){return this._framer.bytesSent}get bytesReceived(){return this._framer.bytesReceived}get buffersCount(){return this._sendBuffers.size}addChannel($){this._channels.push($)}pushData($,I,U){this._enqueueChunk($,I,U),this._sendChunks().catch(q=>log$2.catch(q,void 0,{F:__dxlog_file3$1,L:75,S:this,C:(G,K)=>G(...K)}))}destroy(){this._sendBuffers.size!==0&&log$2.info("destroying balancer with pending calls",void 0,{F:__dxlog_file3$1,L:80,S:this,C:($,I)=>$(...I)}),this._sendBuffers.clear(),this._framer.destroy()}_processIncomingMessage($){const{channelId:I,dataLength:U,chunk:q}=decodeChunk($,G=>!this._receiveBuffers.has(G));if(!this._receiveBuffers.has(I))q.length<U?this._receiveBuffers.set(I,{buffer:export_Buffer.from(q),msgLength:U}):this.incomingData.emit(q);else{const G=this._receiveBuffers.get(I);if(G.buffer=export_Buffer.concat([G.buffer,q]),G.buffer.length<G.msgLength)return;const K=G.buffer;this._receiveBuffers.delete(I),this.incomingData.emit(K)}}_getNextCallerId(){if(this._sendBuffers.has(this._sysChannelId))return this._sysChannelId;const $=this._lastCallerIndex;return this._lastCallerIndex=(this._lastCallerIndex+1)%this._channels.length,this._channels[$]}_enqueueChunk($,I,U){if(!this._channels.includes(U))throw new Error(`Unknown channel ${U}`);this._sendBuffers.has(U)||this._sendBuffers.set(U,[]);const q=this._sendBuffers.get(U),G=[];for(let K=0;K<$.length;K+=MAX_CHUNK_SIZE)G.push($.subarray(K,K+MAX_CHUNK_SIZE));G.forEach((K,Y)=>{const J=encodeChunk({chunk:K,channelId:U,dataLength:Y===0?$.length:void 0});q.push({msg:J,trigger:Y===G.length-1?I:void 0})})}_getNextChunk(){let $;for(;this._sendBuffers.size>0;){const I=this._getNextCallerId(),U=this._sendBuffers.get(I);if(U&&($=U.shift(),!!$))return U.length===0&&this._sendBuffers.delete(I),$}return null}async _sendChunks(){var I,U;if(this._sending)return;this._sending=!0;let $;for($=this._getNextChunk();$;){this._framer.writable||(log$2("PAUSE for drain",void 0,{F:__dxlog_file3$1,L:179,S:this,C:(q,G)=>q(...G)}),await this._framer.drain.waitForCount(1),log$2("RESUME for drain",void 0,{F:__dxlog_file3$1,L:181,S:this,C:(q,G)=>q(...G)}));try{await this._framer.port.send($.msg),(I=$.trigger)==null||I.wake()}catch(q){log$2("Error sending chunk",{err:q},{F:__dxlog_file3$1,L:187,S:this,C:(G,K)=>G(...K)}),(U=$.trigger)==null||U.throw(q)}$=this._getNextChunk()}invariant(this._sendBuffers.size===0,"sendBuffers not empty",{F:__dxlog_file3$1,L:192,S:this,A:["this._sendBuffers.size === 0","'sendBuffers not empty'"]}),this._sending=!1}},encodeChunk=({channelId:$,dataLength:I,chunk:U})=>{const q=varint.encodingLength($),G=I?varint.encodingLength(I):0,K=export_Buffer.allocUnsafe(q+G+U.length);return varint.encode($,K),I&&varint.encode(I,K,q),K.set(U,q+G),K},decodeChunk=($,I)=>{const U=varint.decode($);let q,G=varint.decode.bytes;I(U)&&(q=varint.decode($,G),G+=varint.decode.bytes);const K=$.subarray(G);return{channelId:U,dataLength:q,chunk:K}};function _ts_decorate$3($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4$2="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/muxer.ts",Command=protocols.schema.getCodecForType("dxos.mesh.muxer.Command"),DEFAULT_SEND_COMMAND_TIMEOUT=6e4,DESTROY_COMMAND_SEND_TIMEOUT=5e3,STATS_INTERVAL=1e3,MAX_SAFE_FRAME_SIZE=1e6,SYSTEM_CHANNEL_ID=0,GRACEFUL_CLOSE_TIMEOUT=3e3,Muxer=class{constructor(){this._balancer=new Balancer(SYSTEM_CHANNEL_ID),this._channelsByLocalId=new Map,this._channelsByTag=new Map,this._ctx=new Context,this._nextId=1,this._closing=!1,this._destroying=!1,this._disposed=!1,this._lastStats=void 0,this._lastChannelStats=new Map,this.afterClosed=new Event$1,this.statsUpdated=new Event$1,this.stream=this._balancer.stream,this._balancer.incomingData.on(async $=>{await this._handleCommand(Command.decode($))})}setSessionId($){this._sessionId=$}get sessionIdString(){return this._sessionId?this._sessionId.truncate():"none"}async createStream($,I={}){const U=this._getOrCreateStream({tag:$,contentType:I.contentType});invariant(!U.push,`Channel already open: ${$}`,{F:__dxlog_file4$2,L:151,S:this,A:["!channel.push","`Channel already open: ${tag}`"]});const q=new readableBrowserExports.Duplex({write:(G,K,Y)=>{this._sendData(U,G).then(()=>Y()).catch(Y)},read:()=>{}});U.push=G=>{U.stats.bytesReceived+=G.length,q.push(G)},U.destroy=G=>{G&&q.listeners("error").length>0?q.destroy(G):q.destroy()};try{await this._sendCommand({openChannel:{id:U.id,tag:U.tag,contentType:U.contentType}},SYSTEM_CHANNEL_ID)}catch(G){throw this._destroyChannel(U,G),G}return q}async createPort($,I={}){const U=this._getOrCreateStream({tag:$,contentType:I.contentType});invariant(!U.push,`Channel already open: ${$}`,{F:__dxlog_file4$2,L:211,S:this,A:["!channel.push","`Channel already open: ${tag}`"]});let q=[],G;U.push=Y=>{U.stats.bytesReceived+=Y.length,G?G(Y):q.push(Y)};const K={send:async(Y,J)=>{await this._sendData(U,Y,J)},subscribe:Y=>{invariant(!G,"Only one subscriber is allowed",{F:__dxlog_file4$2,L:233,S:this,A:["!callback","'Only one subscriber is allowed'"]}),G=Y;for(const J of q)Y(J);q=[]}};try{await this._sendCommand({openChannel:{id:U.id,tag:U.tag,contentType:U.contentType}},SYSTEM_CHANNEL_ID)}catch(Y){throw this._destroyChannel(U,Y),Y}return K}async close($){if(this._destroying){log$2("already destroying, ignoring graceful close request",void 0,{F:__dxlog_file4$2,L:266,S:this,C:(I,U)=>I(...U)});return}if(this._closing){log$2("already closing, ignoring graceful close request",void 0,{F:__dxlog_file4$2,L:270,S:this,C:(I,U)=>I(...U)});return}this._closing=!0,await this._sendCommand({close:{error:$==null?void 0:$.message}},SYSTEM_CHANNEL_ID,DESTROY_COMMAND_SEND_TIMEOUT).catch(async I=>{log$2("error sending close command",{err:I},{F:__dxlog_file4$2,L:285,S:this,C:(U,q)=>U(...q)}),await this._dispose(I)}),await asyncTimeout(this._dispose($),GRACEFUL_CLOSE_TIMEOUT,new protocols.TimeoutError("gracefully closing muxer"))}async destroy($){if(this._destroying){log$2("already destroying, ignoring destroy request",void 0,{F:__dxlog_file4$2,L:298,S:this,C:(I,U)=>I(...U)});return}this._destroying=!0,this._ctx.dispose(),this._closing?(log$2("destroy cancelling graceful close",void 0,{F:__dxlog_file4$2,L:304,S:this,C:(I,U)=>I(...U)}),this._closing=!1):await this._sendCommand({close:{error:$==null?void 0:$.message}},SYSTEM_CHANNEL_ID).catch(async I=>{log$2("error sending courtesy close command",{err:I},{F:__dxlog_file4$2,L:317,S:this,C:(U,q)=>U(...q)})}),this._dispose($).catch(I=>{log$2("error disposing after destroy",{err:I},{F:__dxlog_file4$2,L:322,S:this,C:(U,q)=>U(...q)})})}async _dispose($){var I;if(this._disposed){log$2("already destroyed, ignoring dispose request",void 0,{F:__dxlog_file4$2,L:330,S:this,C:(U,q)=>U(...q)});return}this._ctx.dispose(),await this._balancer.destroy();for(const U of this._channelsByTag.values())(I=U.destroy)==null||I.call(U,$);this._disposed=!0,await this._emitStats(),this.afterClosed.emit($),this._channelsByLocalId.clear(),this._channelsByTag.clear()}async _handleCommand($){if(this._disposed){log$2.warn("Received command after disposed",{cmd:$},{F:__dxlog_file4$2,L:353,S:this,C:(I,U)=>I(...U)});return}if($.close){this._closing?log$2("received close from peer, already closing",void 0,{F:__dxlog_file4$2,L:362,S:this,C:(I,U)=>I(...U)}):(log$2("received peer close, initiating my own graceful close",void 0,{F:__dxlog_file4$2,L:359,S:this,C:(I,U)=>I(...U)}),await this.close(new Error("received peer close")));return}if($.openChannel){const I=this._getOrCreateStream({tag:$.openChannel.tag,contentType:$.openChannel.contentType});I.remoteId=$.openChannel.id;for(const U of I.buffer)await this._sendCommand({data:{channelId:I.remoteId,data:U}},I.id);I.buffer=[]}else if($.data){const I=this._channelsByLocalId.get($.data.channelId)??failUndefined();if(!I.push){log$2.warn("Received data for channel before it was opened",{tag:I.tag},{F:__dxlog_file4$2,L:391,S:this,C:(U,q)=>U(...q)});return}I.push($.data.data)}}async _sendCommand($,I=-1,U=DEFAULT_SEND_COMMAND_TIMEOUT){if(this._disposed){log$2.info("ignoring sendCommand after disposed",{cmd:$},{F:__dxlog_file4$2,L:400,S:this,C:(q,G)=>q(...G)});return}try{const q=new Trigger;this._balancer.pushData(Command.encode($),q,I),await q.wait({timeout:U})}catch(q){await this.destroy(q)}}_getOrCreateStream($){this._channelsByTag.size===0&&scheduleTaskInterval(this._ctx,async()=>this._emitStats(),STATS_INTERVAL);let I=this._channelsByTag.get($.tag);return I||(I={id:this._nextId++,remoteId:null,tag:$.tag,contentType:$.contentType,buffer:[],push:null,destroy:null,stats:{bytesSent:0,bytesReceived:0}},this._channelsByTag.set(I.tag,I),this._channelsByLocalId.set(I.id,I),this._balancer.addChannel(I.id)),I}async _sendData($,I,U){if(I.length>MAX_SAFE_FRAME_SIZE&&log$2.warn("frame size exceeds maximum safe value",{size:I.length,threshold:MAX_SAFE_FRAME_SIZE},{F:__dxlog_file4$2,L:441,S:this,C:(q,G)=>q(...G)}),$.stats.bytesSent+=I.length,$.remoteId===null){$.buffer.push(I);return}await this._sendCommand({data:{channelId:$.remoteId,data:I}},$.id,U)}_destroyChannel($,I){$.destroy&&$.destroy(I),this._channelsByLocalId.delete($.id),this._channelsByTag.delete($.tag)}async _emitStats(){if(this._disposed||this._destroying){if(!this._lastStats)return;const K=this._lastStats;this._lastStats=void 0,K.readBufferSize=0,K.writeBufferSize=0;for(const Y of K.channels)Y.writeBufferSize=0;this.statsUpdated.emit(K),this._lastChannelStats.clear();return}const $=this._balancer.bytesSent,I=this._balancer.bytesReceived,U=Date.now(),q=this._lastStats?(U-this._lastStats.timestamp)/1e3:0,G=(K,Y)=>Y?{bytesSentRate:q?(K.bytesSent-Y.bytesSent)/q:void 0,bytesReceivedRate:q?(K.bytesReceived-Y.bytesReceived)/q:void 0}:{};this._lastStats={timestamp:U,channels:Array.from(this._channelsByTag.values()).map(K=>{const Y={id:K.id,tag:K.tag,contentType:K.contentType,writeBufferSize:K.buffer.length,bytesSent:K.stats.bytesSent,bytesReceived:K.stats.bytesReceived,...G(K.stats,this._lastChannelStats.get(K.id))};return this._lastChannelStats.set(K.id,Y),Y}),bytesSent:$,bytesReceived:I,...G({bytesSent:$,bytesReceived:I},this._lastStats),readBufferSize:this._balancer.stream.readableLength,writeBufferSize:this._balancer.stream.writableLength},this.statsUpdated.emit(this._lastStats)}};_ts_decorate$3([logInfo],Muxer.prototype,"sessionIdString",null);function _ts_decorate2$2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5$1="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/teleport.ts",CONTROL_HEARTBEAT_INTERVAL=1e4,CONTROL_HEARTBEAT_TIMEOUT=6e4,Teleport=class{constructor({initiator:$,localPeerId:I,remotePeerId:U}){this._ctx=new Context({onError:q=>{this.destroy(q).catch(()=>{log$2.error("Error during destroy",q,{F:__dxlog_file5$1,L:39,S:this,C:(G,K)=>G(...K)})})}}),this._muxer=new Muxer,this._extensions=new Map,this._remoteExtensions=new Set,this._open=!1,this._destroying=!1,this._aborting=!1,invariant(typeof $=="boolean",void 0,{F:__dxlog_file5$1,L:56,S:this,A:["typeof initiator === 'boolean'",""]}),invariant(PublicKey.isPublicKey(I),void 0,{F:__dxlog_file5$1,L:57,S:this,A:["PublicKey.isPublicKey(localPeerId)",""]}),invariant(PublicKey.isPublicKey(U),void 0,{F:__dxlog_file5$1,L:58,S:this,A:["PublicKey.isPublicKey(remotePeerId)",""]}),this.initiator=$,this.localPeerId=I,this.remotePeerId=U,this._control=new ControlExtension({heartbeatInterval:CONTROL_HEARTBEAT_INTERVAL,heartbeatTimeout:CONTROL_HEARTBEAT_TIMEOUT,onTimeout:()=>{this._destroying||this._aborting||(log$2.info("abort teleport due to onTimeout in ControlExtension",void 0,{F:__dxlog_file5$1,L:71,S:this,C:(q,G)=>q(...G)}),this.abort(new protocols.TimeoutError("control extension")).catch(q=>log$2.catch(q,void 0,{F:__dxlog_file5$1,L:72,S:this,C:(G,K)=>G(...K)})))}},this.localPeerId,this.remotePeerId),this._control.onExtensionRegistered.set(async q=>{if(log$2("remote extension",{name:q},{F:__dxlog_file5$1,L:80,S:this,C:(G,K)=>G(...K)}),invariant(!this._remoteExtensions.has(q),"Remote extension already exists",{F:__dxlog_file5$1,L:81,S:this,A:["!this._remoteExtensions.has(name)","'Remote extension already exists'"]}),this._remoteExtensions.add(q),this._extensions.has(q))try{await this._openExtension(q)}catch(G){await this.destroy(G)}}),this._muxer.stream.on("close",async()=>{if(this._destroying||this._aborting){log$2("destroy teleport due to muxer stream close, skipping due to already destroying/aborting",void 0,{F:__dxlog_file5$1,L:97,S:this,C:(q,G)=>q(...G)});return}await this.destroy()}),this._muxer.stream.on("error",async q=>{await this.destroy(q)}),this._muxer.statsUpdated.on(q=>{log$2.trace("dxos.mesh.teleport.stats",{localPeerId:I,remotePeerId:U,bytesSent:q.bytesSent,bytesSentRate:q.bytesSentRate,bytesReceived:q.bytesReceived,bytesReceivedRate:q.bytesReceivedRate,channels:q.channels},{F:__dxlog_file5$1,L:110,S:this,C:(G,K)=>G(...K)})})}get sessionIdString(){return this._sessionId?this._sessionId.truncate():"none"}get stream(){return this._muxer.stream}get stats(){return this._muxer.statsUpdated}async open($=PublicKey.random()){this._sessionId=$,log$2("open",void 0,{F:__dxlog_file5$1,L:144,S:this,C:(I,U)=>I(...U)}),this._setExtension("dxos.mesh.teleport.control",this._control),await this._openExtension("dxos.mesh.teleport.control"),this._open=!0,this._muxer.setSessionId($)}async close($){await this.destroy($)}async abort($){if(!(this._aborting||this._destroying)&&(this._aborting=!0,!this._ctx.disposed)){await this._ctx.dispose();for(const I of this._extensions.values())try{await I.onAbort($)}catch(U){log$2.catch(U,void 0,{F:__dxlog_file5$1,L:173,S:this,C:(q,G)=>q(...G)})}await this._muxer.destroy($)}}async destroy($){if(!(this._destroying||this._aborting)&&(this._destroying=!0,!this._ctx.disposed)){await this._ctx.dispose();for(const I of this._extensions.values())try{await I.onClose($)}catch(U){log$2.catch(U,void 0,{F:__dxlog_file5$1,L:197,S:this,C:(q,G)=>q(...G)})}await this._muxer.close()}}addExtension($,I){if(!this._open)throw new Error("Not open");log$2("addExtension",{name:$},{F:__dxlog_file5$1,L:209,S:this,C:(U,q)=>U(...q)}),this._setExtension($,I),scheduleTask(this._ctx,async()=>{try{await this._control.registerExtension($)}catch(U){if(U instanceof protocols.RpcClosedError)return;throw U}}),this._remoteExtensions.has($)&&scheduleTask(this._ctx,async()=>{await this._openExtension($)})}_setExtension($,I){invariant(!$.includes("/"),"Invalid extension name",{F:__dxlog_file5$1,L:233,S:this,A:["!extensionName.includes('/')","'Invalid extension name'"]}),invariant(!this._extensions.has($),"Extension already exists",{F:__dxlog_file5$1,L:234,S:this,A:["!this._extensions.has(extensionName)","'Extension already exists'"]}),this._extensions.set($,I)}async _openExtension($){log$2("open extension",{extensionName:$},{F:__dxlog_file5$1,L:239,S:this,C:(q,G)=>q(...G)});const I=this._extensions.get($)??failUndefined(),U={initiator:this.initiator,localPeerId:this.localPeerId,remotePeerId:this.remotePeerId,createPort:async(q,G)=>(invariant(!q.includes("/"),"Invalid channel name",{F:__dxlog_file5$1,L:247,S:this,A:["!channelName.includes('/')","'Invalid channel name'"]}),this._muxer.createPort(`${$}/${q}`,G)),createStream:async(q,G)=>(invariant(!q.includes("/"),"Invalid channel name",{F:__dxlog_file5$1,L:251,S:this,A:["!channelName.includes('/')","'Invalid channel name'"]}),this._muxer.createStream(`${$}/${q}`,G)),close:q=>{runInContextAsync(this._ctx,async()=>{await this.close(q)})}};await I.onOpen(U),log$2("extension opened",{extensionName:$},{F:__dxlog_file5$1,L:262,S:this,C:(q,G)=>q(...G)})}};_ts_decorate2$2([logInfo],Teleport.prototype,"sessionIdString",null),_ts_decorate2$2([synchronized],Teleport.prototype,"abort",null),_ts_decorate2$2([synchronized],Teleport.prototype,"destroy",null);var __require=($=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy($,{get:(I,U)=>(typeof require<"u"?require:I)[U]}):$)(function($){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+$+'" is not supported')});function _ts_decorate$2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$3="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection.ts",STARTING_SIGNALLING_DELAY=10,TRANSPORT_CONNECTION_TIMEOUT=1e4,TRANSPORT_STATS_INTERVAL=5e3,MAX_SIGNALLING_DELAY=300,ConnectionState;(function($){$.CREATED="CREATED",$.INITIAL="INITIAL",$.CONNECTING="CONNECTING",$.CONNECTED="CONNECTED",$.CLOSING="CLOSING",$.CLOSED="CLOSED",$.ABORTING="ABORTING",$.ABORTED="ABORTED"})(ConnectionState||(ConnectionState={}));var Connection=class{constructor($,I,U,q,G,K,Y,J,X){this.topic=$,this.ownId=I,this.remoteId=U,this.sessionId=q,this.initiator=G,this._signalMessaging=K,this._protocol=Y,this._transportFactory=J,this._callbacks=X,this._ctx=new Context,this.connectedTimeoutContext=new Context,this._state="CREATED",this._incomingSignalBuffer=[],this._outgoingSignalBuffer=[],this.stateChanged=new Event$1,this.errors=new ErrorStream,this._instanceId=PublicKey.random().toHex(),this.transportStats=new Event$1,this._signalSendTask=new DeferredTask(this._ctx,async()=>{await this._flushSignalBuffer()}),this._signallingDelay=STARTING_SIGNALLING_DELAY,log$2.trace("dxos.mesh.connection.construct",{sessionId:this.sessionId,topic:this.topic,localPeerId:this.ownId,remotePeerId:this.remoteId,initiator:this.initiator},{F:__dxlog_file$3,L:134,S:this,C:(Z,Q)=>Z(...Q)})}get sessionIdString(){return this.sessionId.truncate()}get state(){return this._state}get transport(){return this._transport}get protocol(){return this._protocol}async openConnection(){invariant(this._state==="INITIAL","Invalid state.",{F:__dxlog_file$3,L:164,S:this,A:["this._state === ConnectionState.INITIAL","'Invalid state.'"]}),log$2.trace("dxos.mesh.connection.open-connection",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file$3,L:165,S:this,C:($,I)=>$(...I)}),log$2.trace("dxos.mesh.connection.open",{sessionId:this.sessionId,topic:this.topic,localPeerId:this.ownId,remotePeerId:this.remoteId,initiator:this.initiator},{F:__dxlog_file$3,L:166,S:this,C:($,I)=>$(...I)}),this._changeState("CONNECTING"),this._protocol.open(this.sessionId).catch($=>{this.errors.raise($)}),this._protocol.stream.on("close",()=>{log$2("protocol stream closed",void 0,{F:__dxlog_file$3,L:183,S:this,C:($,I)=>$(...I)}),this.close(new protocols.ProtocolError("protocol stream closed")).catch($=>this.errors.raise($))}),scheduleTask(this.connectedTimeoutContext,async()=>{log$2.info(`timeout waiting ${TRANSPORT_CONNECTION_TIMEOUT/1e3}s for transport to connect, aborting`,void 0,{F:__dxlog_file$3,L:190,S:this,C:($,I)=>$(...I)}),await this.abort(new protocols.TimeoutError(`${TRANSPORT_CONNECTION_TIMEOUT/1e3}s for transport to connect`)).catch($=>this.errors.raise($))},TRANSPORT_CONNECTION_TIMEOUT),invariant(!this._transport,void 0,{F:__dxlog_file$3,L:198,S:this,A:["!this._transport",""]}),this._transport=this._transportFactory.createTransport({initiator:this.initiator,stream:this._protocol.stream,sendSignal:async $=>this._sendSignal($),sessionId:this.sessionId}),await this._transport.open(),this._transport.connected.once(async()=>{var $,I;this._changeState("CONNECTED"),await this.connectedTimeoutContext.dispose(),(I=($=this._callbacks)==null?void 0:$.onConnected)==null||I.call($),scheduleTaskInterval(this._ctx,async()=>this._emitTransportStats(),TRANSPORT_STATS_INTERVAL)}),this._transport.closed.once(()=>{this._transport=void 0,log$2("abort triggered by transport close",void 0,{F:__dxlog_file$3,L:218,S:this,C:($,I)=>$(...I)}),this.abort().catch($=>this.errors.raise($))}),this._transport.errors.handle(async $=>{log$2("transport error:",{err:$},{F:__dxlog_file$3,L:223,S:this,C:(I,U)=>I(...U)}),this.closeReason||(this.closeReason=$==null?void 0:$.message),$ instanceof protocols.ConnectionResetError?(log$2.info("aborting due to transport ConnectionResetError",void 0,{F:__dxlog_file$3,L:230,S:this,C:(I,U)=>I(...U)}),this.abort().catch(I=>this.errors.raise(I))):$ instanceof protocols.ConnectivityError?(log$2.info("aborting due to transport ConnectivityError",void 0,{F:__dxlog_file$3,L:233,S:this,C:(I,U)=>I(...U)}),this.abort().catch(I=>this.errors.raise(I))):$ instanceof protocols.UnknownProtocolError&&log$2.warn("unsure what to do with UnknownProtocolError, will keep on truckin",{err:$},{F:__dxlog_file$3,L:236,S:this,C:(I,U)=>I(...U)}),this._state!=="CLOSED"&&this._state!=="CLOSING"&&(await this.connectedTimeoutContext.dispose(),this.errors.raise($))});for(const $ of this._incomingSignalBuffer)this._transport.onSignal($);this._incomingSignalBuffer=[],log$2.trace("dxos.mesh.connection.open-connection",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file$3,L:252,S:this,C:($,I)=>$(...I)})}async abort($){var I,U,q;if(log$2("aborting...",{err:$},{F:__dxlog_file$3,L:259,S:this,C:(G,K)=>G(...K)}),this._state==="CLOSED"||this._state==="ABORTED"){log$2(`abort ignored: already ${this._state}`,this.closeReason,{F:__dxlog_file$3,L:261,S:this,C:(G,K)=>G(...K)});return}await this.connectedTimeoutContext.dispose(),this._changeState("ABORTING"),this.closeReason||(this.closeReason=$==null?void 0:$.message),await this._ctx.dispose();try{log$2("aborting protocol... ",void 0,{F:__dxlog_file$3,L:275,S:this,C:(G,K)=>G(...K)}),await this._protocol.abort()}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:278,S:this,C:(K,Y)=>K(...Y)})}try{await((I=this._transport)==null?void 0:I.close())}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:285,S:this,C:(K,Y)=>K(...Y)})}try{(q=(U=this._callbacks)==null?void 0:U.onClosed)==null||q.call(U,$)}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:291,S:this,C:(K,Y)=>K(...Y)})}this._changeState("ABORTED")}async close($){var U,q,G,K;if(this.closeReason?this.closeReason+=`; ${$==null?void 0:$.message}`:this.closeReason=$==null?void 0:$.message,this._state==="CLOSED"||this._state==="ABORTING"||this._state==="ABORTED")return;const I=this._state;if(this._changeState("CLOSING"),await this.connectedTimeoutContext.dispose(),await this._ctx.dispose(),log$2("closing...",{peerId:this.ownId},{F:__dxlog_file$3,L:316,S:this,C:(Y,J)=>Y(...J)}),I==="CONNECTED"){try{await this._protocol.close()}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:323,S:this,C:(J,X)=>J(...X)})}try{await((U=this._transport)==null?void 0:U.close())}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:330,S:this,C:(J,X)=>J(...X)})}}else{log$2.info(`graceful close requested when we were in ${I} state? aborting`,void 0,{F:__dxlog_file$3,L:333,S:this,C:(Y,J)=>Y(...J)});try{await this._protocol.abort()}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:337,S:this,C:(J,X)=>J(...X)})}try{await((q=this._transport)==null?void 0:q.close())}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:342,S:this,C:(J,X)=>J(...X)})}}log$2("closed",{peerId:this.ownId},{F:__dxlog_file$3,L:346,S:this,C:(Y,J)=>Y(...J)}),this._changeState("CLOSED"),(K=(G=this._callbacks)==null?void 0:G.onClosed)==null||K.call(G,$)}_sendSignal($){this._outgoingSignalBuffer.push($),this._signalSendTask.schedule()}async _flushSignalBuffer(){var $;if(this._outgoingSignalBuffer.length!==0)try{await cancelWithContext(this._ctx,sleep(this._signallingDelay)),this._signallingDelay=Math.min(this._signallingDelay*2,MAX_SIGNALLING_DELAY);const I=[...this._outgoingSignalBuffer];this._outgoingSignalBuffer.length=0,await this._signalMessaging.signal({author:this.ownId,recipient:this.remoteId,sessionId:this.sessionId,topic:this.topic,data:{signalBatch:{signals:I}}})}catch(I){if(I instanceof protocols.CancelledError||I instanceof Error&&(($=I.message)!=null&&$.includes("CANCELLED")))return;log$2.info("signal message failed to deliver",{err:I},{F:__dxlog_file$3,L:384,S:this,C:(U,q)=>U(...q)}),await this.close(new protocols.ConnectivityError("signal message failed to deliver",I))}}async signal($){var U,q;if(invariant($.sessionId,void 0,{F:__dxlog_file$3,L:393,S:this,A:["msg.sessionId",""]}),!$.sessionId.equals(this.sessionId)){log$2("dropping signal for incorrect session id",void 0,{F:__dxlog_file$3,L:395,S:this,C:(G,K)=>G(...K)});return}invariant($.data.signal||$.data.signalBatch,void 0,{F:__dxlog_file$3,L:398,S:this,A:["msg.data.signal || msg.data.signalBatch",""]}),invariant((U=$.author)==null?void 0:U.equals(this.remoteId),void 0,{F:__dxlog_file$3,L:399,S:this,A:["msg.author?.equals(this.remoteId)",""]}),invariant((q=$.recipient)==null?void 0:q.equals(this.ownId),void 0,{F:__dxlog_file$3,L:400,S:this,A:["msg.recipient?.equals(this.ownId)",""]});const I=$.data.signalBatch?$.data.signalBatch.signals??[]:[$.data.signal];for(const G of I)G&&(["CREATED","INITIAL"].includes(this.state)?(log$2("buffered signal",{peerId:this.ownId,remoteId:this.remoteId,msg:$.data},{F:__dxlog_file$3,L:409,S:this,C:(K,Y)=>K(...Y)}),this._incomingSignalBuffer.push(G)):(invariant(this._transport,"Connection not ready to accept signals.",{F:__dxlog_file$3,L:412,S:this,A:["this._transport","'Connection not ready to accept signals.'"]}),log$2("received signal",{peerId:this.ownId,remoteId:this.remoteId,msg:$.data},{F:__dxlog_file$3,L:413,S:this,C:(K,Y)=>K(...Y)}),await this._transport.onSignal(G)))}initiate(){this._changeState("INITIAL")}_changeState($){log$2("stateChanged",{from:this._state,to:$,peerId:this.ownId},{F:__dxlog_file$3,L:424,S:this,C:(I,U)=>I(...U)}),invariant($!==this._state,"Already in this state.",{F:__dxlog_file$3,L:425,S:this,A:["state !== this._state","'Already in this state.'"]}),this._state=$,this.stateChanged.emit($)}async _emitTransportStats(){var I;const $=await((I=this.transport)==null?void 0:I.getStats());$&&this.transportStats.emit($)}};_ts_decorate$2([logInfo],Connection.prototype,"sessionIdString",null),_ts_decorate$2([synchronized],Connection.prototype,"abort",null),_ts_decorate$2([synchronized],Connection.prototype,"close",null);var __dxlog_file2$2="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/swarm-messenger.ts",SwarmMessage=protocols.schema.getCodecForType("dxos.mesh.swarm.SwarmMessage"),SwarmMessenger=class{constructor({sendMessage:$,onSignal:I,onOffer:U,topic:q}){this._ctx=new Context,this._offerRecords=new ComplexMap(G=>G.toHex()),this._sendMessage=$,this._onSignal=I,this._onOffer=U,this._topic=q}async receiveMessage({author:$,recipient:I,payload:U}){var G,K,Y,J;if(U.type_url!=="dxos.mesh.swarm.SwarmMessage")return;const q=SwarmMessage.decode(U.value);this._topic.equals(q.topic)&&(log$2("received",{from:$,to:I,msg:q},{F:__dxlog_file2$2,L:69,S:this,C:(X,Z)=>X(...Z)}),(G=q.data)!=null&&G.offer?await this._handleOffer({author:$,recipient:I,message:q}):(K=q.data)!=null&&K.answer?await this._resolveAnswers(q):(Y=q.data)!=null&&Y.signal?await this._handleSignal({author:$,recipient:I,message:q}):(J=q.data)!=null&&J.signalBatch?await this._handleSignal({author:$,recipient:I,message:q}):log$2.warn("unknown message",{message:q},{F:__dxlog_file2$2,L:80,S:this,C:(X,Z)=>X(...Z)}))}async signal($){var I,U;invariant(((I=$.data)==null?void 0:I.signal)||((U=$.data)==null?void 0:U.signalBatch),"Invalid message",{F:__dxlog_file2$2,L:85,S:this,A:["message.data?.signal || message.data?.signalBatch","'Invalid message'"]}),await this._sendReliableMessage({author:$.author,recipient:$.recipient,message:$})}async offer($){const I={...$,messageId:PublicKey.random()};return new Promise((U,q)=>{this._offerRecords.set(I.messageId,{resolve:U}),this._sendReliableMessage({author:$.author,recipient:$.recipient,message:I}).catch(G=>q(G))})}async _sendReliableMessage({author:$,recipient:I,message:U}){const q={...U,messageId:U.messageId??PublicKey.random()};log$2("sending",{from:$,to:I,msg:q},{F:__dxlog_file2$2,L:123,S:this,C:(G,K)=>G(...K)}),await this._sendMessage({author:$,recipient:I,payload:{type_url:"dxos.mesh.swarm.SwarmMessage",value:SwarmMessage.encode(q)}})}async _resolveAnswers($){var U,q,G;invariant((q=(U=$.data)==null?void 0:U.answer)==null?void 0:q.offerMessageId,"No offerMessageId",{F:__dxlog_file2$2,L:135,S:this,A:["message.data?.answer?.offerMessageId","'No offerMessageId'"]});const I=this._offerRecords.get($.data.answer.offerMessageId);I&&(this._offerRecords.delete($.data.answer.offerMessageId),invariant((G=$.data)==null?void 0:G.answer,"No answer",{F:__dxlog_file2$2,L:139,S:this,A:["message.data?.answer","'No answer'"]}),log$2("resolving",{answer:$.data.answer},{F:__dxlog_file2$2,L:140,S:this,C:(K,Y)=>K(...Y)}),I.resolve($.data.answer))}async _handleOffer({author:$,recipient:I,message:U}){invariant(U.data.offer,"No offer",{F:__dxlog_file2$2,L:154,S:this,A:["message.data.offer","'No offer'"]});const q={author:$,recipient:I,...U,data:{offer:U.data.offer}},G=await this._onOffer(q);G.offerMessageId=U.messageId;try{await this._sendReliableMessage({author:I,recipient:$,message:{topic:U.topic,sessionId:U.sessionId,data:{answer:G}}})}catch(K){K instanceof protocols.TimeoutError?log$2.info("timeout sending answer to offer",{err:K},{F:__dxlog_file2$2,L:175,S:this,C:(Y,J)=>Y(...J)}):log$2.info("error sending answer to offer",{err:K},{F:__dxlog_file2$2,L:177,S:this,C:(Y,J)=>Y(...J)})}}async _handleSignal({author:$,recipient:I,message:U}){invariant(U.messageId,void 0,{F:__dxlog_file2$2,L:191,S:this,A:["message.messageId",""]}),invariant(U.data.signal||U.data.signalBatch,"Invalid message",{F:__dxlog_file2$2,L:192,S:this,A:["message.data.signal || message.data.signalBatch","'Invalid message'"]});const q={author:$,recipient:I,...U,data:{signal:U.data.signal,signalBatch:U.data.signalBatch}};await this._onSignal(q)}};function _ts_decorate2$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file3="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/peer.ts",ConnectionDisplacedError=class extends protocols.SystemError{constructor(){super("Connection displaced by remote initiator.")}},CONNECTION_COUNTS_STABLE_AFTER=5e3,Peer=class{constructor($,I,U,q,G,K,Y,J){this.id=$,this.topic=I,this.localPeerId=U,this._signalMessaging=q,this._protocolProvider=G,this._transportFactory=K,this._connectionLimiter=Y,this._callbacks=J,this._availableAfter=0,this.availableToConnect=!0,this._ctx=new Context,this.advertizing=!1,this.initiating=!1,this.connectionDisplaced=new Event$1}async onOffer($){var U;const I=$.author;if(this.connection&&![ConnectionState.CREATED,ConnectionState.INITIAL,ConnectionState.CONNECTING].includes(this.connection.state))return log$2.info(`received offer when connection already in ${this.connection.state} state`,void 0,{F:__dxlog_file3,L:114,S:this,C:(q,G)=>q(...G)}),{accept:!1};if(this.connection||this.initiating)if(I.toHex()<this.localPeerId.toHex())log$2("close local connection",{localPeerId:this.id,topic:this.topic,remotePeerId:this.localPeerId,sessionId:(U=this.connection)==null?void 0:U.sessionId},{F:__dxlog_file3,L:123,S:this,C:(q,G)=>q(...G)}),this.connection&&await this.closeConnection(new ConnectionDisplacedError);else return{accept:!1};if(await this._callbacks.onOffer(I)&&!this.connection){invariant($.sessionId,void 0,{F:__dxlog_file3,L:143,S:this,A:["message.sessionId",""]});const q=this._createConnection(!1,$.sessionId);try{await this._connectionLimiter.connecting($.sessionId),q.initiate(),await q.openConnection()}catch(G){G instanceof protocols.CancelledError||log$2.info("connection error",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,err:G},{F:__dxlog_file3,L:153,S:this,C:(K,Y)=>K(...Y)}),await this.closeConnection(G)}return{accept:!0}}return{accept:!1}}async initiateConnection(){invariant(!this.initiating,"Initiation in progress.",{F:__dxlog_file3,L:170,S:this,A:["!this.initiating","'Initiation in progress.'"]}),invariant(!this.connection,"Already connected.",{F:__dxlog_file3,L:171,S:this,A:["!this.connection","'Already connected.'"]});const $=PublicKey.random();log$2("initiating...",{id:this.id,topic:this.topic,peerId:this.id,sessionId:$},{F:__dxlog_file3,L:173,S:this,C:(q,G)=>q(...G)});const I=this._createConnection(!0,$);this.initiating=!0;let U;try{if(await this._connectionLimiter.connecting($),I.initiate(),U=await this._signalMessaging.offer({author:this.localPeerId,recipient:this.id,sessionId:$,topic:this.topic,data:{offer:{}}}),log$2("received",{answer:U,topic:this.topic,ownId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3,L:190,S:this,C:(q,G)=>q(...G)}),I.state!==ConnectionState.INITIAL){log$2("ignoring response",void 0,{F:__dxlog_file3,L:192,S:this,C:(q,G)=>q(...G)});return}}catch(q){throw log$2("initiation error: send offer",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3,L:196,S:this,C:(G,K)=>G(...K)}),await I.abort(q),q}finally{this.initiating=!1}try{if(!U.accept){this._callbacks.onRejected();return}}catch(q){throw log$2("initiation error: accept answer",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3,L:209,S:this,C:(G,K)=>G(...K)}),await I.abort(q),q}finally{this.initiating=!1}try{log$2("opening connection as initiator",void 0,{F:__dxlog_file3,L:222,S:this,C:(q,G)=>q(...G)}),await I.openConnection(),this._callbacks.onAccepted()}catch(q){throw log$2("initiation error: open connection",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3,L:226,S:this,C:(G,K)=>G(...K)}),log$2.warn("closing connection due to unhandled error on openConnection",{err:q},{F:__dxlog_file3,L:233,S:this,C:(G,K)=>G(...K)}),await this.closeConnection(q),q}finally{this.initiating=!1}}_createConnection($,I){var q;log$2("creating connection",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$,sessionId:I},{F:__dxlog_file3,L:247,S:this,C:(G,K)=>G(...K)}),invariant(!this.connection,"Already connected.",{F:__dxlog_file3,L:254,S:this,A:["!this.connection","'Already connected.'"]});const U=new Connection(this.topic,this.localPeerId,this.id,I,$,this._signalMessaging,this._protocolProvider({initiator:$,localPeerId:this.localPeerId,remotePeerId:this.id,topic:this.topic}),this._transportFactory,{onConnected:()=>{this.availableToConnect=!0,this._lastConnectionTime=Date.now(),this._callbacks.onConnected(),this._connectionLimiter.doneConnecting(I),log$2.trace("dxos.mesh.connection.connected",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$},{F:__dxlog_file3,L:273,S:this,C:(G,K)=>G(...K)})},onClosed:G=>{log$2("connection closed",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$},{F:__dxlog_file3,L:282,S:this,C:(K,Y)=>K(...Y)}),this._connectionLimiter.doneConnecting(I),invariant(this.connection===U,"Connection mismatch (race condition).",{F:__dxlog_file3,L:287,S:this,A:["this.connection === connection","'Connection mismatch (race condition).'"]}),log$2.trace("dxos.mesh.connection.closed",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$},{F:__dxlog_file3,L:289,S:this,C:(K,Y)=>K(...Y)}),G instanceof ConnectionDisplacedError?this.connectionDisplaced.emit(this.connection):(this._lastConnectionTime&&this._lastConnectionTime+CONNECTION_COUNTS_STABLE_AFTER<Date.now()?this._availableAfter=0:(this.availableToConnect=!1,this._availableAfter=increaseInterval(this._availableAfter)),this._callbacks.onDisconnected(),scheduleTask(this._connectionCtx,()=>{this.availableToConnect=!0,this._callbacks.onPeerAvailable()},this._availableAfter)),this.connection=void 0}});return this._callbacks.onInitiated(U),(q=this._connectionCtx)==null||q.dispose(),this._connectionCtx=this._ctx.derive(),U.errors.handle(G=>{log$2.info("connection error, closing",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$,err:G},{F:__dxlog_file3,L:329,S:this,C:(K,Y)=>K(...Y)}),log$2.trace("dxos.mesh.connection.error",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$,err:G},{F:__dxlog_file3,L:336,S:this,C:(K,Y)=>K(...Y)}),this.closeConnection(G)}),this.connection=U,U}async closeConnection($){if(!this.connection)return;const I=this.connection;log$2("closing...",{peerId:this.id,sessionId:I.sessionId},{F:__dxlog_file3,L:361,S:this,C:(U,q)=>U(...q)}),await I.close($),log$2("closed",{peerId:this.id,sessionId:I.sessionId},{F:__dxlog_file3,L:367,S:this,C:(U,q)=>U(...q)})}async onSignal($){if(!this.connection){log$2("dropping signal message for non-existent connection",{message:$},{F:__dxlog_file3,L:372,S:this,C:(I,U)=>I(...U)});return}await this.connection.signal($)}async destroy($){var I;await this._ctx.dispose(),log$2("Destroying peer",{peerId:this.id,topic:this.topic},{F:__dxlog_file3,L:382,S:this,C:(U,q)=>U(...q)}),await((I=this==null?void 0:this.connection)==null?void 0:I.close($))}};_ts_decorate2$1([synchronized],Peer.prototype,"destroy",null);var increaseInterval=$=>$===0?50:$<500?500:$<1e3?1e3:$<5e3?5e3:1e4;function _ts_decorate3$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4$1="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm.ts",INITIATION_DELAY=100,getClassName=$=>Object.getPrototypeOf($).constructor.name,Swarm=class{constructor($,I,U,q,G,K,Y,J,X=INITIATION_DELAY){this._topic=$,this._ownPeerId=I,this._topology=U,this._protocolProvider=q,this._messenger=G,this._transportFactory=K,this._label=Y,this._connectionLimiter=J,this._initiationDelay=X,this._ctx=new Context,this._listeningHandle=void 0,this._peers=new ComplexMap(PublicKey.hash),this._instanceId=PublicKey.random().toHex(),this.connectionAdded=new Event$1,this.disconnected=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream,log$2.trace("dxos.mesh.swarm.constructor",protocols.trace.begin({id:this._instanceId,data:{topic:this._topic.toHex(),peerId:this._ownPeerId.toHex()}}),{F:__dxlog_file4$1,L:89,S:this,C:(Z,Q)=>Z(...Q)}),log$2("creating swarm",{peerId:I},{F:__dxlog_file4$1,L:93,S:this,C:(Z,Q)=>Z(...Q)}),U.init(this._getSwarmController()),this._swarmMessenger=new SwarmMessenger({sendMessage:async Z=>await this._messenger.sendMessage(Z),onSignal:async Z=>await this.onSignal(Z),onOffer:async Z=>await this.onOffer(Z),topic:this._topic}),log$2.trace("dxos.mesh.swarm.constructor",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file4$1,L:102,S:this,C:(Z,Q)=>Z(...Q)})}get connections(){return Array.from(this._peers.values()).map($=>$.connection).filter(isNotNullOrUndefined)}get ownPeerId(){return this._ownPeerId}get label(){return this._label}get topic(){return this._topic}async open(){invariant(!this._listeningHandle,void 0,{F:__dxlog_file4$1,L:129,S:this,A:["!this._listeningHandle",""]}),this._listeningHandle=await this._messenger.listen({peerId:this._ownPeerId,payloadType:"dxos.mesh.swarm.SwarmMessage",onMessage:async $=>{await this._swarmMessenger.receiveMessage($).catch(I=>log$2.info("Error while receiving message",{err:I},{F:__dxlog_file4$1,L:137,S:this,C:(U,q)=>U(...q)}))}})}async destroy(){var $;log$2("destroying...",void 0,{F:__dxlog_file4$1,L:143,S:this,C:(I,U)=>I(...U)}),await(($=this._listeningHandle)==null?void 0:$.unsubscribe()),this._listeningHandle=void 0,await this._ctx.dispose(),await this._topology.destroy(),await Promise.all(Array.from(this._peers.keys()).map(I=>this._destroyPeer(I,"swarm destroyed"))),log$2("destroyed",void 0,{F:__dxlog_file4$1,L:150,S:this,C:(I,U)=>I(...U)})}async setTopology($){invariant(!this._ctx.disposed,"Swarm is offline",{F:__dxlog_file4$1,L:154,S:this,A:["!this._ctx.disposed","'Swarm is offline'"]}),$!==this._topology&&(log$2("setting topology",{previous:getClassName(this._topology),topology:getClassName($)},{F:__dxlog_file4$1,L:158,S:this,C:(I,U)=>I(...U)}),await this._topology.destroy(),this._topology=$,this._topology.init(this._getSwarmController()),this._topology.update())}onSwarmEvent($){var I;if(log$2("swarm event",{swarmEvent:$},{F:__dxlog_file4$1,L:171,S:this,C:(U,q)=>U(...q)}),this._ctx.disposed){log$2("swarm event ignored for disposed swarm",void 0,{F:__dxlog_file4$1,L:174,S:this,C:(U,q)=>U(...q)});return}if($.peerAvailable){const U=PublicKey.from($.peerAvailable.peer);if(log$2("new peer",{peerId:U},{F:__dxlog_file4$1,L:180,S:this,C:(q,G)=>q(...G)}),!U.equals(this._ownPeerId)){const q=this._getOrCreatePeer(U);q.advertizing=!0}}else if($.peerLeft){const U=this._peers.get(PublicKey.from($.peerLeft.peer));U?(U.advertizing=!1,((I=U.connection)==null?void 0:I.state)!==ConnectionState.CONNECTED&&this._destroyPeer(U.id,"peer left").catch(q=>log$2.catch(q,void 0,{F:__dxlog_file4$1,L:191,S:this,C:(G,K)=>G(...K)}))):log$2("received peerLeft but no peer found",{peer:$.peerLeft.peer},{F:__dxlog_file4$1,L:194,S:this,C:(q,G)=>q(...G)})}this._topology.update()}async onOffer($){var q,G;if(log$2("offer",{message:$},{F:__dxlog_file4$1,L:203,S:this,C:(K,Y)=>K(...Y)}),this._ctx.disposed)return log$2("ignored for disposed swarm",void 0,{F:__dxlog_file4$1,L:205,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};if(invariant($.author,void 0,{F:__dxlog_file4$1,L:210,S:this,A:["message.author",""]}),!((q=$.recipient)!=null&&q.equals(this._ownPeerId)))return log$2("rejecting offer with incorrect peerId",{message:$},{F:__dxlog_file4$1,L:212,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};if(!((G=$.topic)!=null&&G.equals(this._topic)))return log$2("rejecting offer with incorrect topic",{message:$},{F:__dxlog_file4$1,L:216,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};const U=await this._getOrCreatePeer($.author).onOffer($);return this._topology.update(),U}async onSignal($){var U,q;if(log$2("signal",{message:$},{F:__dxlog_file4$1,L:227,S:this,C:(G,K)=>G(...K)}),this._ctx.disposed){log$2.info("ignored for offline swarm",void 0,{F:__dxlog_file4$1,L:229,S:this,C:(G,K)=>G(...K)});return}invariant((U=$.recipient)==null?void 0:U.equals(this._ownPeerId),`Invalid signal peer id expected=${this.ownPeerId}, actual=${$.recipient}`,{F:__dxlog_file4$1,L:232,S:this,A:["message.recipient?.equals(this._ownPeerId)","`Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`"]}),invariant((q=$.topic)==null?void 0:q.equals(this._topic),void 0,{F:__dxlog_file4$1,L:236,S:this,A:["message.topic?.equals(this._topic)",""]}),invariant($.author,void 0,{F:__dxlog_file4$1,L:237,S:this,A:["message.author",""]}),await this._getOrCreatePeer($.author).onSignal($)}async goOffline(){await this._ctx.dispose(),await Promise.all([...this._peers.keys()].map($=>this._destroyPeer($,"goOffline")))}async goOnline(){this._ctx=new Context}_getOrCreatePeer($){let I=this._peers.get($);return I||(I=new Peer($,this._topic,this._ownPeerId,this._swarmMessenger,this._protocolProvider,this._transportFactory,this._connectionLimiter,{onInitiated:U=>{this.connectionAdded.emit(U)},onConnected:()=>{this.connected.emit($)},onDisconnected:async()=>{I.advertizing||await this._destroyPeer(I.id,"peer disconnected"),this.disconnected.emit($),this._topology.update()},onRejected:()=>{this._peers.has($)&&(log$2("peer rejected connection",{peerId:$},{F:__dxlog_file4$1,L:286,S:this,C:(U,q)=>U(...q)}),this._destroyPeer($,"peer rejected connection"))},onAccepted:()=>{this._topology.update()},onOffer:U=>this._topology.onOffer(U),onPeerAvailable:()=>{this._topology.update()}}),this._peers.set($,I)),I}async _destroyPeer($,I){invariant(this._peers.has($),void 0,{F:__dxlog_file4$1,L:308,S:this,A:["this._peers.has(peerId)",""]}),await this._peers.get($).destroy(new Error(I)),this._peers.delete($)}_getSwarmController(){return{getState:()=>({ownPeerId:this._ownPeerId,connected:Array.from(this._peers.values()).filter($=>$.connection).map($=>$.id),candidates:Array.from(this._peers.values()).filter($=>!$.connection&&$.advertizing&&$.availableToConnect).map($=>$.id)}),connect:$=>{this._ctx.disposed||scheduleTask(this._ctx,async()=>{try{await this._initiateConnection($)}catch(I){log$2("initiation error",I,{F:__dxlog_file4$1,L:334,S:this,C:(U,q)=>U(...q)})}})},disconnect:async $=>{this._ctx.disposed||scheduleTask(this._ctx,async()=>{await this._closeConnection($),this._topology.update()})}}}async _initiateConnection($){const I=this._ctx;if($.toHex()<this._ownPeerId.toHex()&&(log$2("initiation delay",{remoteId:$},{F:__dxlog_file4$1,L:361,S:this,C:(q,G)=>q(...G)}),await sleep(this._initiationDelay)),I.disposed)return;const U=this._getOrCreatePeer($);U.connection||(log$2("initiating connection...",{remoteId:$},{F:__dxlog_file4$1,L:375,S:this,C:(q,G)=>q(...G)}),await U.initiateConnection(),this._topology.update(),log$2("initiated",{remoteId:$},{F:__dxlog_file4$1,L:378,S:this,C:(q,G)=>q(...G)}))}async _closeConnection($){const I=this._peers.get($);I&&await I.closeConnection()}};_ts_decorate3$1([logInfo],Swarm.prototype,"_instanceId",void 0),_ts_decorate3$1([logInfo],Swarm.prototype,"ownPeerId",null),_ts_decorate3$1([logInfo],Swarm.prototype,"topic",null),_ts_decorate3$1([synchronized],Swarm.prototype,"onSwarmEvent",null),_ts_decorate3$1([synchronized],Swarm.prototype,"onOffer",null),_ts_decorate3$1([synchronized],Swarm.prototype,"goOffline",null),_ts_decorate3$1([synchronized],Swarm.prototype,"goOnline",null);var EventType;(function($){$.CONNECTION_STATE_CHANGED="CONNECTION_STATE_CHANGED",$.PROTOCOL_ERROR="PROTOCOL_ERROR",$.PROTOCOL_EXTENSIONS_INITIALIZED="PROTOCOL_EXTENSIONS_INITIALIZED",$.PROTOCOL_EXTENSIONS_HANDSHAKE="PROTOCOL_EXTENSIONS_HANDSHAKE",$.PROTOCOL_HANDSHAKE="PROTOCOL_HANDSHAKE"})(EventType||(EventType={}));function _ts_decorate4$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file11="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts",MEMORY_TRANSPORT_DELAY=1,createStreamDelay=$=>new readableBrowserExports.Transform({objectMode:!0,transform:(I,U,q)=>{setTimeout(()=>q(null,I),$)}}),MemoryTransport=(Zn=class{constructor(I){this._options=I,this._instanceId=PublicKey.random(),this._remote=new Trigger,this._outgoingDelay=createStreamDelay(MEMORY_TRANSPORT_DELAY),this._incomingDelay=createStreamDelay(MEMORY_TRANSPORT_DELAY),this._closed=!1,this.closed=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream,invariant(!Zn._connections.has(this._instanceId),"Duplicate memory connection",{F:__dxlog_file11,L:64,S:this,A:["!MemoryTransport._connections.has(this._instanceId)","'Duplicate memory connection'"]}),Zn._connections.set(this._instanceId,this)}get isOpen(){return!this._closed}async open(){if(log$2("opening...",void 0,{F:__dxlog_file11,L:74,S:this,C:(I,U)=>I(...U)}),this._options.initiator){log$2("sending signal",void 0,{F:__dxlog_file11,L:78,S:this,C:(I,U)=>I(...U)});try{await this._options.sendSignal({payload:{transportId:this._instanceId.toHex()}})}catch(I){this._closed||this.errors.raise(toError(I))}}else this._remote.wait({timeout:this._options.timeout??1e3}).then(I=>{if(!this._closed){if(this._remoteInstanceId=I,this._remoteConnection=Zn._connections.get(this._remoteInstanceId),!this._remoteConnection){this._closed=!0,this.closed.emit();return}invariant(!this._remoteConnection._remoteConnection,`Remote already connected: ${this._remoteInstanceId}`,{F:__dxlog_file11,L:104,S:this,A:["!this._remoteConnection._remoteConnection","`Remote already connected: ${this._remoteInstanceId}`"]}),this._remoteConnection._remoteConnection=this,this._remoteConnection._remoteInstanceId=this._instanceId,log$2("connected",void 0,{F:__dxlog_file11,L:108,S:this,C:(U,q)=>U(...q)}),this._options.stream.pipe(this._outgoingDelay).pipe(this._remoteConnection._options.stream).pipe(this._incomingDelay).pipe(this._options.stream),this.connected.emit(),this._remoteConnection.connected.emit()}}).catch(I=>{this._closed||this.errors.raise(I)})}async close(){log$2("closing...",void 0,{F:__dxlog_file11,L:129,S:this,C:(I,U)=>I(...U)}),this._closed=!0,Zn._connections.delete(this._instanceId),this._remoteConnection&&(this._remoteConnection._closed=!0,Zn._connections.delete(this._remoteInstanceId),this._options.stream.unpipe(this._incomingDelay),this._incomingDelay.unpipe(this._remoteConnection._options.stream),this._remoteConnection._options.stream.unpipe(this._outgoingDelay),this._outgoingDelay.unpipe(this._options.stream),this._options.stream.unpipe(this._outgoingDelay),this._remoteConnection.closed.emit(),this._remoteConnection._remoteConnection=void 0,this._remoteConnection=void 0),this.closed.emit(),log$2("closed",void 0,{F:__dxlog_file11,L:157,S:this,C:(I,U)=>I(...U)})}async onSignal({payload:I}){if(log$2("received signal",{payload:I},{F:__dxlog_file11,L:161,S:this,C:(q,G)=>q(...G)}),!(I!=null&&I.transportId))return;const U=I.transportId;if(U){const q=PublicKey.fromHex(U);this._remote.wake(q)}}async getDetails(){return this._instanceId.toHex()}async getStats(){return{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0}}},Zn._connections=new ComplexMap(PublicKey.hash),Zn);_ts_decorate4$1([logInfo],MemoryTransport.prototype,"_instanceId",void 0),_ts_decorate4$1([logInfo],MemoryTransport.prototype,"_remoteInstanceId",void 0);var toError=$=>$ instanceof Error?$:new Error(String($)),TransportKind;(function($){$.SIMPLE_PEER="SIMPLE_PEER",$.SIMPLE_PEER_PROXY="SIMPLE_PEER_PROXY",$.LIBDATACHANNEL="LIBDATACHANNEL",$.MEMORY="MEMORY",$.TCP="TCP"})(TransportKind||(TransportKind={}));var wrtc=null;try{wrtc=__require("@koush/wrtc")}catch{}function _ts_decorate5$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file15="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/libdatachannel-transport.ts",DATACHANNEL_LABEL="dxos.mesh.transport",MAX_BUFFERED_AMOUNT=64*1024,MAX_MESSAGE_SIZE=64*1024,LibDataChannelTransport=(rr=class{constructor(I){this._options=I,this._closed=!1,this._connected=!1,this._writeCallback=null,this._readyForCandidates=new Trigger,this.closed=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream}get isOpen(){return!!this._peer&&!this._closed}async open(){this._closed&&this.errors.raise(new Error("connection already closed"));const{RTCPeerConnection:I}=(await importESM("node-datachannel/polyfill")).default;this._options.webrtcConfig?this._options.webrtcConfig.iceServers=this._options.webrtcConfig.iceServers??[]:this._options.webrtcConfig={iceServers:[]},this._peer=new I(this._options.webrtcConfig),this._peer.onicecandidateerror=U=>{log$2.error("peer.onicecandidateerror",{event:U},{F:__dxlog_file15,L:77,S:this,C:(q,G)=>q(...G)})},this._peer.onconnectionstatechange=U=>{var q;log$2.debug("peer.onconnectionstatechange",{event:U,peerConnectionState:(q=this._peer)==null?void 0:q.connectionState,transportConnectionState:this._connected},{F:__dxlog_file15,L:81,S:this,C:(G,K)=>G(...K)})},this._peer.onicecandidate=async U=>{if(log$2.debug("peer.onicecandidate",{event:U},{F:__dxlog_file15,L:91,S:this,C:(q,G)=>q(...G)}),U.candidate)try{await this._options.sendSignal({payload:{data:{type:"candidate",candidate:{candidate:U.candidate.candidate,sdpMLineIndex:U.candidate.sdpMLineIndex??0,sdpMid:U.candidate.sdpMid??0}}}})}catch(q){log$2.info("signaling error",{err:q},{F:__dxlog_file15,L:108,S:this,C:(G,K)=>G(...K)})}},this._options.initiator?(invariant(this._peer,"not open",{F:__dxlog_file15,L:114,S:this,A:["this._peer","'not open'"]}),this._peer.createOffer().then(async U=>{var q;this._closed||(((q=this._peer)==null?void 0:q.connectionState)!=="connecting"&&(log$2.error("peer not connecting",{peer:this._peer},{F:__dxlog_file15,L:125,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("invalid state: peer is initiator, but other peer not in state connecting"))),log$2.debug("creating offer",{peer:this._peer,offer:U},{F:__dxlog_file15,L:129,S:this,C:(G,K)=>G(...K)}),await this._peer.setLocalDescription(U),await this._options.sendSignal({payload:{data:{type:U.type,sdp:U.sdp}}}))}).catch(U=>{this.errors.raise(U)}),this._handleChannel(this._peer.createDataChannel(DATACHANNEL_LABEL)),log$2.debug("created data channel",void 0,{F:__dxlog_file15,L:139,S:this,C:(U,q)=>U(...q)}),this._peer.ondatachannel=()=>{this.errors.raise(new Error("unexpected ondatachannel event for initiator"))}):this._peer.ondatachannel=U=>{log$2.debug("peer.ondatachannel (non-initiator)",{event:U},{F:__dxlog_file15,L:145,S:this,C:(q,G)=>q(...G)}),U.channel.label!==DATACHANNEL_LABEL&&this.errors.raise(new Error(`unexpected channel label ${U.channel.label}`)),this._handleChannel(U.channel)},rr._instanceCount++}async close(){await this._close(),--rr._instanceCount===0&&(await importESM("node-datachannel")).cleanup()}async _close(){var I;if(!this._closed){await this._disconnectStreams();try{(I=this._peer)==null||I.close()}catch(U){this.errors.raise(U)}this._peer=void 0,this._closed=!0,this.closed.emit()}}_handleChannel(I){this._channel=I,this._channel.onopen=()=>{log$2.debug("channel.onopen",void 0,{F:__dxlog_file15,L:190,S:this,C:(q,G)=>q(...G)});const U=new stream.Duplex({read:()=>{},write:async(q,G,K)=>{q.length>MAX_MESSAGE_SIZE&&this.errors.raise(new Error(`message too large: ${q.length} > ${MAX_MESSAGE_SIZE}`));try{I.send(q)}catch(Y){this.errors.raise(Y),await this._close()}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._writeCallback!==null&&log$2.error("consumer trying to write before we are ready for more data",void 0,{F:__dxlog_file15,L:207,S:this,C:(Y,J)=>Y(...J)}),this._writeCallback=K):K()}});U.pipe(this._options.stream).pipe(U),this._stream=U,this._connected=!0,this.connected.emit()},this._channel.onclose=async U=>{log$2.info("channel.onclose",{err:U},{F:__dxlog_file15,L:223,S:this,C:(q,G)=>q(...G)}),await this._close()},this._channel.onerror=async U=>{this.errors.raise(new Error("channel error: "+U.toString())),await this._close()},this._channel.onbufferedamountlow=()=>{const U=this._writeCallback;this._writeCallback=null,U==null||U()},this._channel.onmessage=U=>{let q=U.data;q instanceof ArrayBuffer&&(q=export_Buffer.from(q)),this._stream.push(q)}}async onSignal(I){invariant(this._peer,"not open",{F:__dxlog_file15,L:249,S:this,A:["this._peer","'not open'"]});try{const U=I.payload.data;switch(U.type){case"offer":{if(this._peer.connectionState!=="new"){log$2.error("received offer but peer not in state new",{peer:this._peer},{F:__dxlog_file15,L:256,S:this,C:(q,G)=>q(...G)}),this.errors.raise(new Error("invalid signalling state: received offer when peer is not in state new"));break}try{await this._peer.setRemoteDescription({type:U.type,sdp:U.sdp});const q=await this._peer.createAnswer();await this._peer.setLocalDescription(q),await this._options.sendSignal({payload:{data:{type:q.type,sdp:q.sdp}}}),this._readyForCandidates.wake()}catch(q){log$2.error("cannot handle offer from signalling server",{err:q},{F:__dxlog_file15,L:268,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("error handling offer"))}break}case"answer":try{await this._peer.setRemoteDescription({type:U.type,sdp:U.sdp}),this._readyForCandidates.wake()}catch(q){log$2.error("cannot handle answer from signalling server",{err:q},{F:__dxlog_file15,L:279,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("error handling answer"))}break;case"candidate":await this._readyForCandidates.wait(),await this._peer.addIceCandidate({candidate:U.candidate.candidate});break;default:log$2.error("unhandled signal type",{type:U.type,signal:I},{F:__dxlog_file15,L:290,S:this,C:(q,G)=>q(...G)}),this.errors.raise(new Error(`unhandled signal type ${U.type}`))}}catch(U){log$2.catch(U,void 0,{F:__dxlog_file15,L:294,S:this,C:(q,G)=>q(...G)})}}async getDetails(){const I=await this._getStats(),U=I==null?void 0:I.remoteCandidate;return U?U.candidateType==="relay"?`${U.ip}:${U.port} relay for ${U.relatedAddress}:${U.relatedPort}`:`${U.ip}:${U.port} ${U.candidateType}`:"unavailable"}async getStats(){const I=await this._getStats();return I?{bytesSent:I.transport.bytesSent,bytesReceived:I.transport.bytesReceived,packetsSent:0,packetsReceived:0,rawStats:I.raw}:{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rawStats:{}}}async _getStats(){invariant(this._peer,"not open",{F:__dxlog_file15,L:334,S:this,A:["this._peer","'not open'"]});const I=await this._peer.getStats(),U=Array.from(I.entries()),q=U.filter(J=>J[1].type==="transport")[0][1],G=U.filter(J=>J[0]===q.selectedCandidatePairId);let K,Y;return G.length>0&&(K=G[0][1],Y=U.filter(J=>J[0]===K.remoteCandidateId)[0][1]),{transport:q,selectedCandidatePair:K,remoteCandidate:Y,raw:Object.fromEntries(I)}}async _disconnectStreams(){var I,U,q,G;(G=(q=(U=(I=this._options.stream).unpipe)==null?void 0:U.call(I,this._stream))==null?void 0:q.unpipe)==null||G.call(q,this._options.stream)}},rr._instanceCount=0,rr);_ts_decorate5$1([synchronized],LibDataChannelTransport.prototype,"_close",null);var importESM=Function("path","return import(path)"),uaParser={exports:{}};(function($,I){(function(U,q){var G="1.0.35",K="",Y="?",J="function",X="undefined",Z="object",Q="string",ee="major",te="model",ne="name",ie="type",oe="vendor",ce="version",fe="architecture",se="console",de="mobile",ue="tablet",pe="smarttv",ve="wearable",me="embedded",be=350,ye="Amazon",Se="Apple",xe="ASUS",ke="BlackBerry",De="Browser",Be="Chrome",Ve="Edge",nt="Firefox",ot="Google",ft="Huawei",it="LG",ut="Microsoft",et="Motorola",Ue="Opera",We="Samsung",tt="Sharp",vt="Sony",je="Xiaomi",ze="Zebra",Ae="Facebook",Re="Chromium OS",Ce="Mac OS",ge=function(St,Ut){var le={};for(var re in St)Ut[re]&&Ut[re].length%2===0?le[re]=Ut[re].concat(St[re]):le[re]=St[re];return le},_e=function(St){for(var Ut={},le=0;le<St.length;le++)Ut[St[le].toUpperCase()]=St[le];return Ut},Me=function(St,Ut){return typeof St===Q?Ke(Ut).indexOf(Ke(St))!==-1:!1},Ke=function(St){return St.toLowerCase()},st=function(St){return typeof St===Q?St.replace(/[^\d\.]/g,K).split(".")[0]:q},dt=function(St,Ut){if(typeof St===Q)return St=St.replace(/^\s\s*/,K),typeof Ut===X?St:St.substring(0,be)},$t=function(St,Ut){for(var le=0,re,ae,he,we,Ee,Le;le<Ut.length&&!Ee;){var bt=Ut[le],Lt=Ut[le+1];for(re=ae=0;re<bt.length&&!Ee&&bt[re];)if(Ee=bt[re++].exec(St),Ee)for(he=0;he<Lt.length;he++)Le=Ee[++ae],we=Lt[he],typeof we===Z&&we.length>0?we.length===2?typeof we[1]==J?this[we[0]]=we[1].call(this,Le):this[we[0]]=we[1]:we.length===3?typeof we[1]===J&&!(we[1].exec&&we[1].test)?this[we[0]]=Le?we[1].call(this,Le,we[2]):q:this[we[0]]=Le?Le.replace(we[1],we[2]):q:we.length===4&&(this[we[0]]=Le?we[3].call(this,Le.replace(we[1],we[2])):q):this[we]=Le||q;le+=2}},Et=function(St,Ut){for(var le in Ut)if(typeof Ut[le]===Z&&Ut[le].length>0){for(var re=0;re<Ut[le].length;re++)if(Me(Ut[le][re],St))return le===Y?q:le}else if(Me(Ut[le],St))return le===Y?q:le;return St},rt={"1.0":"/8","1.2":"/1","1.3":"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},jt={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2","8.1":"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Gt={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[ce,[ne,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[ce,[ne,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[ne,ce],[/opios[\/ ]+([\w\.]+)/i],[ce,[ne,Ue+" Mini"]],[/\bopr\/([\w\.]+)/i],[ce,[ne,Ue]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[ne,ce],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[ce,[ne,"UC"+De]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[ce,[ne,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[ce,[ne,"WeChat"]],[/konqueror\/([\w\.]+)/i],[ce,[ne,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[ce,[ne,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[ce,[ne,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[ne,/(.+)/,"$1 Secure "+De],ce],[/\bfocus\/([\w\.]+)/i],[ce,[ne,nt+" Focus"]],[/\bopt\/([\w\.]+)/i],[ce,[ne,Ue+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[ce,[ne,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[ce,[ne,"Dolphin"]],[/coast\/([\w\.]+)/i],[ce,[ne,Ue+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[ce,[ne,"MIUI "+De]],[/fxios\/([-\w\.]+)/i],[ce,[ne,nt]],[/\bqihu|(qi?ho?o?|360)browser/i],[[ne,"360 "+De]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[ne,/(.+)/,"$1 "+De],ce],[/(comodo_dragon)\/([\w\.]+)/i],[[ne,/_/g," "],ce],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[ne,ce],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[ne],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[ne,Ae],ce],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[ne,ce],[/\bgsa\/([\w\.]+) .*safari\//i],[ce,[ne,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[ce,[ne,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[ce,[ne,Be+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[ne,Be+" WebView"],ce],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[ce,[ne,"Android "+De]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[ne,ce],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[ce,[ne,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[ce,ne],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[ne,[ce,Et,rt]],[/(webkit|khtml)\/([\w\.]+)/i],[ne,ce],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[ne,"Netscape"],ce],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[ce,[ne,nt+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[ne,ce],[/(cobalt)\/([\w\.]+)/i],[ne,[ce,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[fe,"amd64"]],[/(ia32(?=;))/i],[[fe,Ke]],[/((?:i[346]|x)86)[;\)]/i],[[fe,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[fe,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[fe,"armhf"]],[/windows (ce|mobile); ppc;/i],[[fe,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[fe,/ower/,K,Ke]],[/(sun4\w)[;\)]/i],[[fe,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[fe,Ke]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[te,[oe,We],[ie,ue]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[te,[oe,We],[ie,de]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[te,[oe,Se],[ie,de]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[te,[oe,Se],[ie,ue]],[/(macintosh);/i],[te,[oe,Se]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[te,[oe,tt],[ie,de]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[te,[oe,ft],[ie,ue]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[te,[oe,ft],[ie,de]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[te,/_/g," "],[oe,je],[ie,de]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[te,/_/g," "],[oe,je],[ie,ue]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[te,[oe,"OPPO"],[ie,de]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[te,[oe,"Vivo"],[ie,de]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[te,[oe,"Realme"],[ie,de]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[te,[oe,et],[ie,de]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[te,[oe,et],[ie,ue]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[te,[oe,it],[ie,ue]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[te,[oe,it],[ie,de]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[te,[oe,"Lenovo"],[ie,ue]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[te,/_/g," "],[oe,"Nokia"],[ie,de]],[/(pixel c)\b/i],[te,[oe,ot],[ie,ue]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[te,[oe,ot],[ie,de]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[te,[oe,vt],[ie,de]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[te,"Xperia Tablet"],[oe,vt],[ie,ue]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[te,[oe,"OnePlus"],[ie,de]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[te,[oe,ye],[ie,ue]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[te,/(.+)/g,"Fire Phone $1"],[oe,ye],[ie,de]],[/(playbook);[-\w\),; ]+(rim)/i],[te,oe,[ie,ue]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[te,[oe,ke],[ie,de]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[te,[oe,xe],[ie,ue]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[te,[oe,xe],[ie,de]],[/(nexus 9)/i],[te,[oe,"HTC"],[ie,ue]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[oe,[te,/_/g," "],[ie,de]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[te,[oe,"Acer"],[ie,ue]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[te,[oe,"Meizu"],[ie,de]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[oe,te,[ie,de]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[oe,te,[ie,ue]],[/(surface duo)/i],[te,[oe,ut],[ie,ue]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[te,[oe,"Fairphone"],[ie,de]],[/(u304aa)/i],[te,[oe,"AT&T"],[ie,de]],[/\bsie-(\w*)/i],[te,[oe,"Siemens"],[ie,de]],[/\b(rct\w+) b/i],[te,[oe,"RCA"],[ie,ue]],[/\b(venue[\d ]{2,7}) b/i],[te,[oe,"Dell"],[ie,ue]],[/\b(q(?:mv|ta)\w+) b/i],[te,[oe,"Verizon"],[ie,ue]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[te,[oe,"Barnes & Noble"],[ie,ue]],[/\b(tm\d{3}\w+) b/i],[te,[oe,"NuVision"],[ie,ue]],[/\b(k88) b/i],[te,[oe,"ZTE"],[ie,ue]],[/\b(nx\d{3}j) b/i],[te,[oe,"ZTE"],[ie,de]],[/\b(gen\d{3}) b.+49h/i],[te,[oe,"Swiss"],[ie,de]],[/\b(zur\d{3}) b/i],[te,[oe,"Swiss"],[ie,ue]],[/\b((zeki)?tb.*\b) b/i],[te,[oe,"Zeki"],[ie,ue]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[oe,"Dragon Touch"],te,[ie,ue]],[/\b(ns-?\w{0,9}) b/i],[te,[oe,"Insignia"],[ie,ue]],[/\b((nxa|next)-?\w{0,9}) b/i],[te,[oe,"NextBook"],[ie,ue]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[oe,"Voice"],te,[ie,de]],[/\b(lvtel\-)?(v1[12]) b/i],[[oe,"LvTel"],te,[ie,de]],[/\b(ph-1) /i],[te,[oe,"Essential"],[ie,de]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[te,[oe,"Envizen"],[ie,ue]],[/\b(trio[-\w\. ]+) b/i],[te,[oe,"MachSpeed"],[ie,ue]],[/\btu_(1491) b/i],[te,[oe,"Rotor"],[ie,ue]],[/(shield[\w ]+) b/i],[te,[oe,"Nvidia"],[ie,ue]],[/(sprint) (\w+)/i],[oe,te,[ie,de]],[/(kin\.[onetw]{3})/i],[[te,/\./g," "],[oe,ut],[ie,de]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[te,[oe,ze],[ie,ue]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[te,[oe,ze],[ie,de]],[/smart-tv.+(samsung)/i],[oe,[ie,pe]],[/hbbtv.+maple;(\d+)/i],[[te,/^/,"SmartTV"],[oe,We],[ie,pe]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[oe,it],[ie,pe]],[/(apple) ?tv/i],[oe,[te,Se+" TV"],[ie,pe]],[/crkey/i],[[te,Be+"cast"],[oe,ot],[ie,pe]],[/droid.+aft(\w)( bui|\))/i],[te,[oe,ye],[ie,pe]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[te,[oe,tt],[ie,pe]],[/(bravia[\w ]+)( bui|\))/i],[te,[oe,vt],[ie,pe]],[/(mitv-\w{5}) bui/i],[te,[oe,je],[ie,pe]],[/Hbbtv.*(technisat) (.*);/i],[oe,te,[ie,pe]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[oe,dt],[te,dt],[ie,pe]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[ie,pe]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[oe,te,[ie,se]],[/droid.+; (shield) bui/i],[te,[oe,"Nvidia"],[ie,se]],[/(playstation [345portablevi]+)/i],[te,[oe,vt],[ie,se]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[te,[oe,ut],[ie,se]],[/((pebble))app/i],[oe,te,[ie,ve]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[te,[oe,Se],[ie,ve]],[/droid.+; (glass) \d/i],[te,[oe,ot],[ie,ve]],[/droid.+; (wt63?0{2,3})\)/i],[te,[oe,ze],[ie,ve]],[/(quest( 2| pro)?)/i],[te,[oe,Ae],[ie,ve]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[oe,[ie,me]],[/(aeobc)\b/i],[te,[oe,ye],[ie,me]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[te,[ie,de]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[te,[ie,ue]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[ie,ue]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[ie,de]],[/(android[-\w\. ]{0,9});.+buil/i],[te,[oe,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[ce,[ne,Ve+"HTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[ce,[ne,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[ne,ce],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[ce,ne]],os:[[/microsoft (windows) (vista|xp)/i],[ne,ce],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[ne,[ce,Et,jt]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[ne,"Windows"],[ce,Et,jt]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/ios;fbsv\/([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[ce,/_/g,"."],[ne,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[ne,Ce],[ce,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[ce,ne],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[ne,ce],[/\(bb(10);/i],[ce,[ne,ke]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[ce,[ne,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[ce,[ne,nt+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[ce,[ne,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[ce,[ne,"watchOS"]],[/crkey\/([\d\.]+)/i],[ce,[ne,Be+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[ne,Re],ce],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[ne,ce],[/(sunos) ?([\w\.\d]*)/i],[[ne,"Solaris"],ce],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[ne,ce]]},At=function(St,Ut){if(typeof St===Z&&(Ut=St,St=q),!(this instanceof At))return new At(St,Ut).getResult();var le=typeof U!==X&&U.navigator?U.navigator:q,re=St||(le&&le.userAgent?le.userAgent:K),ae=le&&le.userAgentData?le.userAgentData:q,he=Ut?ge(Gt,Ut):Gt,we=le&&le.userAgent==re;return this.getBrowser=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.browser),Ee[ee]=st(Ee[ce]),we&&le&&le.brave&&typeof le.brave.isBrave==J&&(Ee[ne]="Brave"),Ee},this.getCPU=function(){var Ee={};return Ee[fe]=q,$t.call(Ee,re,he.cpu),Ee},this.getDevice=function(){var Ee={};return Ee[oe]=q,Ee[te]=q,Ee[ie]=q,$t.call(Ee,re,he.device),we&&!Ee[ie]&&ae&&ae.mobile&&(Ee[ie]=de),we&&Ee[te]=="Macintosh"&&le&&typeof le.standalone!==X&&le.maxTouchPoints&&le.maxTouchPoints>2&&(Ee[te]="iPad",Ee[ie]=ue),Ee},this.getEngine=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.engine),Ee},this.getOS=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.os),we&&!Ee[ne]&&ae&&ae.platform!="Unknown"&&(Ee[ne]=ae.platform.replace(/chrome os/i,Re).replace(/macos/i,Ce)),Ee},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return re},this.setUA=function(Ee){return re=typeof Ee===Q&&Ee.length>be?dt(Ee,be):Ee,this},this.setUA(re),this};At.VERSION=G,At.BROWSER=_e([ne,ce,ee]),At.CPU=_e([fe]),At.DEVICE=_e([te,oe,ie,se,de,pe,ue,ve,me]),At.ENGINE=At.OS=_e([ne,ce]),$.exports&&(I=$.exports=At),I.UAParser=At;var zt=typeof U!==X&&(U.jQuery||U.Zepto);if(zt&&!zt.ua){var nn=new At;zt.ua=nn.getResult(),zt.ua.get=function(){return nn.getUA()},zt.ua.set=function(St){nn.setUA(St);var Ut=nn.getResult();for(var le in Ut)zt.ua[le]=Ut[le]}}})(typeof window=="object"?window:commonjsGlobal)})(uaParser,uaParser.exports);var uaParserExports=uaParser.exports,__dxlog_file$2="/home/runner/work/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/iframe.ts",browser,os$1;if(typeof navigator<"u"){const $=new uaParserExports.UAParser(navigator.userAgent);browser=$.getBrowser().name,os$1=$.getOS().name}var sendToIFrame=($,I,U)=>{if(!$.contentWindow){log$2("IFrame content window missing",{origin:I},{F:__dxlog_file$2,L:24,S:void 0,C:(q,G)=>q(...G)});return}browser==="Chrome"&&os$1==="iOS"?$.contentWindow.postMessage(U,I):$.contentWindow.postMessage(U,I,[U.payload])},sendToParentWindow=($,I)=>{browser==="Chrome"&&os$1==="iOS"?window.parent.postMessage(I,$):window.parent.postMessage(I,$,[I.payload])},createIFramePort=({channel:$,iframe:I,origin:U,onOrigin:q})=>({send:async G=>{if(!U){log$2("no origin set",{channel:$},{F:__dxlog_file$2,L:62,S:void 0,C:(J,X)=>J(...X)});return}log$2("sending",{channel:$,data:G.length},{F:__dxlog_file$2,L:66,S:void 0,C:(J,X)=>J(...X)});const K=G.buffer.slice(G.byteOffset,G.byteOffset+G.byteLength),Y={channel:$,payload:K};I?sendToIFrame(I,U,Y):sendToParentWindow(U,Y)},subscribe:G=>{const K=Y=>{if(!I&&Y.source!==window.parent)return;if(I&&Y.source!==I.contentWindow)return;const X=Y.data&&typeof Y.data=="object"&&"channel"in Y.data&&"payload"in Y.data?Y.data:void 0;(X==null?void 0:X.channel)===$&&(U||(U=Y.origin,q==null||q(U)),log$2("received",X,{F:__dxlog_file$2,L:98,S:void 0,C:(Z,Q)=>Z(...Q)}),G(new Uint8Array(X.payload)))};return window.addEventListener("message",K),()=>window.removeEventListener("message",K)}}),createIFrame=($,I,{hidden:U=!0,allow:q}={})=>{const G=()=>{const K=document.createElement("iframe");return K.id=I,K.src=$,U&&K.setAttribute("style","display: none;"),q&&K.setAttribute("allow",q),document.body.appendChild(K),K};return document.getElementById(I)??G()},__dxlog_file2$1="/home/runner/work/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/worker.ts",createWorkerPort=({port:$,channel:I,subscribe:U})=>({send:async q=>{const G=q.buffer.slice(q.byteOffset,q.byteOffset+q.byteLength);$.postMessage({channel:I,payload:G},[G])},subscribe:U??(q=>{const G=K=>{const Y=K.data;I&&Y.channel!==I||(log$2.debug("Recieved message",Y,{F:__dxlog_file2$1,L:46,S:void 0,C:(J,X)=>J(...X)}),q(new Uint8Array(Y.payload)))};return $.onmessage=G,()=>{$.onmessage=null}})});function _ts_decorate$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$1="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/agent.ts",getUnixSocket=($,I="unix")=>`${I}://`+clientProtocol.getProfilePath(clientProtocol.DX_RUNTIME,$,"agent.sock"),AgentClientServiceProvider=class{constructor($){this._profile=$,this.closed=new Event$1}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return this._client.rpc}async open(){const{WebsocketRpcClient:$}=await Promise.resolve().then(()=>index);this._client=new $({url:getUnixSocket(this._profile,"ws+unix"),requested:clientProtocol.clientServiceBundle,exposed:{},handlers:{}}),this._client.error.on(I=>{this.closed.emit(I)}),await this._client.open()}async close(){var $;try{await(($=this._client)==null?void 0:$.close())}catch(I){log$2.warn("Failed to close",I,{F:__dxlog_file$1,L:72,S:this,C:(U,q)=>U(...q)})}}};AgentClientServiceProvider=_ts_decorate$1([trace.resource({annotation:clientServices.ClientServicesProviderResource})],AgentClientServiceProvider);function _ts_decorate2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var LocalClientServices=class{constructor($){this.closed=new Event$1,this._ctx=new Context,this.signalMetadataTags={runtime:"local-client-services"},this._isOpen=!1,this._params=$,typeof window>"u"?this.signalMetadataTags.origin="undefined":globalThis.__args?(this.signalMetadataTags.runtime="native",this.signalMetadataTags.origin=window.location.origin):this.signalMetadataTags.origin=window.location.origin}get descriptors(){return clientProtocol.clientServiceBundle}get services(){var $;return(($=this._host)==null?void 0:$.services)??{}}get host(){return this._host}async open(){if(this._isOpen)return;const{ClientServicesHost:$}=await import("@dxos/client-services");this._host=new $({...this._params,callbacks:{...this._params.callbacks,onReset:async()=>{var I,U;this.closed.emit(void 0),await((U=(I=this._params.callbacks)==null?void 0:I.onReset)==null?void 0:U.call(I))}}}),await this._host.open(this._ctx),this._isOpen=!0,setIdentityTags({identityService:this._host.services.IdentityService,devicesService:this._host.services.DevicesService,setTag:(I,U)=>{this.signalMetadataTags[I]=U}})}async close(){var $;this._isOpen&&(await(($=this._host)==null?void 0:$.close()),this._isOpen=!1)}};_ts_decorate2([trace.info()],LocalClientServices.prototype,"_isOpen",void 0),_ts_decorate2([synchronized],LocalClientServices.prototype,"open",null),_ts_decorate2([synchronized],LocalClientServices.prototype,"close",null),LocalClientServices=_ts_decorate2([trace.resource({annotation:clientServices.ClientServicesProviderResource})],LocalClientServices);var IFrameManager=class{constructor({source:$,onOpen:I,onMessage:U}){this._source=$,this._onOpen=I,this._onMessage=U,this._messageHandler=this._messageHandler.bind(this)}get source(){return this._source}get iframe(){return this._iframe}async open(){var I;if(this._iframe)return;window.addEventListener("message",this._messageHandler);const $=`__DXOS_CLIENT_${PublicKey.random().toHex()}__`;this._iframe=createIFrame(this._source.toString(),$,{allow:"clipboard-read; clipboard-write"}),await((I=this._onOpen)==null?void 0:I.call(this))}async close(){var $;window.removeEventListener("message",this._messageHandler),($=this._iframe)==null||$.remove(),this._iframe=void 0}async _messageHandler($){var I;(I=this._onMessage)==null||I.call(this,$)}},__dxlog_file4="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/shell-manager.ts",shellStyles=Object.entries({display:"none",position:"fixed",top:0,left:0,width:"100vw",height:"100vh",border:0,"z-index":60}).reduce(($,[I,U])=>`${$}${I}: ${U};`,""),ShellManager=class{constructor($,I=clientProtocol.DEFAULT_SHELL_CHANNEL){this._iframeManager=$,this._channel=I,this.contextUpdate=new Event$1,this._display=ShellDisplay.NONE}get display(){return this._display}async setLayout($){var I;log$2("set layout",$,{F:__dxlog_file4,L:51,S:this,C:(U,q)=>U(...q)}),this._display=ShellDisplay.FULLSCREEN,this.contextUpdate.emit({display:this._display}),await((I=this._shellRpc)==null?void 0:I.rpc.ShellService.setLayout($,{timeout:RPC_TIMEOUT}))}async open(){if(this._shellRpc)return;await this._iframeManager.open();const $=this._iframeManager.iframe;$.setAttribute("style",shellStyles),$.setAttribute("name","dxos-shell"),$.setAttribute("data-testid","dxos-shell"),this.contextUpdate.on(({display:q,reload:G})=>{G&&window.location.reload(),$.style.display=q===ShellDisplay.NONE?"none":"",q===ShellDisplay.NONE&&$.blur()});const I=this._iframeManager.source.origin==="null"?this._iframeManager.source.toString().split("/").slice(0,3).join("/"):this._iframeManager.source.origin,U=createIFramePort({origin:I,channel:this._channel,iframe:this._iframeManager.iframe});this._shellRpc=createProtoRpcPeer({requested:clientProtocol.shellServiceBundle,exposed:clientProtocol.appServiceBundle,handlers:{AppService:{setContext:async q=>{log$2("set context",q,{F:__dxlog_file4,L:98,S:this,C:(G,K)=>G(...K)}),q.display&&(this._display=q.display),this.contextUpdate.emit(q)}}},port:U}),await this._shellRpc.open()}async close(){var $;this._shellRpc&&(await(($=this._shellRpc)==null?void 0:$.close()),this._shellRpc=void 0)}};function _ts_decorate3($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var IFrameClientServicesHost=class{constructor({host:$,source:I=clientProtocol.DEFAULT_VAULT_URL,vault:U=clientProtocol.DEFAULT_INTERNAL_CHANNEL,timeout:q=clientProtocol.PROXY_CONNECTION_TIMEOUT}){this.closed=new Event$1,this._host=$,this._source=I,this._vault=U,this._timeout=q;const G=new Trigger;this._iframeManager=new IFrameManager({source:new URL(this._source,window.location.origin),onOpen:async()=>{var K,Y,J;await asyncTimeout(G.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to load")),(J=(Y=(K=this._iframeManager)==null?void 0:K.iframe)==null?void 0:Y.contentWindow)==null||J.postMessage({channel:this._vault,payload:"init"},this._iframeManager.source.origin)},onMessage:K=>{var X,Z,Q;const{channel:Y,payload:J}=K.data;if(Y===this._vault){if(J==="loaded")G.wake();else if(J==="client"){const ee=new MessageChannel,te=createBundledRpcServer({services:this._host.descriptors,handlers:this._host.services,port:createWorkerPort({port:ee.port1})});(Q=(Z=(X=this._iframeManager)==null?void 0:X.iframe)==null?void 0:Z.contentWindow)==null||Q.postMessage({channel:this._vault,payload:{command:"port",port:ee.port2}},this._iframeManager.source.origin,[ee.port2]),te.open()}}}}),this._shellManager=new ShellManager(this._iframeManager)}get descriptors(){return this._host.descriptors}get services(){return this._host.services}async open(){await this._host.open(new Context),await this._shellManager.open()}async close(){await this._shellManager.close(),await this._iframeManager.close(),await this._host.close(new Context)}};IFrameClientServicesHost=_ts_decorate3([trace.resource()],IFrameClientServicesHost);function _ts_decorate4($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/service-proxy.ts",ClientServicesProxy=class{constructor($,I=3e4){this._port=$,this._timeout=I,this.closed=new Event$1}get proxy(){return invariant(this._proxy,"Client services not open",{F:__dxlog_file5,L:30,S:this,A:["this._proxy","'Client services not open'"]}),this._proxy}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return invariant(this._proxy,"Client services not open",{F:__dxlog_file5,L:39,S:this,A:["this._proxy","'Client services not open'"]}),this._proxy.rpc}async open(){this._proxy||(this._proxy=createProtoRpcPeer({requested:clientProtocol.clientServiceBundle,exposed:{},handlers:{},port:this._port}),await asyncTimeout(this._proxy.open(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Failed to establish dxrpc connection",{timeout:this._timeout})))}async close(){this._proxy&&(await this._proxy.close(),this._proxy=void 0)}};ClientServicesProxy=_ts_decorate4([trace.resource({annotation:clientServices.ClientServicesProviderResource})],ClientServicesProxy);function _ts_decorate5($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file6="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/iframe-service-proxy.ts",IFrameClientServicesProxy=class{constructor({source:$=clientProtocol.DEFAULT_VAULT_URL,shell:I=clientProtocol.DEFAULT_SHELL_CHANNEL,vault:U=clientProtocol.DEFAULT_INTERNAL_CHANNEL,timeout:q=clientProtocol.PROXY_CONNECTION_TIMEOUT,logFilter:G="error,warn"}={}){this.closed=new Event$1,this._instanceId=PublicKey.random().toHex(),this._source=$,this._shell=I,this._vault=U,this._logFilter=parseFilter(G),this._timeout=q;const K=new Trigger,Y=new Trigger;this._iframeManager=new IFrameManager({source:new URL(typeof this._shell=="string"?this._source:`${this._source}#disableshell`,window.location.origin),onOpen:async()=>{var X,Z;await asyncTimeout(K.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to load")),(Z=(X=this._iframeManager.iframe)==null?void 0:X.contentWindow)==null||Z.postMessage({channel:this._vault,payload:"init"},this._iframeManager.source.origin);const J=await asyncTimeout(Y.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to provide MessagePort"));this._appPort=createWorkerPort({port:J})},onMessage:async J=>{const{channel:X,payload:Z}=J.data;X===this._vault&&(Z==="loaded"?K.wake():(Z==null?void 0:Z.command)==="init"&&Y.wake(Z.port))}}),typeof this._shell=="string"&&(this._shellManager=new ShellManager(this._iframeManager))}get proxy(){return this._clientServicesProxy.proxy}get descriptors(){return this._clientServicesProxy.descriptors}get services(){return this._clientServicesProxy.services}async open(){var $;this._clientServicesProxy||(log$2.trace("dxos.sdk.iframe-clientTraceices-proxy",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file6,L:142,S:this,C:(I,U)=>I(...U)}),await this._iframeManager.open(),this._clientServicesProxy=new ClientServicesProxy(this._appPort),await this._clientServicesProxy.open(),this._loggingStream=this._clientServicesProxy.services.LoggingService.queryLogs({filters:this._logFilter},{timeout:RPC_TIMEOUT}),this._loggingStream.subscribe(I=>{switch(I.level){case LogLevel.DEBUG:log$2.debug(`[vault] ${I.message}`,I.context,{F:__dxlog_file6,L:157,S:this,C:(U,q)=>U(...q)});break;case LogLevel.INFO:log$2.info(`[vault] ${I.message}`,I.context,{F:__dxlog_file6,L:160,S:this,C:(U,q)=>U(...q)});break;case LogLevel.WARN:log$2.warn(`[vault] ${I.message}`,I.context,{F:__dxlog_file6,L:163,S:this,C:(U,q)=>U(...q)});break;case LogLevel.ERROR:log$2.error(`[vault] ${I.message}`,I.context,{F:__dxlog_file6,L:166,S:this,C:(U,q)=>U(...q)});break}}),await(($=this._shellManager)==null?void 0:$.open()))}async close(){var $,I,U;await(($=this._shellManager)==null?void 0:$.close()),await this._iframeManager.close(),await((I=this._loggingStream)==null?void 0:I.close()),await((U=this._clientServicesProxy)==null?void 0:U.close()),this._clientServicesProxy=void 0,log$2.trace("dxos.sdk.iframe-clientTraceices-proxy",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file6,L:180,S:this,C:(q,G)=>q(...G)})}};IFrameClientServicesProxy=_ts_decorate5([trace.resource()],IFrameClientServicesProxy);function _ts_decorate6($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file8="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/worker-client-services.ts",WorkerClientServices=class{constructor({config:$,createWorker:I,logFilter:U="error,warn",observabilityGroup:q,signalTelemetryEnabled:G}){this.closed=new Event$1,this.joinedSpace=new Event$1,this._isOpen=!1,this._config=$,this._createWorker=I,this._logFilter=parseFilter(U),this._observabilityGroup=q,this._signalTelemetryEnabled=G??!1}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return this._services.services}get runtime(){return this._runtime}async open(){if(this._isOpen)return;log$2("opening...",void 0,{F:__dxlog_file8,L:88,S:this,C:(K,Y)=>K(...Y)});const{SharedWorkerConnection:$}=await import("@dxos/client-services"),I=new Trigger,U=this._createWorker();U.port.postMessage({dxlog:localStorage.getItem("dxlog")}),U.port.onmessage=K=>{const{command:Y,payload:J}=K.data;Y==="init"&&I.wake(J)};const{systemPort:q,appPort:G}=await I.wait();this._runtime=new $({config:this._config,systemPort:createWorkerPort({port:q})}),await this._runtime.open({origin:location.origin,observabilityGroup:this._observabilityGroup,signalTelemetryEnabled:this._signalTelemetryEnabled}),this._services=new ClientServicesProxy(createWorkerPort({port:G})),await this._services.open(),navigator.locks.request(LOCK_KEY,()=>{log$2("terminated",void 0,{F:__dxlog_file8,L:115,S:this,C:(K,Y)=>K(...Y)}),this._isOpen&&this.closed.emit(new Error("Shared worker terminated."))}),this._loggingStream=this._services.services.LoggingService.queryLogs({filters:this._logFilter},{timeout:RPC_TIMEOUT}),this._loggingStream.subscribe(K=>{switch(K.level){case LogLevel.DEBUG:log$2.debug(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.INFO:log$2.info(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.WARN:log$2.warn(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.ERROR:log$2.error(K.message,K.context,mapLogMeta(K.meta));break}}),log$2("opened",void 0,{F:__dxlog_file8,L:144,S:this,C:(K,Y)=>K(...Y)}),this._isOpen=!0}async close(){var $;this._isOpen&&(log$2("closing...",void 0,{F:__dxlog_file8,L:154,S:this,C:(I,U)=>I(...U)}),await(($=this._loggingStream)==null?void 0:$.close()),await this._runtime.close(),await this._services.close(),log$2("closed",void 0,{F:__dxlog_file8,L:159,S:this,C:(I,U)=>I(...U)}),this._isOpen=!1)}};_ts_decorate6([trace.info()],WorkerClientServices.prototype,"_isOpen",void 0),_ts_decorate6([synchronized],WorkerClientServices.prototype,"open",null),_ts_decorate6([synchronized],WorkerClientServices.prototype,"close",null),WorkerClientServices=_ts_decorate6([trace.resource()],WorkerClientServices);var mapLogMeta=$=>$&&{F:$.file,L:$.line,S:$.scope},i$1=Symbol.for("preact-signals");function t(){if(s$1>1)s$1--;else{for(var $,I=!1;h$1!==void 0;){var U=h$1;for(h$1=void 0,f++;U!==void 0;){var q=U.o;if(U.o=void 0,U.f&=-3,!(8&U.f)&&c(U))try{U.c()}catch(G){I||($=G,I=!0)}U=q}}if(f=0,s$1--,I)throw $}}var o=void 0,h$1=void 0,s$1=0,f=0,v$1=0;function e($){if(o!==void 0){var I=$.n;if(I===void 0||I.t!==o)return I={i:0,S:$,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:I},o.s!==void 0&&(o.s.n=I),o.s=I,$.n=I,32&o.f&&$.S(I),I;if(I.i===-1)return I.i=0,I.n!==void 0&&(I.n.p=I.p,I.p!==void 0&&(I.p.n=I.n),I.p=o.s,I.n=void 0,o.s.n=I,o.s=I),I}}function u($){this.v=$,this.i=0,this.n=void 0,this.t=void 0}u.prototype.brand=i$1,u.prototype.h=function(){return!0},u.prototype.S=function($){this.t!==$&&$.e===void 0&&($.x=this.t,this.t!==void 0&&(this.t.e=$),this.t=$)},u.prototype.U=function($){if(this.t!==void 0){var I=$.e,U=$.x;I!==void 0&&(I.x=U,$.e=void 0),U!==void 0&&(U.e=I,$.x=void 0),$===this.t&&(this.t=U)}},u.prototype.subscribe=function($){var I=this;return E(function(){var U=I.value,q=o;o=void 0;try{$(U)}finally{o=q}})},u.prototype.valueOf=function(){return this.value},u.prototype.toString=function(){return this.value+""},u.prototype.toJSON=function(){return this.value},u.prototype.peek=function(){var $=o;o=void 0;try{return this.value}finally{o=$}},Object.defineProperty(u.prototype,"value",{get:function(){var $=e(this);return $!==void 0&&($.i=this.i),this.v},set:function($){if($!==this.v){if(f>100)throw new Error("Cycle detected");this.v=$,this.i++,v$1++,s$1++;try{for(var I=this.t;I!==void 0;I=I.x)I.t.N()}finally{t()}}}});function c($){for(var I=$.s;I!==void 0;I=I.n)if(I.S.i!==I.i||!I.S.h()||I.S.i!==I.i)return!0;return!1}function a($){for(var I=$.s;I!==void 0;I=I.n){var U=I.S.n;if(U!==void 0&&(I.r=U),I.S.n=I,I.i=-1,I.n===void 0){$.s=I;break}}}function l($){for(var I=$.s,U=void 0;I!==void 0;){var q=I.p;I.i===-1?(I.S.U(I),q!==void 0&&(q.n=I.n),I.n!==void 0&&(I.n.p=q)):U=I,I.S.n=I.r,I.r!==void 0&&(I.r=void 0),I=q}$.s=U}function y($){u.call(this,void 0),this.x=$,this.s=void 0,this.g=v$1-1,this.f=4}(y.prototype=new u).h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===v$1))return!0;if(this.g=v$1,this.f|=1,this.i>0&&!c(this))return this.f&=-2,!0;var $=o;try{a(this),o=this;var I=this.x();(16&this.f||this.v!==I||this.i===0)&&(this.v=I,this.f&=-17,this.i++)}catch(U){this.v=U,this.f|=16,this.i++}return o=$,l(this),this.f&=-2,!0},y.prototype.S=function($){if(this.t===void 0){this.f|=36;for(var I=this.s;I!==void 0;I=I.n)I.S.S(I)}u.prototype.S.call(this,$)},y.prototype.U=function($){if(this.t!==void 0&&(u.prototype.U.call(this,$),this.t===void 0)){this.f&=-33;for(var I=this.s;I!==void 0;I=I.n)I.S.U(I)}},y.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var $=this.t;$!==void 0;$=$.x)$.t.N()}},Object.defineProperty(y.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var $=e(this);if(this.h(),$!==void 0&&($.i=this.i),16&this.f)throw this.v;return this.v}});function _($){var I=$.u;if($.u=void 0,typeof I=="function"){s$1++;var U=o;o=void 0;try{I()}catch(q){throw $.f&=-2,$.f|=8,g($),q}finally{o=U,t()}}}function g($){for(var I=$.s;I!==void 0;I=I.n)I.S.U(I);$.x=void 0,$.s=void 0,_($)}function p$1($){if(o!==this)throw new Error("Out-of-order effect");l(this),o=$,this.f&=-2,8&this.f&&g(this),t()}function b$1($){this.x=$,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32}b$1.prototype.c=function(){var $=this.S();try{if(8&this.f||this.x===void 0)return;var I=this.x();typeof I=="function"&&(this.u=I)}finally{$()}},b$1.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,_(this),a(this),s$1++;var $=o;return o=this,p$1.bind(this,$)},b$1.prototype.N=function(){2&this.f||(this.f|=2,this.o=h$1,h$1=this)},b$1.prototype.d=function(){this.f|=8,1&this.f||g(this)};function E($){var I=new b$1($);try{I.c()}catch(U){throw I.d(),U}return I.d.bind(I)}var shim={exports:{}},useSyncExternalStoreShim_production_min={};/**
|
|
923
|
+
Use Chrome, Firefox or Internet Explorer 11`)}var Buffer$2=requireSafeBuffer().Buffer,crypto=commonjsGlobal.crypto||commonjsGlobal.msCrypto;crypto&&crypto.getRandomValues?browser$1.exports=randomBytes:browser$1.exports=oldBrowser;function randomBytes($,I){if($>MAX_UINT32)throw new RangeError("requested too many random bytes");var U=Buffer$2.allocUnsafe($);if($>0)if($>MAX_BYTES)for(var q=0;q<$;q+=MAX_BYTES)crypto.getRandomValues(U.slice(q,q+MAX_BYTES));else crypto.getRandomValues(U);return typeof I=="function"?process.nextTick(function(){I(null,U)}):U}var browserExports=browser$1.exports;/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */let promise;var queueMicrotask_1=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:commonjsGlobal):$=>(promise||(promise=Promise.resolve())).then($).catch(I=>setTimeout(()=>{throw I},0));function assign$3($,I){for(const U in I)Object.defineProperty($,U,{value:I[U],enumerable:!0,configurable:!0});return $}function createError($,I,U){if(!$||typeof $=="string")throw new TypeError("Please pass an Error to err-code");U||(U={}),typeof I=="object"&&(U=I,I=""),I&&(U.code=I);try{return assign$3($,U)}catch{U.message=$.message,U.stack=$.stack;const G=function(){};return G.prototype=Object.create(Object.getPrototypeOf($)),assign$3(new G,U)}}var errCode$1=createError;/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const debug=browserExports$1("simple-peer"),getBrowserRTC=getBrowserRtc,randombytes=browserExports,stream$1=readableBrowserExports,queueMicrotask$1=queueMicrotask_1,errCode=errCode$1,{Buffer:Buffer$1}=buffer,MAX_BUFFERED_AMOUNT$1=64*1024,ICECOMPLETE_TIMEOUT=5*1e3,CHANNEL_CLOSING_TIMEOUT=5*1e3;function filterTrickle($){return $.replace(/a=ice-options:trickle\s\n/g,"")}function warn$1($){console.warn($)}let Peer$1=class pr extends stream$1.Duplex{constructor(I){if(I=Object.assign({allowHalfOpen:!1},I),super(I),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",I),this.channelName=I.initiator?I.channelName||randombytes(20).toString("hex"):null,this.initiator=I.initiator||!1,this.channelConfig=I.channelConfig||pr.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},pr.config,I.config),this.offerOptions=I.offerOptions||{},this.answerOptions=I.answerOptions||{},this.sdpTransform=I.sdpTransform||(U=>U),this.streams=I.streams||(I.stream?[I.stream]:[]),this.trickle=I.trickle!==void 0?I.trickle:!0,this.allowHalfTrickle=I.allowHalfTrickle!==void 0?I.allowHalfTrickle:!1,this.iceCompleteTimeout=I.iceCompleteTimeout||ICECOMPLETE_TIMEOUT,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=I.wrtc&&typeof I.wrtc=="object"?I.wrtc:getBrowserRTC(),!this._wrtc)throw errCode(typeof window>"u"?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(U){this.destroy(errCode(U,"ERR_PC_CONSTRUCTOR"));return}this._isReactNativeWebrtc=typeof this._pc._peerConnectionId=="number",this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=U=>{this._onIceCandidate(U)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(U=>{this.destroy(errCode(U,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=U=>{this._setupData(U)},this.streams&&this.streams.forEach(U=>{this.addStream(U)}),this._pc.ontrack=U=>{this._onTrack(U)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&this._channel.readyState==="open"}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof I=="string")try{I=JSON.parse(I)}catch{I={}}this._debug("signal()"),I.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),I.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(I.transceiverRequest.kind,I.transceiverRequest.init)),I.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(I.candidate):this._pendingCandidates.push(I.candidate)),I.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(I)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(U=>{this._addIceCandidate(U)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(U=>{this.destroy(errCode(U,"ERR_SET_REMOTE_DESCRIPTION"))}),!I.sdp&&!I.candidate&&!I.renegotiate&&!I.transceiverRequest&&this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(I){const U=new this._wrtc.RTCIceCandidate(I);this._pc.addIceCandidate(U).catch(q=>{!U.address||U.address.endsWith(".local")?warn$1("Ignoring unsupported ICE candidate."):this.destroy(errCode(q,"ERR_ADD_ICE_CANDIDATE"))})}send(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(I)}}addTransceiver(I,U){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(I,U),this._needsNegotiation()}catch(q){this.destroy(errCode(q,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:I,init:U}})}}addStream(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),I.getTracks().forEach(U=>{this.addTrack(U,I)})}}addTrack(I,U){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const q=this._senderMap.get(I)||new Map;let G=q.get(U);if(!G)G=this._pc.addTrack(I,U),q.set(U,G),this._senderMap.set(I,q),this._needsNegotiation();else throw G.removed?errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(I,U,q){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const G=this._senderMap.get(I),K=G?G.get(q):null;if(!K)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");U&&this._senderMap.set(U,G),K.replaceTrack!=null?K.replaceTrack(U):this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(I,U){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const q=this._senderMap.get(I),G=q?q.get(U):null;if(!G)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{G.removed=!0,this._pc.removeTrack(G)}catch(K){K.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(G):this.destroy(errCode(K,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),I.getTracks().forEach(U=>{this.removeTrack(U,I)})}}_needsNegotiation(){this._debug("_needsNegotiation"),!this._batchedNegotiation&&(this._batchedNegotiation=!0,queueMicrotask$1(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(I){this._destroy(I,()=>{})}_destroy(I,U){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",I&&(I.message||I)),queueMicrotask$1(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",I&&(I.message||I)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch{}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch{}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,I&&this.emit("error",I),this.emit("close"),U()}))}_setupData(I){if(!I.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=I.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT$1),this.channelName=this._channel.label,this._channel.onmessage=q=>{this._onChannelMessage(q)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=q=>{const G=q.error instanceof Error?q.error:new Error(`Datachannel error: ${q.message} ${q.filename}:${q.lineno}:${q.colno}`);this.destroy(errCode(G,"ERR_DATA_CHANNEL"))};let U=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(U&&this._onChannelClose(),U=!0):U=!1},CHANNEL_CLOSING_TIMEOUT)}_read(){}_write(I,U,q){if(this.destroyed)return q(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(I)}catch(G){return this.destroy(errCode(G,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT$1?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=q):q(null)}else this._debug("write before connect"),this._chunk=I,this._cb=q}_onFinish(){if(this.destroyed)return;const I=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?I():this.once("connect",I)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(I=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(I.sdp=filterTrickle(I.sdp)),I.sdp=this.sdpTransform(I.sdp);const U=()=>{if(this.destroyed)return;const K=this._pc.localDescription||I;this._debug("signal"),this.emit("signal",{type:K.type,sdp:K.sdp})},q=()=>{this._debug("createOffer success"),!this.destroyed&&(this.trickle||this._iceComplete?U():this.once("_iceComplete",U))},G=K=>{this.destroy(errCode(K,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(I).then(q).catch(G)}).catch(I=>{this.destroy(errCode(I,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(I=>{!I.mid&&I.sender.track&&!I.requested&&(I.requested=!0,this.addTransceiver(I.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(I=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(I.sdp=filterTrickle(I.sdp)),I.sdp=this.sdpTransform(I.sdp);const U=()=>{if(this.destroyed)return;const K=this._pc.localDescription||I;this._debug("signal"),this.emit("signal",{type:K.type,sdp:K.sdp}),this.initiator||this._requestMissingTransceivers()},q=()=>{this.destroyed||(this.trickle||this._iceComplete?U():this.once("_iceComplete",U))},G=K=>{this.destroy(errCode(K,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(I).then(q).catch(G)}).catch(I=>{this.destroy(errCode(I,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._pc.connectionState==="failed"&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const I=this._pc.iceConnectionState,U=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",I,U),this.emit("iceStateChange",I,U),(I==="connected"||I==="completed")&&(this._pcReady=!0,this._maybeReady()),I==="failed"&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),I==="closed"&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(I){const U=q=>(Object.prototype.toString.call(q.values)==="[object Array]"&&q.values.forEach(G=>{Object.assign(q,G)}),q);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(q=>{const G=[];q.forEach(K=>{G.push(U(K))}),I(null,G)},q=>I(q)):this._pc.getStats.length>0?this._pc.getStats(q=>{if(this.destroyed)return;const G=[];q.result().forEach(K=>{const Y={};K.names().forEach(J=>{Y[J]=K.stat(J)}),Y.id=K.id,Y.type=K.type,Y.timestamp=K.timestamp,G.push(U(Y))}),I(null,G)},q=>I(q)):I(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const I=()=>{this.destroyed||this.getStats((U,q)=>{if(this.destroyed)return;U&&(q=[]);const G={},K={},Y={};let J=!1;q.forEach(Z=>{(Z.type==="remotecandidate"||Z.type==="remote-candidate")&&(G[Z.id]=Z),(Z.type==="localcandidate"||Z.type==="local-candidate")&&(K[Z.id]=Z),(Z.type==="candidatepair"||Z.type==="candidate-pair")&&(Y[Z.id]=Z)});const X=Z=>{J=!0;let Q=K[Z.localCandidateId];Q&&(Q.ip||Q.address)?(this.localAddress=Q.ip||Q.address,this.localPort=Number(Q.port)):Q&&Q.ipAddress?(this.localAddress=Q.ipAddress,this.localPort=Number(Q.portNumber)):typeof Z.googLocalAddress=="string"&&(Q=Z.googLocalAddress.split(":"),this.localAddress=Q[0],this.localPort=Number(Q[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let ee=G[Z.remoteCandidateId];ee&&(ee.ip||ee.address)?(this.remoteAddress=ee.ip||ee.address,this.remotePort=Number(ee.port)):ee&&ee.ipAddress?(this.remoteAddress=ee.ipAddress,this.remotePort=Number(ee.portNumber)):typeof Z.googRemoteAddress=="string"&&(ee=Z.googRemoteAddress.split(":"),this.remoteAddress=ee[0],this.remotePort=Number(ee[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(q.forEach(Z=>{Z.type==="transport"&&Z.selectedCandidatePairId&&X(Y[Z.selectedCandidatePairId]),(Z.type==="googCandidatePair"&&Z.googActiveConnection==="true"||(Z.type==="candidatepair"||Z.type==="candidate-pair")&&Z.selected)&&X(Z)}),!J&&(!Object.keys(Y).length||Object.keys(K).length)){setTimeout(I,100);return}else this._connecting=!1,this._connected=!0;if(this._chunk){try{this.send(this._chunk)}catch(Q){return this.destroy(errCode(Q,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const Z=this._cb;this._cb=null,Z(null)}typeof this._channel.bufferedAmountLowThreshold!="number"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};I()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT$1||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(I=>{this._pc.removeTrack(I),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(I){this.destroyed||(I.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:I.candidate.candidate,sdpMLineIndex:I.candidate.sdpMLineIndex,sdpMid:I.candidate.sdpMid}}):!I.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),I.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(I){if(this.destroyed)return;let U=I.data;U instanceof ArrayBuffer&&(U=Buffer$1.from(U)),this.push(U)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const I=this._cb;this._cb=null,I(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(I){this.destroyed||I.streams.forEach(U=>{this._debug("on track"),this.emit("track",I.track,U),this._remoteTracks.push({track:I.track,stream:U}),!this._remoteStreams.some(q=>q.id===U.id)&&(this._remoteStreams.push(U),queueMicrotask$1(()=>{this._debug("on stream"),this.emit("stream",U)}))})}_debug(){const I=[].slice.call(arguments);I[0]="["+this._id+"] "+I[0],debug.apply(null,I)}};Peer$1.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer$1.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer$1.channelConfig={};var ConnectionState$1;(function($){$[$.INVALID=0]="INVALID",$[$.CONNECTING=1]="CONNECTING",$[$.CONNECTED=2]="CONNECTED",$[$.CLOSED=3]="CLOSED"})(ConnectionState$1||(ConnectionState$1={}));var emitterComponent=Emitter$1;function Emitter$1($){if($)return mixin($)}function mixin($){for(var I in Emitter$1.prototype)$[I]=Emitter$1.prototype[I];return $}Emitter$1.prototype.on=Emitter$1.prototype.addEventListener=function($,I){return this._callbacks=this._callbacks||{},(this._callbacks[$]=this._callbacks[$]||[]).push(I),this},Emitter$1.prototype.once=function($,I){var U=this;this._callbacks=this._callbacks||{};function q(){U.off($,q),I.apply(this,arguments)}return q.fn=I,this.on($,q),this},Emitter$1.prototype.off=Emitter$1.prototype.removeListener=Emitter$1.prototype.removeAllListeners=Emitter$1.prototype.removeEventListener=function($,I){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var U=this._callbacks[$];if(!U)return this;if(arguments.length==1)return delete this._callbacks[$],this;for(var q,G=0;G<U.length;G++)if(q=U[G],q===I||q.fn===I){U.splice(G,1);break}return this},Emitter$1.prototype.emit=function($){this._callbacks=this._callbacks||{};var I=[].slice.call(arguments,1),U=this._callbacks[$];if(U){U=U.slice(0);for(var q=0,G=U.length;q<G;++q)U[q].apply(this,I)}return this},Emitter$1.prototype.listeners=function($){return this._callbacks=this._callbacks||{},this._callbacks[$]||[]},Emitter$1.prototype.hasListeners=function($){return!!this.listeners($).length};var Emitter=emitterComponent;function Stream(){Emitter.call(this)}Stream.prototype=new Emitter;var stream=Stream;Stream.Stream=Stream,Stream.prototype.pipe=function($,I){var U=this;function q(Q){$.writable&&$.write(Q)===!1&&U.pause&&U.pause()}U.on("data",q);function G(){U.readable&&U.resume&&U.resume()}$.on("drain",G),!$._isStdio&&(!I||I.end!==!1)&&(U.on("end",Y),U.on("close",J));var K=!1;function Y(){K||(K=!0,$.end())}function J(){K||(K=!0,typeof $.destroy=="function"&&$.destroy())}function X(Q){if(Z(),!this.hasListeners("error"))throw Q}U.on("error",X),$.on("error",X);function Z(){U.off("data",q),$.off("drain",G),U.off("end",Y),U.off("close",J),U.off("error",X),$.off("error",X),U.off("end",Z),U.off("close",Z),$.off("end",Z),$.off("close",Z)}return U.on("end",Z),U.on("close",Z),$.on("end",Z),$.on("close",Z),$.emit("pipe",U),$};var encode_1=encode,MSB$1=128,REST$1=127,MSBALL=~REST$1,INT=Math.pow(2,31);function encode($,I,U){if(Number.MAX_SAFE_INTEGER&&$>Number.MAX_SAFE_INTEGER)throw encode.bytes=0,new RangeError("Could not encode varint");I=I||[],U=U||0;for(var q=U;$>=INT;)I[U++]=$&255|MSB$1,$/=128;for(;$&MSBALL;)I[U++]=$&255|MSB$1,$>>>=7;return I[U]=$|0,encode.bytes=U-q+1,I}var decode=read,MSB=128,REST=127;function read($,q){var U=0,q=q||0,G=0,K=q,Y,J=$.length;do{if(K>=J||G>49)throw read.bytes=0,new RangeError("Could not decode varint");Y=$[K++],U+=G<28?(Y&REST)<<G:(Y&REST)*Math.pow(2,G),G+=7}while(Y>=MSB);return read.bytes=K-q,U}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length=function($){return $<N1?1:$<N2?2:$<N3?3:$<N4?4:$<N5?5:$<N6?6:$<N7?7:$<N8?8:$<N9?9:10},varint={encode:encode_1,decode,encodingLength:length},__dxlog_file$4="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/control-extension.ts",HEARTBEAT_RTT_WARN_THRESH=1e4,ControlExtension=class{constructor($,I,U){this.opts=$,this.localPeerId=I,this.remotePeerId=U,this._ctx=new Context({onError:q=>{this._extensionContext.close(q)}}),this.onExtensionRegistered=new Callback}async registerExtension($){await this._rpc.rpc.Control.registerExtension({name:$})}async onOpen($){this._extensionContext=$,this._rpc=createProtoRpcPeer({requested:{Control:protocols.schema.getService("dxos.mesh.teleport.control.ControlService")},exposed:{Control:protocols.schema.getService("dxos.mesh.teleport.control.ControlService")},handlers:{Control:{registerExtension:async I=>{this.onExtensionRegistered.call(I.name)},heartbeat:async I=>(log$2("received heartbeat request",{ts:I.requestTimestamp,localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:66,S:this,C:(U,q)=>U(...q)}),{requestTimestamp:I.requestTimestamp})}},port:await $.createPort("rpc",{contentType:'application/x-protobuf; messageType="dxos.rpc.Message"'}),timeout:this.opts.heartbeatTimeout}),await this._rpc.open(),scheduleTaskInterval(this._ctx,async()=>{const I=new Date;try{const U=await asyncTimeout(this._rpc.rpc.Control.heartbeat({requestTimestamp:I}),this.opts.heartbeatTimeout),q=Date.now();U.requestTimestamp instanceof Date&&(q-U.requestTimestamp.getTime()>(HEARTBEAT_RTT_WARN_THRESH<this.opts.heartbeatTimeout?HEARTBEAT_RTT_WARN_THRESH:this.opts.heartbeatTimeout/2)?log$2.warn(`heartbeat RTT for Teleport > ${HEARTBEAT_RTT_WARN_THRESH/1e3}s`,{rtt:q-U.requestTimestamp.getTime(),localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:103,S:this,C:(G,K)=>G(...K)}):log$2("heartbeat RTT",{rtt:q-U.requestTimestamp.getTime(),localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:109,S:this,C:(G,K)=>G(...K)}))}catch(U){const q=Date.now();if(U instanceof protocols.RpcClosedError){log$2("ignoring RpcClosedError in heartbeat",void 0,{F:__dxlog_file$4,L:119,S:this,C:(G,K)=>G(...K)});return}U instanceof TimeoutError?(log$2("timeout waiting for heartbeat response",{err:U,delay:q-I.getTime()},{F:__dxlog_file$4,L:123,S:this,C:(G,K)=>G(...K)}),this.opts.onTimeout(U)):(log$2.info("other error waiting for heartbeat response",{err:U,delay:q-I.getTime()},{F:__dxlog_file$4,L:126,S:this,C:(G,K)=>G(...K)}),this.opts.onTimeout(U))}},this.opts.heartbeatInterval)}async onClose($){await this._ctx.dispose(),await this._rpc.close()}async onAbort($){await this._ctx.dispose(),await this._rpc.abort()}},__dxlog_file2$3="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/framer.ts",FRAME_LENGTH_SIZE=2,Framer=class{constructor(){this._messageCb=void 0,this._subscribeCb=void 0,this._buffer=void 0,this._sendCallbacks=[],this._bytesSent=0,this._bytesReceived=0,this._writable=!0,this.drain=new Event$1,this._stream=new readableBrowserExports.Duplex({objectMode:!1,read:()=>{this._processResponseQueue()},write:($,I,U)=>{invariant(!this._subscribeCb,"Internal Framer bug. Concurrent writes detected.",{F:__dxlog_file2$3,L:40,S:this,A:["!this._subscribeCb","'Internal Framer bug. Concurrent writes detected.'"]}),this._bytesReceived+=$.length,this._buffer&&this._buffer.length>0?this._buffer=export_Buffer.concat([this._buffer,$]):this._buffer=$,this._messageCb?(this._popFrames(),U()):this._subscribeCb=()=>{this._popFrames(),this._subscribeCb=void 0,U()}}}),this.port={send:$=>new Promise(I=>{const U=encodeFrame($);this._bytesSent+=U.length,this._writable=this._stream.push(U),this._writable?I():this._sendCallbacks.push(I)}),subscribe:$=>{var I;return invariant(!this._messageCb,"Rpc port already has a message listener.",{F:__dxlog_file2$3,L:79,S:this,A:["!this._messageCb","'Rpc port already has a message listener.'"]}),this._messageCb=$,(I=this._subscribeCb)==null||I.call(this),()=>{this._messageCb=void 0}}}}get stream(){return this._stream}get bytesSent(){return this._bytesSent}get bytesReceived(){return this._bytesReceived}get writable(){return this._writable}_processResponseQueue(){const $=this._sendCallbacks;this._sendCallbacks=[],this._writable=!0,this.drain.emit(),$.forEach(I=>I())}_popFrames(){let $=0;for(;$<this._buffer.length;){const I=decodeFrame(this._buffer,$);if(!I)break;$+=I.bytesConsumed,this._messageCb(I.payload)}$<this._buffer.length?this._buffer=this._buffer.subarray($):this._buffer=void 0}destroy(){this._stream.readableLength>0&&log$2("framer destroyed while there are still read bytes in the buffer.",void 0,{F:__dxlog_file2$3,L:140,S:this,C:($,I)=>$(...I)}),this._stream.writableLength>0&&log$2.warn("framer destroyed while there are still write bytes in the buffer.",void 0,{F:__dxlog_file2$3,L:143,S:this,C:($,I)=>$(...I)}),this._stream.destroy()}},decodeFrame=($,I)=>{if($.length<I+FRAME_LENGTH_SIZE)return;const U=$.readUInt16BE(I),q=FRAME_LENGTH_SIZE+U;return $.length<I+q?void 0:{payload:$.subarray(I+FRAME_LENGTH_SIZE,I+q),bytesConsumed:q}},encodeFrame=$=>{const I=export_Buffer.allocUnsafe(FRAME_LENGTH_SIZE+$.length);return I.writeUInt16BE($.length,0),I.set($,FRAME_LENGTH_SIZE),I},__dxlog_file3$1="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/balancer.ts",MAX_CHUNK_SIZE=8192,Balancer=class{constructor($){this._sysChannelId=$,this._lastCallerIndex=0,this._channels=[],this._framer=new Framer,this._sendBuffers=new Map,this._receiveBuffers=new Map,this._sending=!1,this.incomingData=new Event$1,this.stream=this._framer.stream,this._channels.push($),this._framer.port.subscribe(this._processIncomingMessage.bind(this))}get bytesSent(){return this._framer.bytesSent}get bytesReceived(){return this._framer.bytesReceived}get buffersCount(){return this._sendBuffers.size}addChannel($){this._channels.push($)}pushData($,I,U){this._enqueueChunk($,I,U),this._sendChunks().catch(q=>log$2.catch(q,void 0,{F:__dxlog_file3$1,L:75,S:this,C:(G,K)=>G(...K)}))}destroy(){this._sendBuffers.size!==0&&log$2.info("destroying balancer with pending calls",void 0,{F:__dxlog_file3$1,L:80,S:this,C:($,I)=>$(...I)}),this._sendBuffers.clear(),this._framer.destroy()}_processIncomingMessage($){const{channelId:I,dataLength:U,chunk:q}=decodeChunk($,G=>!this._receiveBuffers.has(G));if(!this._receiveBuffers.has(I))q.length<U?this._receiveBuffers.set(I,{buffer:export_Buffer.from(q),msgLength:U}):this.incomingData.emit(q);else{const G=this._receiveBuffers.get(I);if(G.buffer=export_Buffer.concat([G.buffer,q]),G.buffer.length<G.msgLength)return;const K=G.buffer;this._receiveBuffers.delete(I),this.incomingData.emit(K)}}_getNextCallerId(){if(this._sendBuffers.has(this._sysChannelId))return this._sysChannelId;const $=this._lastCallerIndex;return this._lastCallerIndex=(this._lastCallerIndex+1)%this._channels.length,this._channels[$]}_enqueueChunk($,I,U){if(!this._channels.includes(U))throw new Error(`Unknown channel ${U}`);this._sendBuffers.has(U)||this._sendBuffers.set(U,[]);const q=this._sendBuffers.get(U),G=[];for(let K=0;K<$.length;K+=MAX_CHUNK_SIZE)G.push($.subarray(K,K+MAX_CHUNK_SIZE));G.forEach((K,Y)=>{const J=encodeChunk({chunk:K,channelId:U,dataLength:Y===0?$.length:void 0});q.push({msg:J,trigger:Y===G.length-1?I:void 0})})}_getNextChunk(){let $;for(;this._sendBuffers.size>0;){const I=this._getNextCallerId(),U=this._sendBuffers.get(I);if(U&&($=U.shift(),!!$))return U.length===0&&this._sendBuffers.delete(I),$}return null}async _sendChunks(){var I,U;if(this._sending)return;this._sending=!0;let $;for($=this._getNextChunk();$;){this._framer.writable||(log$2("PAUSE for drain",void 0,{F:__dxlog_file3$1,L:179,S:this,C:(q,G)=>q(...G)}),await this._framer.drain.waitForCount(1),log$2("RESUME for drain",void 0,{F:__dxlog_file3$1,L:181,S:this,C:(q,G)=>q(...G)}));try{await this._framer.port.send($.msg),(I=$.trigger)==null||I.wake()}catch(q){log$2("Error sending chunk",{err:q},{F:__dxlog_file3$1,L:187,S:this,C:(G,K)=>G(...K)}),(U=$.trigger)==null||U.throw(q)}$=this._getNextChunk()}invariant(this._sendBuffers.size===0,"sendBuffers not empty",{F:__dxlog_file3$1,L:192,S:this,A:["this._sendBuffers.size === 0","'sendBuffers not empty'"]}),this._sending=!1}},encodeChunk=({channelId:$,dataLength:I,chunk:U})=>{const q=varint.encodingLength($),G=I?varint.encodingLength(I):0,K=export_Buffer.allocUnsafe(q+G+U.length);return varint.encode($,K),I&&varint.encode(I,K,q),K.set(U,q+G),K},decodeChunk=($,I)=>{const U=varint.decode($);let q,G=varint.decode.bytes;I(U)&&(q=varint.decode($,G),G+=varint.decode.bytes);const K=$.subarray(G);return{channelId:U,dataLength:q,chunk:K}};function _ts_decorate$3($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4$2="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/muxer.ts",Command=protocols.schema.getCodecForType("dxos.mesh.muxer.Command"),DEFAULT_SEND_COMMAND_TIMEOUT=6e4,DESTROY_COMMAND_SEND_TIMEOUT=5e3,STATS_INTERVAL=1e3,MAX_SAFE_FRAME_SIZE=1e6,SYSTEM_CHANNEL_ID=0,GRACEFUL_CLOSE_TIMEOUT=3e3,Muxer=class{constructor(){this._balancer=new Balancer(SYSTEM_CHANNEL_ID),this._channelsByLocalId=new Map,this._channelsByTag=new Map,this._ctx=new Context,this._nextId=1,this._closing=!1,this._destroying=!1,this._disposed=!1,this._lastStats=void 0,this._lastChannelStats=new Map,this.afterClosed=new Event$1,this.statsUpdated=new Event$1,this.stream=this._balancer.stream,this._balancer.incomingData.on(async $=>{await this._handleCommand(Command.decode($))})}setSessionId($){this._sessionId=$}get sessionIdString(){return this._sessionId?this._sessionId.truncate():"none"}async createStream($,I={}){const U=this._getOrCreateStream({tag:$,contentType:I.contentType});invariant(!U.push,`Channel already open: ${$}`,{F:__dxlog_file4$2,L:151,S:this,A:["!channel.push","`Channel already open: ${tag}`"]});const q=new readableBrowserExports.Duplex({write:(G,K,Y)=>{this._sendData(U,G).then(()=>Y()).catch(Y)},read:()=>{}});U.push=G=>{U.stats.bytesReceived+=G.length,q.push(G)},U.destroy=G=>{G&&q.listeners("error").length>0?q.destroy(G):q.destroy()};try{await this._sendCommand({openChannel:{id:U.id,tag:U.tag,contentType:U.contentType}},SYSTEM_CHANNEL_ID)}catch(G){throw this._destroyChannel(U,G),G}return q}async createPort($,I={}){const U=this._getOrCreateStream({tag:$,contentType:I.contentType});invariant(!U.push,`Channel already open: ${$}`,{F:__dxlog_file4$2,L:211,S:this,A:["!channel.push","`Channel already open: ${tag}`"]});let q=[],G;U.push=Y=>{U.stats.bytesReceived+=Y.length,G?G(Y):q.push(Y)};const K={send:async(Y,J)=>{await this._sendData(U,Y,J)},subscribe:Y=>{invariant(!G,"Only one subscriber is allowed",{F:__dxlog_file4$2,L:233,S:this,A:["!callback","'Only one subscriber is allowed'"]}),G=Y;for(const J of q)Y(J);q=[]}};try{await this._sendCommand({openChannel:{id:U.id,tag:U.tag,contentType:U.contentType}},SYSTEM_CHANNEL_ID)}catch(Y){throw this._destroyChannel(U,Y),Y}return K}async close($){if(this._destroying){log$2("already destroying, ignoring graceful close request",void 0,{F:__dxlog_file4$2,L:266,S:this,C:(I,U)=>I(...U)});return}if(this._closing){log$2("already closing, ignoring graceful close request",void 0,{F:__dxlog_file4$2,L:270,S:this,C:(I,U)=>I(...U)});return}this._closing=!0,await this._sendCommand({close:{error:$==null?void 0:$.message}},SYSTEM_CHANNEL_ID,DESTROY_COMMAND_SEND_TIMEOUT).catch(async I=>{log$2("error sending close command",{err:I},{F:__dxlog_file4$2,L:285,S:this,C:(U,q)=>U(...q)}),await this._dispose(I)}),await asyncTimeout(this._dispose($),GRACEFUL_CLOSE_TIMEOUT,new protocols.TimeoutError("gracefully closing muxer"))}async destroy($){if(this._destroying){log$2("already destroying, ignoring destroy request",void 0,{F:__dxlog_file4$2,L:298,S:this,C:(I,U)=>I(...U)});return}this._destroying=!0,this._ctx.dispose(),this._closing?(log$2("destroy cancelling graceful close",void 0,{F:__dxlog_file4$2,L:304,S:this,C:(I,U)=>I(...U)}),this._closing=!1):await this._sendCommand({close:{error:$==null?void 0:$.message}},SYSTEM_CHANNEL_ID).catch(async I=>{log$2("error sending courtesy close command",{err:I},{F:__dxlog_file4$2,L:317,S:this,C:(U,q)=>U(...q)})}),this._dispose($).catch(I=>{log$2("error disposing after destroy",{err:I},{F:__dxlog_file4$2,L:322,S:this,C:(U,q)=>U(...q)})})}async _dispose($){var I;if(this._disposed){log$2("already destroyed, ignoring dispose request",void 0,{F:__dxlog_file4$2,L:330,S:this,C:(U,q)=>U(...q)});return}this._ctx.dispose(),await this._balancer.destroy();for(const U of this._channelsByTag.values())(I=U.destroy)==null||I.call(U,$);this._disposed=!0,await this._emitStats(),this.afterClosed.emit($),this._channelsByLocalId.clear(),this._channelsByTag.clear()}async _handleCommand($){if(this._disposed){log$2.warn("Received command after disposed",{cmd:$},{F:__dxlog_file4$2,L:353,S:this,C:(I,U)=>I(...U)});return}if($.close){this._closing?log$2("received close from peer, already closing",void 0,{F:__dxlog_file4$2,L:362,S:this,C:(I,U)=>I(...U)}):(log$2("received peer close, initiating my own graceful close",void 0,{F:__dxlog_file4$2,L:359,S:this,C:(I,U)=>I(...U)}),await this.close(new Error("received peer close")));return}if($.openChannel){const I=this._getOrCreateStream({tag:$.openChannel.tag,contentType:$.openChannel.contentType});I.remoteId=$.openChannel.id;for(const U of I.buffer)await this._sendCommand({data:{channelId:I.remoteId,data:U}},I.id);I.buffer=[]}else if($.data){const I=this._channelsByLocalId.get($.data.channelId)??failUndefined();if(!I.push){log$2.warn("Received data for channel before it was opened",{tag:I.tag},{F:__dxlog_file4$2,L:391,S:this,C:(U,q)=>U(...q)});return}I.push($.data.data)}}async _sendCommand($,I=-1,U=DEFAULT_SEND_COMMAND_TIMEOUT){if(this._disposed){log$2.info("ignoring sendCommand after disposed",{cmd:$},{F:__dxlog_file4$2,L:400,S:this,C:(q,G)=>q(...G)});return}try{const q=new Trigger;this._balancer.pushData(Command.encode($),q,I),await q.wait({timeout:U})}catch(q){await this.destroy(q)}}_getOrCreateStream($){this._channelsByTag.size===0&&scheduleTaskInterval(this._ctx,async()=>this._emitStats(),STATS_INTERVAL);let I=this._channelsByTag.get($.tag);return I||(I={id:this._nextId++,remoteId:null,tag:$.tag,contentType:$.contentType,buffer:[],push:null,destroy:null,stats:{bytesSent:0,bytesReceived:0}},this._channelsByTag.set(I.tag,I),this._channelsByLocalId.set(I.id,I),this._balancer.addChannel(I.id)),I}async _sendData($,I,U){if(I.length>MAX_SAFE_FRAME_SIZE&&log$2.warn("frame size exceeds maximum safe value",{size:I.length,threshold:MAX_SAFE_FRAME_SIZE},{F:__dxlog_file4$2,L:441,S:this,C:(q,G)=>q(...G)}),$.stats.bytesSent+=I.length,$.remoteId===null){$.buffer.push(I);return}await this._sendCommand({data:{channelId:$.remoteId,data:I}},$.id,U)}_destroyChannel($,I){$.destroy&&$.destroy(I),this._channelsByLocalId.delete($.id),this._channelsByTag.delete($.tag)}async _emitStats(){if(this._disposed||this._destroying){if(!this._lastStats)return;const K=this._lastStats;this._lastStats=void 0,K.readBufferSize=0,K.writeBufferSize=0;for(const Y of K.channels)Y.writeBufferSize=0;this.statsUpdated.emit(K),this._lastChannelStats.clear();return}const $=this._balancer.bytesSent,I=this._balancer.bytesReceived,U=Date.now(),q=this._lastStats?(U-this._lastStats.timestamp)/1e3:0,G=(K,Y)=>Y?{bytesSentRate:q?(K.bytesSent-Y.bytesSent)/q:void 0,bytesReceivedRate:q?(K.bytesReceived-Y.bytesReceived)/q:void 0}:{};this._lastStats={timestamp:U,channels:Array.from(this._channelsByTag.values()).map(K=>{const Y={id:K.id,tag:K.tag,contentType:K.contentType,writeBufferSize:K.buffer.length,bytesSent:K.stats.bytesSent,bytesReceived:K.stats.bytesReceived,...G(K.stats,this._lastChannelStats.get(K.id))};return this._lastChannelStats.set(K.id,Y),Y}),bytesSent:$,bytesReceived:I,...G({bytesSent:$,bytesReceived:I},this._lastStats),readBufferSize:this._balancer.stream.readableLength,writeBufferSize:this._balancer.stream.writableLength},this.statsUpdated.emit(this._lastStats)}};_ts_decorate$3([logInfo],Muxer.prototype,"sessionIdString",null);function _ts_decorate2$2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5$1="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/teleport.ts",CONTROL_HEARTBEAT_INTERVAL=1e4,CONTROL_HEARTBEAT_TIMEOUT=6e4,Teleport=class{constructor({initiator:$,localPeerId:I,remotePeerId:U}){this._ctx=new Context({onError:q=>{this.destroy(q).catch(()=>{log$2.error("Error during destroy",q,{F:__dxlog_file5$1,L:39,S:this,C:(G,K)=>G(...K)})})}}),this._muxer=new Muxer,this._extensions=new Map,this._remoteExtensions=new Set,this._open=!1,this._destroying=!1,this._aborting=!1,invariant(typeof $=="boolean",void 0,{F:__dxlog_file5$1,L:56,S:this,A:["typeof initiator === 'boolean'",""]}),invariant(PublicKey.isPublicKey(I),void 0,{F:__dxlog_file5$1,L:57,S:this,A:["PublicKey.isPublicKey(localPeerId)",""]}),invariant(PublicKey.isPublicKey(U),void 0,{F:__dxlog_file5$1,L:58,S:this,A:["PublicKey.isPublicKey(remotePeerId)",""]}),this.initiator=$,this.localPeerId=I,this.remotePeerId=U,this._control=new ControlExtension({heartbeatInterval:CONTROL_HEARTBEAT_INTERVAL,heartbeatTimeout:CONTROL_HEARTBEAT_TIMEOUT,onTimeout:()=>{this._destroying||this._aborting||(log$2.info("abort teleport due to onTimeout in ControlExtension",void 0,{F:__dxlog_file5$1,L:71,S:this,C:(q,G)=>q(...G)}),this.abort(new protocols.TimeoutError("control extension")).catch(q=>log$2.catch(q,void 0,{F:__dxlog_file5$1,L:72,S:this,C:(G,K)=>G(...K)})))}},this.localPeerId,this.remotePeerId),this._control.onExtensionRegistered.set(async q=>{if(log$2("remote extension",{name:q},{F:__dxlog_file5$1,L:80,S:this,C:(G,K)=>G(...K)}),invariant(!this._remoteExtensions.has(q),"Remote extension already exists",{F:__dxlog_file5$1,L:81,S:this,A:["!this._remoteExtensions.has(name)","'Remote extension already exists'"]}),this._remoteExtensions.add(q),this._extensions.has(q))try{await this._openExtension(q)}catch(G){await this.destroy(G)}}),this._muxer.stream.on("close",async()=>{if(this._destroying||this._aborting){log$2("destroy teleport due to muxer stream close, skipping due to already destroying/aborting",void 0,{F:__dxlog_file5$1,L:97,S:this,C:(q,G)=>q(...G)});return}await this.destroy()}),this._muxer.stream.on("error",async q=>{await this.destroy(q)}),this._muxer.statsUpdated.on(q=>{log$2.trace("dxos.mesh.teleport.stats",{localPeerId:I,remotePeerId:U,bytesSent:q.bytesSent,bytesSentRate:q.bytesSentRate,bytesReceived:q.bytesReceived,bytesReceivedRate:q.bytesReceivedRate,channels:q.channels},{F:__dxlog_file5$1,L:110,S:this,C:(G,K)=>G(...K)})})}get sessionIdString(){return this._sessionId?this._sessionId.truncate():"none"}get stream(){return this._muxer.stream}get stats(){return this._muxer.statsUpdated}async open($=PublicKey.random()){this._sessionId=$,log$2("open",void 0,{F:__dxlog_file5$1,L:144,S:this,C:(I,U)=>I(...U)}),this._setExtension("dxos.mesh.teleport.control",this._control),await this._openExtension("dxos.mesh.teleport.control"),this._open=!0,this._muxer.setSessionId($)}async close($){await this.destroy($)}async abort($){if(!(this._aborting||this._destroying)&&(this._aborting=!0,!this._ctx.disposed)){await this._ctx.dispose();for(const I of this._extensions.values())try{await I.onAbort($)}catch(U){log$2.catch(U,void 0,{F:__dxlog_file5$1,L:173,S:this,C:(q,G)=>q(...G)})}await this._muxer.destroy($)}}async destroy($){if(!(this._destroying||this._aborting)&&(this._destroying=!0,!this._ctx.disposed)){await this._ctx.dispose();for(const I of this._extensions.values())try{await I.onClose($)}catch(U){log$2.catch(U,void 0,{F:__dxlog_file5$1,L:197,S:this,C:(q,G)=>q(...G)})}await this._muxer.close()}}addExtension($,I){if(!this._open)throw new Error("Not open");log$2("addExtension",{name:$},{F:__dxlog_file5$1,L:209,S:this,C:(U,q)=>U(...q)}),this._setExtension($,I),scheduleTask(this._ctx,async()=>{try{await this._control.registerExtension($)}catch(U){if(U instanceof protocols.RpcClosedError)return;throw U}}),this._remoteExtensions.has($)&&scheduleTask(this._ctx,async()=>{await this._openExtension($)})}_setExtension($,I){invariant(!$.includes("/"),"Invalid extension name",{F:__dxlog_file5$1,L:233,S:this,A:["!extensionName.includes('/')","'Invalid extension name'"]}),invariant(!this._extensions.has($),"Extension already exists",{F:__dxlog_file5$1,L:234,S:this,A:["!this._extensions.has(extensionName)","'Extension already exists'"]}),this._extensions.set($,I)}async _openExtension($){log$2("open extension",{extensionName:$},{F:__dxlog_file5$1,L:239,S:this,C:(q,G)=>q(...G)});const I=this._extensions.get($)??failUndefined(),U={initiator:this.initiator,localPeerId:this.localPeerId,remotePeerId:this.remotePeerId,createPort:async(q,G)=>(invariant(!q.includes("/"),"Invalid channel name",{F:__dxlog_file5$1,L:247,S:this,A:["!channelName.includes('/')","'Invalid channel name'"]}),this._muxer.createPort(`${$}/${q}`,G)),createStream:async(q,G)=>(invariant(!q.includes("/"),"Invalid channel name",{F:__dxlog_file5$1,L:251,S:this,A:["!channelName.includes('/')","'Invalid channel name'"]}),this._muxer.createStream(`${$}/${q}`,G)),close:q=>{runInContextAsync(this._ctx,async()=>{await this.close(q)})}};await I.onOpen(U),log$2("extension opened",{extensionName:$},{F:__dxlog_file5$1,L:262,S:this,C:(q,G)=>q(...G)})}};_ts_decorate2$2([logInfo],Teleport.prototype,"sessionIdString",null),_ts_decorate2$2([synchronized],Teleport.prototype,"abort",null),_ts_decorate2$2([synchronized],Teleport.prototype,"destroy",null);var __require=($=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy($,{get:(I,U)=>(typeof require<"u"?require:I)[U]}):$)(function($){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+$+'" is not supported')});function _ts_decorate$2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$3="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection.ts",STARTING_SIGNALLING_DELAY=10,TRANSPORT_CONNECTION_TIMEOUT=1e4,TRANSPORT_STATS_INTERVAL=5e3,MAX_SIGNALLING_DELAY=300,ConnectionState;(function($){$.CREATED="CREATED",$.INITIAL="INITIAL",$.CONNECTING="CONNECTING",$.CONNECTED="CONNECTED",$.CLOSING="CLOSING",$.CLOSED="CLOSED",$.ABORTING="ABORTING",$.ABORTED="ABORTED"})(ConnectionState||(ConnectionState={}));var Connection=class{constructor($,I,U,q,G,K,Y,J,X){this.topic=$,this.ownId=I,this.remoteId=U,this.sessionId=q,this.initiator=G,this._signalMessaging=K,this._protocol=Y,this._transportFactory=J,this._callbacks=X,this._ctx=new Context,this.connectedTimeoutContext=new Context,this._state="CREATED",this._incomingSignalBuffer=[],this._outgoingSignalBuffer=[],this.stateChanged=new Event$1,this.errors=new ErrorStream,this._instanceId=PublicKey.random().toHex(),this.transportStats=new Event$1,this._signalSendTask=new DeferredTask(this._ctx,async()=>{await this._flushSignalBuffer()}),this._signallingDelay=STARTING_SIGNALLING_DELAY,log$2.trace("dxos.mesh.connection.construct",{sessionId:this.sessionId,topic:this.topic,localPeerId:this.ownId,remotePeerId:this.remoteId,initiator:this.initiator},{F:__dxlog_file$3,L:134,S:this,C:(Z,Q)=>Z(...Q)})}get sessionIdString(){return this.sessionId.truncate()}get state(){return this._state}get transport(){return this._transport}get protocol(){return this._protocol}async openConnection(){invariant(this._state==="INITIAL","Invalid state.",{F:__dxlog_file$3,L:164,S:this,A:["this._state === ConnectionState.INITIAL","'Invalid state.'"]}),log$2.trace("dxos.mesh.connection.open-connection",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file$3,L:165,S:this,C:($,I)=>$(...I)}),log$2.trace("dxos.mesh.connection.open",{sessionId:this.sessionId,topic:this.topic,localPeerId:this.ownId,remotePeerId:this.remoteId,initiator:this.initiator},{F:__dxlog_file$3,L:166,S:this,C:($,I)=>$(...I)}),this._changeState("CONNECTING"),this._protocol.open(this.sessionId).catch($=>{this.errors.raise($)}),this._protocol.stream.on("close",()=>{log$2("protocol stream closed",void 0,{F:__dxlog_file$3,L:183,S:this,C:($,I)=>$(...I)}),this.close(new protocols.ProtocolError("protocol stream closed")).catch($=>this.errors.raise($))}),scheduleTask(this.connectedTimeoutContext,async()=>{log$2.info(`timeout waiting ${TRANSPORT_CONNECTION_TIMEOUT/1e3}s for transport to connect, aborting`,void 0,{F:__dxlog_file$3,L:190,S:this,C:($,I)=>$(...I)}),await this.abort(new protocols.TimeoutError(`${TRANSPORT_CONNECTION_TIMEOUT/1e3}s for transport to connect`)).catch($=>this.errors.raise($))},TRANSPORT_CONNECTION_TIMEOUT),invariant(!this._transport,void 0,{F:__dxlog_file$3,L:198,S:this,A:["!this._transport",""]}),this._transport=this._transportFactory.createTransport({initiator:this.initiator,stream:this._protocol.stream,sendSignal:async $=>this._sendSignal($),sessionId:this.sessionId}),await this._transport.open(),this._transport.connected.once(async()=>{var $,I;this._changeState("CONNECTED"),await this.connectedTimeoutContext.dispose(),(I=($=this._callbacks)==null?void 0:$.onConnected)==null||I.call($),scheduleTaskInterval(this._ctx,async()=>this._emitTransportStats(),TRANSPORT_STATS_INTERVAL)}),this._transport.closed.once(()=>{this._transport=void 0,log$2("abort triggered by transport close",void 0,{F:__dxlog_file$3,L:218,S:this,C:($,I)=>$(...I)}),this.abort().catch($=>this.errors.raise($))}),this._transport.errors.handle(async $=>{log$2("transport error:",{err:$},{F:__dxlog_file$3,L:223,S:this,C:(I,U)=>I(...U)}),this.closeReason||(this.closeReason=$==null?void 0:$.message),$ instanceof protocols.ConnectionResetError?(log$2.info("aborting due to transport ConnectionResetError",void 0,{F:__dxlog_file$3,L:230,S:this,C:(I,U)=>I(...U)}),this.abort().catch(I=>this.errors.raise(I))):$ instanceof protocols.ConnectivityError?(log$2.info("aborting due to transport ConnectivityError",void 0,{F:__dxlog_file$3,L:233,S:this,C:(I,U)=>I(...U)}),this.abort().catch(I=>this.errors.raise(I))):$ instanceof protocols.UnknownProtocolError&&log$2.warn("unsure what to do with UnknownProtocolError, will keep on truckin",{err:$},{F:__dxlog_file$3,L:236,S:this,C:(I,U)=>I(...U)}),this._state!=="CLOSED"&&this._state!=="CLOSING"&&(await this.connectedTimeoutContext.dispose(),this.errors.raise($))});for(const $ of this._incomingSignalBuffer)this._transport.onSignal($);this._incomingSignalBuffer=[],log$2.trace("dxos.mesh.connection.open-connection",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file$3,L:252,S:this,C:($,I)=>$(...I)})}async abort($){var I,U,q;if(log$2("aborting...",{err:$},{F:__dxlog_file$3,L:259,S:this,C:(G,K)=>G(...K)}),this._state==="CLOSED"||this._state==="ABORTED"){log$2(`abort ignored: already ${this._state}`,this.closeReason,{F:__dxlog_file$3,L:261,S:this,C:(G,K)=>G(...K)});return}await this.connectedTimeoutContext.dispose(),this._changeState("ABORTING"),this.closeReason||(this.closeReason=$==null?void 0:$.message),await this._ctx.dispose();try{log$2("aborting protocol... ",void 0,{F:__dxlog_file$3,L:275,S:this,C:(G,K)=>G(...K)}),await this._protocol.abort()}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:278,S:this,C:(K,Y)=>K(...Y)})}try{await((I=this._transport)==null?void 0:I.close())}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:285,S:this,C:(K,Y)=>K(...Y)})}try{(q=(U=this._callbacks)==null?void 0:U.onClosed)==null||q.call(U,$)}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:291,S:this,C:(K,Y)=>K(...Y)})}this._changeState("ABORTED")}async close($){var U,q,G,K;if(this.closeReason?this.closeReason+=`; ${$==null?void 0:$.message}`:this.closeReason=$==null?void 0:$.message,this._state==="CLOSED"||this._state==="ABORTING"||this._state==="ABORTED")return;const I=this._state;if(this._changeState("CLOSING"),await this.connectedTimeoutContext.dispose(),await this._ctx.dispose(),log$2("closing...",{peerId:this.ownId},{F:__dxlog_file$3,L:316,S:this,C:(Y,J)=>Y(...J)}),I==="CONNECTED"){try{await this._protocol.close()}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:323,S:this,C:(J,X)=>J(...X)})}try{await((U=this._transport)==null?void 0:U.close())}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:330,S:this,C:(J,X)=>J(...X)})}}else{log$2(`graceful close requested when we were in ${I} state? aborting`,void 0,{F:__dxlog_file$3,L:333,S:this,C:(Y,J)=>Y(...J)});try{await this._protocol.abort()}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:337,S:this,C:(J,X)=>J(...X)})}try{await((q=this._transport)==null?void 0:q.close())}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:342,S:this,C:(J,X)=>J(...X)})}}log$2("closed",{peerId:this.ownId},{F:__dxlog_file$3,L:346,S:this,C:(Y,J)=>Y(...J)}),this._changeState("CLOSED"),(K=(G=this._callbacks)==null?void 0:G.onClosed)==null||K.call(G,$)}_sendSignal($){this._outgoingSignalBuffer.push($),this._signalSendTask.schedule()}async _flushSignalBuffer(){var $;if(this._outgoingSignalBuffer.length!==0)try{await cancelWithContext(this._ctx,sleep(this._signallingDelay)),this._signallingDelay=Math.min(this._signallingDelay*2,MAX_SIGNALLING_DELAY);const I=[...this._outgoingSignalBuffer];this._outgoingSignalBuffer.length=0,await this._signalMessaging.signal({author:this.ownId,recipient:this.remoteId,sessionId:this.sessionId,topic:this.topic,data:{signalBatch:{signals:I}}})}catch(I){if(I instanceof protocols.CancelledError||I instanceof Error&&(($=I.message)!=null&&$.includes("CANCELLED")))return;log$2.info("signal message failed to deliver",{err:I},{F:__dxlog_file$3,L:384,S:this,C:(U,q)=>U(...q)}),await this.close(new protocols.ConnectivityError("signal message failed to deliver",I))}}async signal($){var U,q;if(invariant($.sessionId,void 0,{F:__dxlog_file$3,L:393,S:this,A:["msg.sessionId",""]}),!$.sessionId.equals(this.sessionId)){log$2("dropping signal for incorrect session id",void 0,{F:__dxlog_file$3,L:395,S:this,C:(G,K)=>G(...K)});return}invariant($.data.signal||$.data.signalBatch,void 0,{F:__dxlog_file$3,L:398,S:this,A:["msg.data.signal || msg.data.signalBatch",""]}),invariant((U=$.author)==null?void 0:U.equals(this.remoteId),void 0,{F:__dxlog_file$3,L:399,S:this,A:["msg.author?.equals(this.remoteId)",""]}),invariant((q=$.recipient)==null?void 0:q.equals(this.ownId),void 0,{F:__dxlog_file$3,L:400,S:this,A:["msg.recipient?.equals(this.ownId)",""]});const I=$.data.signalBatch?$.data.signalBatch.signals??[]:[$.data.signal];for(const G of I)G&&(["CREATED","INITIAL"].includes(this.state)?(log$2("buffered signal",{peerId:this.ownId,remoteId:this.remoteId,msg:$.data},{F:__dxlog_file$3,L:409,S:this,C:(K,Y)=>K(...Y)}),this._incomingSignalBuffer.push(G)):(invariant(this._transport,"Connection not ready to accept signals.",{F:__dxlog_file$3,L:412,S:this,A:["this._transport","'Connection not ready to accept signals.'"]}),log$2("received signal",{peerId:this.ownId,remoteId:this.remoteId,msg:$.data},{F:__dxlog_file$3,L:413,S:this,C:(K,Y)=>K(...Y)}),await this._transport.onSignal(G)))}initiate(){this._changeState("INITIAL")}_changeState($){log$2("stateChanged",{from:this._state,to:$,peerId:this.ownId},{F:__dxlog_file$3,L:424,S:this,C:(I,U)=>I(...U)}),invariant($!==this._state,"Already in this state.",{F:__dxlog_file$3,L:425,S:this,A:["state !== this._state","'Already in this state.'"]}),this._state=$,this.stateChanged.emit($)}async _emitTransportStats(){var I;const $=await((I=this.transport)==null?void 0:I.getStats());$&&this.transportStats.emit($)}};_ts_decorate$2([logInfo],Connection.prototype,"sessionIdString",null),_ts_decorate$2([synchronized],Connection.prototype,"abort",null),_ts_decorate$2([synchronized],Connection.prototype,"close",null);var __dxlog_file2$2="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/swarm-messenger.ts",SwarmMessage=protocols.schema.getCodecForType("dxos.mesh.swarm.SwarmMessage"),SwarmMessenger=class{constructor({sendMessage:$,onSignal:I,onOffer:U,topic:q}){this._ctx=new Context,this._offerRecords=new ComplexMap(G=>G.toHex()),this._sendMessage=$,this._onSignal=I,this._onOffer=U,this._topic=q}async receiveMessage({author:$,recipient:I,payload:U}){var G,K,Y,J;if(U.type_url!=="dxos.mesh.swarm.SwarmMessage")return;const q=SwarmMessage.decode(U.value);this._topic.equals(q.topic)&&(log$2("received",{from:$,to:I,msg:q},{F:__dxlog_file2$2,L:69,S:this,C:(X,Z)=>X(...Z)}),(G=q.data)!=null&&G.offer?await this._handleOffer({author:$,recipient:I,message:q}):(K=q.data)!=null&&K.answer?await this._resolveAnswers(q):(Y=q.data)!=null&&Y.signal?await this._handleSignal({author:$,recipient:I,message:q}):(J=q.data)!=null&&J.signalBatch?await this._handleSignal({author:$,recipient:I,message:q}):log$2.warn("unknown message",{message:q},{F:__dxlog_file2$2,L:80,S:this,C:(X,Z)=>X(...Z)}))}async signal($){var I,U;invariant(((I=$.data)==null?void 0:I.signal)||((U=$.data)==null?void 0:U.signalBatch),"Invalid message",{F:__dxlog_file2$2,L:85,S:this,A:["message.data?.signal || message.data?.signalBatch","'Invalid message'"]}),await this._sendReliableMessage({author:$.author,recipient:$.recipient,message:$})}async offer($){const I={...$,messageId:PublicKey.random()};return new Promise((U,q)=>{this._offerRecords.set(I.messageId,{resolve:U}),this._sendReliableMessage({author:$.author,recipient:$.recipient,message:I}).catch(G=>q(G))})}async _sendReliableMessage({author:$,recipient:I,message:U}){const q={...U,messageId:U.messageId??PublicKey.random()};log$2("sending",{from:$,to:I,msg:q},{F:__dxlog_file2$2,L:123,S:this,C:(G,K)=>G(...K)}),await this._sendMessage({author:$,recipient:I,payload:{type_url:"dxos.mesh.swarm.SwarmMessage",value:SwarmMessage.encode(q)}})}async _resolveAnswers($){var U,q,G;invariant((q=(U=$.data)==null?void 0:U.answer)==null?void 0:q.offerMessageId,"No offerMessageId",{F:__dxlog_file2$2,L:135,S:this,A:["message.data?.answer?.offerMessageId","'No offerMessageId'"]});const I=this._offerRecords.get($.data.answer.offerMessageId);I&&(this._offerRecords.delete($.data.answer.offerMessageId),invariant((G=$.data)==null?void 0:G.answer,"No answer",{F:__dxlog_file2$2,L:139,S:this,A:["message.data?.answer","'No answer'"]}),log$2("resolving",{answer:$.data.answer},{F:__dxlog_file2$2,L:140,S:this,C:(K,Y)=>K(...Y)}),I.resolve($.data.answer))}async _handleOffer({author:$,recipient:I,message:U}){invariant(U.data.offer,"No offer",{F:__dxlog_file2$2,L:154,S:this,A:["message.data.offer","'No offer'"]});const q={author:$,recipient:I,...U,data:{offer:U.data.offer}},G=await this._onOffer(q);G.offerMessageId=U.messageId;try{await this._sendReliableMessage({author:I,recipient:$,message:{topic:U.topic,sessionId:U.sessionId,data:{answer:G}}})}catch(K){K instanceof protocols.TimeoutError?log$2.info("timeout sending answer to offer",{err:K},{F:__dxlog_file2$2,L:175,S:this,C:(Y,J)=>Y(...J)}):log$2.info("error sending answer to offer",{err:K},{F:__dxlog_file2$2,L:177,S:this,C:(Y,J)=>Y(...J)})}}async _handleSignal({author:$,recipient:I,message:U}){invariant(U.messageId,void 0,{F:__dxlog_file2$2,L:191,S:this,A:["message.messageId",""]}),invariant(U.data.signal||U.data.signalBatch,"Invalid message",{F:__dxlog_file2$2,L:192,S:this,A:["message.data.signal || message.data.signalBatch","'Invalid message'"]});const q={author:$,recipient:I,...U,data:{signal:U.data.signal,signalBatch:U.data.signalBatch}};await this._onSignal(q)}};function _ts_decorate2$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file3="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/peer.ts",ConnectionDisplacedError=class extends protocols.SystemError{constructor(){super("Connection displaced by remote initiator.")}},CONNECTION_COUNTS_STABLE_AFTER=5e3,Peer=class{constructor($,I,U,q,G,K,Y,J){this.id=$,this.topic=I,this.localPeerId=U,this._signalMessaging=q,this._protocolProvider=G,this._transportFactory=K,this._connectionLimiter=Y,this._callbacks=J,this._availableAfter=0,this.availableToConnect=!0,this._ctx=new Context,this.advertizing=!1,this.initiating=!1,this.connectionDisplaced=new Event$1}async onOffer($){var U;const I=$.author;if(this.connection&&![ConnectionState.CREATED,ConnectionState.INITIAL,ConnectionState.CONNECTING].includes(this.connection.state))return log$2.info(`received offer when connection already in ${this.connection.state} state`,void 0,{F:__dxlog_file3,L:114,S:this,C:(q,G)=>q(...G)}),{accept:!1};if(this.connection||this.initiating)if(I.toHex()<this.localPeerId.toHex())log$2("close local connection",{localPeerId:this.id,topic:this.topic,remotePeerId:this.localPeerId,sessionId:(U=this.connection)==null?void 0:U.sessionId},{F:__dxlog_file3,L:123,S:this,C:(q,G)=>q(...G)}),this.connection&&await this.closeConnection(new ConnectionDisplacedError);else return{accept:!1};if(await this._callbacks.onOffer(I)&&!this.connection){invariant($.sessionId,void 0,{F:__dxlog_file3,L:143,S:this,A:["message.sessionId",""]});const q=this._createConnection(!1,$.sessionId);try{await this._connectionLimiter.connecting($.sessionId),q.initiate(),await q.openConnection()}catch(G){G instanceof protocols.CancelledError||log$2.info("connection error",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,err:G},{F:__dxlog_file3,L:153,S:this,C:(K,Y)=>K(...Y)}),await this.closeConnection(G)}return{accept:!0}}return{accept:!1}}async initiateConnection(){invariant(!this.initiating,"Initiation in progress.",{F:__dxlog_file3,L:170,S:this,A:["!this.initiating","'Initiation in progress.'"]}),invariant(!this.connection,"Already connected.",{F:__dxlog_file3,L:171,S:this,A:["!this.connection","'Already connected.'"]});const $=PublicKey.random();log$2("initiating...",{id:this.id,topic:this.topic,peerId:this.id,sessionId:$},{F:__dxlog_file3,L:173,S:this,C:(q,G)=>q(...G)});const I=this._createConnection(!0,$);this.initiating=!0;let U;try{if(await this._connectionLimiter.connecting($),I.initiate(),U=await this._signalMessaging.offer({author:this.localPeerId,recipient:this.id,sessionId:$,topic:this.topic,data:{offer:{}}}),log$2("received",{answer:U,topic:this.topic,ownId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3,L:190,S:this,C:(q,G)=>q(...G)}),I.state!==ConnectionState.INITIAL){log$2("ignoring response",void 0,{F:__dxlog_file3,L:192,S:this,C:(q,G)=>q(...G)});return}}catch(q){throw log$2("initiation error: send offer",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3,L:196,S:this,C:(G,K)=>G(...K)}),await I.abort(q),q}finally{this.initiating=!1}try{if(!U.accept){this._callbacks.onRejected();return}}catch(q){throw log$2("initiation error: accept answer",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3,L:209,S:this,C:(G,K)=>G(...K)}),await I.abort(q),q}finally{this.initiating=!1}try{log$2("opening connection as initiator",void 0,{F:__dxlog_file3,L:222,S:this,C:(q,G)=>q(...G)}),await I.openConnection(),this._callbacks.onAccepted()}catch(q){throw log$2("initiation error: open connection",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3,L:226,S:this,C:(G,K)=>G(...K)}),log$2.warn("closing connection due to unhandled error on openConnection",{err:q},{F:__dxlog_file3,L:233,S:this,C:(G,K)=>G(...K)}),await this.closeConnection(q),q}finally{this.initiating=!1}}_createConnection($,I){var q;log$2("creating connection",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$,sessionId:I},{F:__dxlog_file3,L:247,S:this,C:(G,K)=>G(...K)}),invariant(!this.connection,"Already connected.",{F:__dxlog_file3,L:254,S:this,A:["!this.connection","'Already connected.'"]});const U=new Connection(this.topic,this.localPeerId,this.id,I,$,this._signalMessaging,this._protocolProvider({initiator:$,localPeerId:this.localPeerId,remotePeerId:this.id,topic:this.topic}),this._transportFactory,{onConnected:()=>{this.availableToConnect=!0,this._lastConnectionTime=Date.now(),this._callbacks.onConnected(),this._connectionLimiter.doneConnecting(I),log$2.trace("dxos.mesh.connection.connected",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$},{F:__dxlog_file3,L:273,S:this,C:(G,K)=>G(...K)})},onClosed:G=>{log$2("connection closed",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$},{F:__dxlog_file3,L:282,S:this,C:(K,Y)=>K(...Y)}),this._connectionLimiter.doneConnecting(I),invariant(this.connection===U,"Connection mismatch (race condition).",{F:__dxlog_file3,L:287,S:this,A:["this.connection === connection","'Connection mismatch (race condition).'"]}),log$2.trace("dxos.mesh.connection.closed",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$},{F:__dxlog_file3,L:289,S:this,C:(K,Y)=>K(...Y)}),G instanceof ConnectionDisplacedError?this.connectionDisplaced.emit(this.connection):(this._lastConnectionTime&&this._lastConnectionTime+CONNECTION_COUNTS_STABLE_AFTER<Date.now()?this._availableAfter=0:(this.availableToConnect=!1,this._availableAfter=increaseInterval(this._availableAfter)),this._callbacks.onDisconnected(),scheduleTask(this._connectionCtx,()=>{this.availableToConnect=!0,this._callbacks.onPeerAvailable()},this._availableAfter)),this.connection=void 0}});return this._callbacks.onInitiated(U),(q=this._connectionCtx)==null||q.dispose(),this._connectionCtx=this._ctx.derive(),U.errors.handle(G=>{log$2.info("connection error, closing",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$,err:G},{F:__dxlog_file3,L:329,S:this,C:(K,Y)=>K(...Y)}),log$2.trace("dxos.mesh.connection.error",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$,err:G},{F:__dxlog_file3,L:336,S:this,C:(K,Y)=>K(...Y)}),this.closeConnection(G)}),this.connection=U,U}async closeConnection($){if(!this.connection)return;const I=this.connection;log$2("closing...",{peerId:this.id,sessionId:I.sessionId},{F:__dxlog_file3,L:361,S:this,C:(U,q)=>U(...q)}),await I.close($),log$2("closed",{peerId:this.id,sessionId:I.sessionId},{F:__dxlog_file3,L:367,S:this,C:(U,q)=>U(...q)})}async onSignal($){if(!this.connection){log$2("dropping signal message for non-existent connection",{message:$},{F:__dxlog_file3,L:372,S:this,C:(I,U)=>I(...U)});return}await this.connection.signal($)}async destroy($){var I;await this._ctx.dispose(),log$2("Destroying peer",{peerId:this.id,topic:this.topic},{F:__dxlog_file3,L:382,S:this,C:(U,q)=>U(...q)}),await((I=this==null?void 0:this.connection)==null?void 0:I.close($))}};_ts_decorate2$1([synchronized],Peer.prototype,"destroy",null);var increaseInterval=$=>$===0?50:$<500?500:$<1e3?1e3:$<5e3?5e3:1e4;function _ts_decorate3$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4$1="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm.ts",INITIATION_DELAY=100,getClassName=$=>Object.getPrototypeOf($).constructor.name,Swarm=class{constructor($,I,U,q,G,K,Y,J,X=INITIATION_DELAY){this._topic=$,this._ownPeerId=I,this._topology=U,this._protocolProvider=q,this._messenger=G,this._transportFactory=K,this._label=Y,this._connectionLimiter=J,this._initiationDelay=X,this._ctx=new Context,this._listeningHandle=void 0,this._peers=new ComplexMap(PublicKey.hash),this._instanceId=PublicKey.random().toHex(),this.connectionAdded=new Event$1,this.disconnected=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream,log$2.trace("dxos.mesh.swarm.constructor",protocols.trace.begin({id:this._instanceId,data:{topic:this._topic.toHex(),peerId:this._ownPeerId.toHex()}}),{F:__dxlog_file4$1,L:89,S:this,C:(Z,Q)=>Z(...Q)}),log$2("creating swarm",{peerId:I},{F:__dxlog_file4$1,L:93,S:this,C:(Z,Q)=>Z(...Q)}),U.init(this._getSwarmController()),this._swarmMessenger=new SwarmMessenger({sendMessage:async Z=>await this._messenger.sendMessage(Z),onSignal:async Z=>await this.onSignal(Z),onOffer:async Z=>await this.onOffer(Z),topic:this._topic}),log$2.trace("dxos.mesh.swarm.constructor",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file4$1,L:102,S:this,C:(Z,Q)=>Z(...Q)})}get connections(){return Array.from(this._peers.values()).map($=>$.connection).filter(isNotNullOrUndefined)}get ownPeerId(){return this._ownPeerId}get label(){return this._label}get topic(){return this._topic}async open(){invariant(!this._listeningHandle,void 0,{F:__dxlog_file4$1,L:129,S:this,A:["!this._listeningHandle",""]}),this._listeningHandle=await this._messenger.listen({peerId:this._ownPeerId,payloadType:"dxos.mesh.swarm.SwarmMessage",onMessage:async $=>{await this._swarmMessenger.receiveMessage($).catch(I=>log$2.info("Error while receiving message",{err:I},{F:__dxlog_file4$1,L:137,S:this,C:(U,q)=>U(...q)}))}})}async destroy(){var $;log$2("destroying...",void 0,{F:__dxlog_file4$1,L:143,S:this,C:(I,U)=>I(...U)}),await(($=this._listeningHandle)==null?void 0:$.unsubscribe()),this._listeningHandle=void 0,await this._ctx.dispose(),await this._topology.destroy(),await Promise.all(Array.from(this._peers.keys()).map(I=>this._destroyPeer(I,"swarm destroyed"))),log$2("destroyed",void 0,{F:__dxlog_file4$1,L:150,S:this,C:(I,U)=>I(...U)})}async setTopology($){invariant(!this._ctx.disposed,"Swarm is offline",{F:__dxlog_file4$1,L:154,S:this,A:["!this._ctx.disposed","'Swarm is offline'"]}),$!==this._topology&&(log$2("setting topology",{previous:getClassName(this._topology),topology:getClassName($)},{F:__dxlog_file4$1,L:158,S:this,C:(I,U)=>I(...U)}),await this._topology.destroy(),this._topology=$,this._topology.init(this._getSwarmController()),this._topology.update())}onSwarmEvent($){var I;if(log$2("swarm event",{swarmEvent:$},{F:__dxlog_file4$1,L:171,S:this,C:(U,q)=>U(...q)}),this._ctx.disposed){log$2("swarm event ignored for disposed swarm",void 0,{F:__dxlog_file4$1,L:174,S:this,C:(U,q)=>U(...q)});return}if($.peerAvailable){const U=PublicKey.from($.peerAvailable.peer);if(log$2("new peer",{peerId:U},{F:__dxlog_file4$1,L:180,S:this,C:(q,G)=>q(...G)}),!U.equals(this._ownPeerId)){const q=this._getOrCreatePeer(U);q.advertizing=!0}}else if($.peerLeft){const U=this._peers.get(PublicKey.from($.peerLeft.peer));U?(U.advertizing=!1,((I=U.connection)==null?void 0:I.state)!==ConnectionState.CONNECTED&&this._destroyPeer(U.id,"peer left").catch(q=>log$2.catch(q,void 0,{F:__dxlog_file4$1,L:191,S:this,C:(G,K)=>G(...K)}))):log$2("received peerLeft but no peer found",{peer:$.peerLeft.peer},{F:__dxlog_file4$1,L:194,S:this,C:(q,G)=>q(...G)})}this._topology.update()}async onOffer($){var q,G;if(log$2("offer",{message:$},{F:__dxlog_file4$1,L:203,S:this,C:(K,Y)=>K(...Y)}),this._ctx.disposed)return log$2("ignored for disposed swarm",void 0,{F:__dxlog_file4$1,L:205,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};if(invariant($.author,void 0,{F:__dxlog_file4$1,L:210,S:this,A:["message.author",""]}),!((q=$.recipient)!=null&&q.equals(this._ownPeerId)))return log$2("rejecting offer with incorrect peerId",{message:$},{F:__dxlog_file4$1,L:212,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};if(!((G=$.topic)!=null&&G.equals(this._topic)))return log$2("rejecting offer with incorrect topic",{message:$},{F:__dxlog_file4$1,L:216,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};const U=await this._getOrCreatePeer($.author).onOffer($);return this._topology.update(),U}async onSignal($){var U,q;if(log$2("signal",{message:$},{F:__dxlog_file4$1,L:227,S:this,C:(G,K)=>G(...K)}),this._ctx.disposed){log$2.info("ignored for offline swarm",void 0,{F:__dxlog_file4$1,L:229,S:this,C:(G,K)=>G(...K)});return}invariant((U=$.recipient)==null?void 0:U.equals(this._ownPeerId),`Invalid signal peer id expected=${this.ownPeerId}, actual=${$.recipient}`,{F:__dxlog_file4$1,L:232,S:this,A:["message.recipient?.equals(this._ownPeerId)","`Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`"]}),invariant((q=$.topic)==null?void 0:q.equals(this._topic),void 0,{F:__dxlog_file4$1,L:236,S:this,A:["message.topic?.equals(this._topic)",""]}),invariant($.author,void 0,{F:__dxlog_file4$1,L:237,S:this,A:["message.author",""]}),await this._getOrCreatePeer($.author).onSignal($)}async goOffline(){await this._ctx.dispose(),await Promise.all([...this._peers.keys()].map($=>this._destroyPeer($,"goOffline")))}async goOnline(){this._ctx=new Context}_getOrCreatePeer($){let I=this._peers.get($);return I||(I=new Peer($,this._topic,this._ownPeerId,this._swarmMessenger,this._protocolProvider,this._transportFactory,this._connectionLimiter,{onInitiated:U=>{this.connectionAdded.emit(U)},onConnected:()=>{this.connected.emit($)},onDisconnected:async()=>{I.advertizing||await this._destroyPeer(I.id,"peer disconnected"),this.disconnected.emit($),this._topology.update()},onRejected:()=>{this._peers.has($)&&(log$2("peer rejected connection",{peerId:$},{F:__dxlog_file4$1,L:286,S:this,C:(U,q)=>U(...q)}),this._destroyPeer($,"peer rejected connection"))},onAccepted:()=>{this._topology.update()},onOffer:U=>this._topology.onOffer(U),onPeerAvailable:()=>{this._topology.update()}}),this._peers.set($,I)),I}async _destroyPeer($,I){invariant(this._peers.has($),void 0,{F:__dxlog_file4$1,L:308,S:this,A:["this._peers.has(peerId)",""]}),await this._peers.get($).destroy(new Error(I)),this._peers.delete($)}_getSwarmController(){return{getState:()=>({ownPeerId:this._ownPeerId,connected:Array.from(this._peers.values()).filter($=>$.connection).map($=>$.id),candidates:Array.from(this._peers.values()).filter($=>!$.connection&&$.advertizing&&$.availableToConnect).map($=>$.id)}),connect:$=>{this._ctx.disposed||scheduleTask(this._ctx,async()=>{try{await this._initiateConnection($)}catch(I){log$2("initiation error",I,{F:__dxlog_file4$1,L:334,S:this,C:(U,q)=>U(...q)})}})},disconnect:async $=>{this._ctx.disposed||scheduleTask(this._ctx,async()=>{await this._closeConnection($),this._topology.update()})}}}async _initiateConnection($){const I=this._ctx;if($.toHex()<this._ownPeerId.toHex()&&(log$2("initiation delay",{remoteId:$},{F:__dxlog_file4$1,L:361,S:this,C:(q,G)=>q(...G)}),await sleep(this._initiationDelay)),I.disposed)return;const U=this._getOrCreatePeer($);U.connection||(log$2("initiating connection...",{remoteId:$},{F:__dxlog_file4$1,L:375,S:this,C:(q,G)=>q(...G)}),await U.initiateConnection(),this._topology.update(),log$2("initiated",{remoteId:$},{F:__dxlog_file4$1,L:378,S:this,C:(q,G)=>q(...G)}))}async _closeConnection($){const I=this._peers.get($);I&&await I.closeConnection()}};_ts_decorate3$1([logInfo],Swarm.prototype,"_instanceId",void 0),_ts_decorate3$1([logInfo],Swarm.prototype,"ownPeerId",null),_ts_decorate3$1([logInfo],Swarm.prototype,"topic",null),_ts_decorate3$1([synchronized],Swarm.prototype,"onSwarmEvent",null),_ts_decorate3$1([synchronized],Swarm.prototype,"onOffer",null),_ts_decorate3$1([synchronized],Swarm.prototype,"goOffline",null),_ts_decorate3$1([synchronized],Swarm.prototype,"goOnline",null);var EventType;(function($){$.CONNECTION_STATE_CHANGED="CONNECTION_STATE_CHANGED",$.PROTOCOL_ERROR="PROTOCOL_ERROR",$.PROTOCOL_EXTENSIONS_INITIALIZED="PROTOCOL_EXTENSIONS_INITIALIZED",$.PROTOCOL_EXTENSIONS_HANDSHAKE="PROTOCOL_EXTENSIONS_HANDSHAKE",$.PROTOCOL_HANDSHAKE="PROTOCOL_HANDSHAKE"})(EventType||(EventType={}));function _ts_decorate4$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file11="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts",MEMORY_TRANSPORT_DELAY=1,createStreamDelay=$=>new readableBrowserExports.Transform({objectMode:!0,transform:(I,U,q)=>{setTimeout(()=>q(null,I),$)}}),MemoryTransport=(Zn=class{constructor(I){this._options=I,this._instanceId=PublicKey.random(),this._remote=new Trigger,this._outgoingDelay=createStreamDelay(MEMORY_TRANSPORT_DELAY),this._incomingDelay=createStreamDelay(MEMORY_TRANSPORT_DELAY),this._closed=!1,this.closed=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream,invariant(!Zn._connections.has(this._instanceId),"Duplicate memory connection",{F:__dxlog_file11,L:64,S:this,A:["!MemoryTransport._connections.has(this._instanceId)","'Duplicate memory connection'"]}),Zn._connections.set(this._instanceId,this)}get isOpen(){return!this._closed}async open(){if(log$2("opening...",void 0,{F:__dxlog_file11,L:74,S:this,C:(I,U)=>I(...U)}),this._options.initiator){log$2("sending signal",void 0,{F:__dxlog_file11,L:78,S:this,C:(I,U)=>I(...U)});try{await this._options.sendSignal({payload:{transportId:this._instanceId.toHex()}})}catch(I){this._closed||this.errors.raise(toError(I))}}else this._remote.wait({timeout:this._options.timeout??1e3}).then(I=>{if(!this._closed){if(this._remoteInstanceId=I,this._remoteConnection=Zn._connections.get(this._remoteInstanceId),!this._remoteConnection){this._closed=!0,this.closed.emit();return}invariant(!this._remoteConnection._remoteConnection,`Remote already connected: ${this._remoteInstanceId}`,{F:__dxlog_file11,L:104,S:this,A:["!this._remoteConnection._remoteConnection","`Remote already connected: ${this._remoteInstanceId}`"]}),this._remoteConnection._remoteConnection=this,this._remoteConnection._remoteInstanceId=this._instanceId,log$2("connected",void 0,{F:__dxlog_file11,L:108,S:this,C:(U,q)=>U(...q)}),this._options.stream.pipe(this._outgoingDelay).pipe(this._remoteConnection._options.stream).pipe(this._incomingDelay).pipe(this._options.stream),this.connected.emit(),this._remoteConnection.connected.emit()}}).catch(I=>{this._closed||this.errors.raise(I)})}async close(){log$2("closing...",void 0,{F:__dxlog_file11,L:129,S:this,C:(I,U)=>I(...U)}),this._closed=!0,Zn._connections.delete(this._instanceId),this._remoteConnection&&(this._remoteConnection._closed=!0,Zn._connections.delete(this._remoteInstanceId),this._options.stream.unpipe(this._incomingDelay),this._incomingDelay.unpipe(this._remoteConnection._options.stream),this._remoteConnection._options.stream.unpipe(this._outgoingDelay),this._outgoingDelay.unpipe(this._options.stream),this._options.stream.unpipe(this._outgoingDelay),this._remoteConnection.closed.emit(),this._remoteConnection._remoteConnection=void 0,this._remoteConnection=void 0),this.closed.emit(),log$2("closed",void 0,{F:__dxlog_file11,L:157,S:this,C:(I,U)=>I(...U)})}async onSignal({payload:I}){if(log$2("received signal",{payload:I},{F:__dxlog_file11,L:161,S:this,C:(q,G)=>q(...G)}),!(I!=null&&I.transportId))return;const U=I.transportId;if(U){const q=PublicKey.fromHex(U);this._remote.wake(q)}}async getDetails(){return this._instanceId.toHex()}async getStats(){return{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0}}},Zn._connections=new ComplexMap(PublicKey.hash),Zn);_ts_decorate4$1([logInfo],MemoryTransport.prototype,"_instanceId",void 0),_ts_decorate4$1([logInfo],MemoryTransport.prototype,"_remoteInstanceId",void 0);var toError=$=>$ instanceof Error?$:new Error(String($)),TransportKind;(function($){$.SIMPLE_PEER="SIMPLE_PEER",$.SIMPLE_PEER_PROXY="SIMPLE_PEER_PROXY",$.LIBDATACHANNEL="LIBDATACHANNEL",$.MEMORY="MEMORY",$.TCP="TCP"})(TransportKind||(TransportKind={}));var wrtc=null;try{wrtc=__require("@koush/wrtc")}catch{}function _ts_decorate5$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file15="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/libdatachannel-transport.ts",DATACHANNEL_LABEL="dxos.mesh.transport",MAX_BUFFERED_AMOUNT=64*1024,MAX_MESSAGE_SIZE=64*1024,LibDataChannelTransport=(rr=class{constructor(I){this._options=I,this._closed=!1,this._connected=!1,this._writeCallback=null,this._readyForCandidates=new Trigger,this.closed=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream}get isOpen(){return!!this._peer&&!this._closed}async open(){this._closed&&this.errors.raise(new Error("connection already closed"));const{RTCPeerConnection:I}=(await importESM("node-datachannel/polyfill")).default;this._options.webrtcConfig?this._options.webrtcConfig.iceServers=this._options.webrtcConfig.iceServers??[]:this._options.webrtcConfig={iceServers:[]},this._peer=new I(this._options.webrtcConfig),this._peer.onicecandidateerror=U=>{log$2.error("peer.onicecandidateerror",{event:U},{F:__dxlog_file15,L:77,S:this,C:(q,G)=>q(...G)})},this._peer.onconnectionstatechange=U=>{var q;log$2.debug("peer.onconnectionstatechange",{event:U,peerConnectionState:(q=this._peer)==null?void 0:q.connectionState,transportConnectionState:this._connected},{F:__dxlog_file15,L:81,S:this,C:(G,K)=>G(...K)})},this._peer.onicecandidate=async U=>{if(log$2.debug("peer.onicecandidate",{event:U},{F:__dxlog_file15,L:91,S:this,C:(q,G)=>q(...G)}),U.candidate)try{await this._options.sendSignal({payload:{data:{type:"candidate",candidate:{candidate:U.candidate.candidate,sdpMLineIndex:U.candidate.sdpMLineIndex??0,sdpMid:U.candidate.sdpMid??0}}}})}catch(q){log$2.info("signaling error",{err:q},{F:__dxlog_file15,L:108,S:this,C:(G,K)=>G(...K)})}},this._options.initiator?(invariant(this._peer,"not open",{F:__dxlog_file15,L:114,S:this,A:["this._peer","'not open'"]}),this._peer.createOffer().then(async U=>{var q;this._closed||(((q=this._peer)==null?void 0:q.connectionState)!=="connecting"&&(log$2.error("peer not connecting",{peer:this._peer},{F:__dxlog_file15,L:125,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("invalid state: peer is initiator, but other peer not in state connecting"))),log$2.debug("creating offer",{peer:this._peer,offer:U},{F:__dxlog_file15,L:129,S:this,C:(G,K)=>G(...K)}),await this._peer.setLocalDescription(U),await this._options.sendSignal({payload:{data:{type:U.type,sdp:U.sdp}}}))}).catch(U=>{this.errors.raise(U)}),this._handleChannel(this._peer.createDataChannel(DATACHANNEL_LABEL)),log$2.debug("created data channel",void 0,{F:__dxlog_file15,L:139,S:this,C:(U,q)=>U(...q)}),this._peer.ondatachannel=()=>{this.errors.raise(new Error("unexpected ondatachannel event for initiator"))}):this._peer.ondatachannel=U=>{log$2.debug("peer.ondatachannel (non-initiator)",{event:U},{F:__dxlog_file15,L:145,S:this,C:(q,G)=>q(...G)}),U.channel.label!==DATACHANNEL_LABEL&&this.errors.raise(new Error(`unexpected channel label ${U.channel.label}`)),this._handleChannel(U.channel)},rr._instanceCount++}async close(){await this._close(),--rr._instanceCount===0&&(await importESM("node-datachannel")).cleanup()}async _close(){var I;if(!this._closed){await this._disconnectStreams();try{(I=this._peer)==null||I.close()}catch(U){this.errors.raise(U)}this._peer=void 0,this._closed=!0,this.closed.emit()}}_handleChannel(I){this._channel=I,this._channel.onopen=()=>{log$2.debug("channel.onopen",void 0,{F:__dxlog_file15,L:190,S:this,C:(q,G)=>q(...G)});const U=new stream.Duplex({read:()=>{},write:async(q,G,K)=>{q.length>MAX_MESSAGE_SIZE&&this.errors.raise(new Error(`message too large: ${q.length} > ${MAX_MESSAGE_SIZE}`));try{I.send(q)}catch(Y){this.errors.raise(Y),await this._close()}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._writeCallback!==null&&log$2.error("consumer trying to write before we are ready for more data",void 0,{F:__dxlog_file15,L:207,S:this,C:(Y,J)=>Y(...J)}),this._writeCallback=K):K()}});U.pipe(this._options.stream).pipe(U),this._stream=U,this._connected=!0,this.connected.emit()},this._channel.onclose=async U=>{log$2.info("channel.onclose",{err:U},{F:__dxlog_file15,L:223,S:this,C:(q,G)=>q(...G)}),await this._close()},this._channel.onerror=async U=>{this.errors.raise(new Error("channel error: "+U.toString())),await this._close()},this._channel.onbufferedamountlow=()=>{const U=this._writeCallback;this._writeCallback=null,U==null||U()},this._channel.onmessage=U=>{let q=U.data;q instanceof ArrayBuffer&&(q=export_Buffer.from(q)),this._stream.push(q)}}async onSignal(I){invariant(this._peer,"not open",{F:__dxlog_file15,L:249,S:this,A:["this._peer","'not open'"]});try{const U=I.payload.data;switch(U.type){case"offer":{if(this._peer.connectionState!=="new"){log$2.error("received offer but peer not in state new",{peer:this._peer},{F:__dxlog_file15,L:256,S:this,C:(q,G)=>q(...G)}),this.errors.raise(new Error("invalid signalling state: received offer when peer is not in state new"));break}try{await this._peer.setRemoteDescription({type:U.type,sdp:U.sdp});const q=await this._peer.createAnswer();await this._peer.setLocalDescription(q),await this._options.sendSignal({payload:{data:{type:q.type,sdp:q.sdp}}}),this._readyForCandidates.wake()}catch(q){log$2.error("cannot handle offer from signalling server",{err:q},{F:__dxlog_file15,L:268,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("error handling offer"))}break}case"answer":try{await this._peer.setRemoteDescription({type:U.type,sdp:U.sdp}),this._readyForCandidates.wake()}catch(q){log$2.error("cannot handle answer from signalling server",{err:q},{F:__dxlog_file15,L:279,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("error handling answer"))}break;case"candidate":await this._readyForCandidates.wait(),await this._peer.addIceCandidate({candidate:U.candidate.candidate});break;default:log$2.error("unhandled signal type",{type:U.type,signal:I},{F:__dxlog_file15,L:290,S:this,C:(q,G)=>q(...G)}),this.errors.raise(new Error(`unhandled signal type ${U.type}`))}}catch(U){log$2.catch(U,void 0,{F:__dxlog_file15,L:294,S:this,C:(q,G)=>q(...G)})}}async getDetails(){const I=await this._getStats(),U=I==null?void 0:I.remoteCandidate;return U?U.candidateType==="relay"?`${U.ip}:${U.port} relay for ${U.relatedAddress}:${U.relatedPort}`:`${U.ip}:${U.port} ${U.candidateType}`:"unavailable"}async getStats(){const I=await this._getStats();return I?{bytesSent:I.transport.bytesSent,bytesReceived:I.transport.bytesReceived,packetsSent:0,packetsReceived:0,rawStats:I.raw}:{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rawStats:{}}}async _getStats(){invariant(this._peer,"not open",{F:__dxlog_file15,L:334,S:this,A:["this._peer","'not open'"]});const I=await this._peer.getStats(),U=Array.from(I.entries()),q=U.filter(J=>J[1].type==="transport")[0][1],G=U.filter(J=>J[0]===q.selectedCandidatePairId);let K,Y;return G.length>0&&(K=G[0][1],Y=U.filter(J=>J[0]===K.remoteCandidateId)[0][1]),{transport:q,selectedCandidatePair:K,remoteCandidate:Y,raw:Object.fromEntries(I)}}async _disconnectStreams(){var I,U,q,G;(G=(q=(U=(I=this._options.stream).unpipe)==null?void 0:U.call(I,this._stream))==null?void 0:q.unpipe)==null||G.call(q,this._options.stream)}},rr._instanceCount=0,rr);_ts_decorate5$1([synchronized],LibDataChannelTransport.prototype,"_close",null);var importESM=Function("path","return import(path)"),uaParser={exports:{}};(function($,I){(function(U,q){var G="1.0.35",K="",Y="?",J="function",X="undefined",Z="object",Q="string",ee="major",te="model",ne="name",ie="type",oe="vendor",ce="version",fe="architecture",se="console",de="mobile",ue="tablet",pe="smarttv",ve="wearable",me="embedded",be=350,ye="Amazon",Se="Apple",xe="ASUS",ke="BlackBerry",De="Browser",Be="Chrome",Ve="Edge",nt="Firefox",ot="Google",ft="Huawei",it="LG",ut="Microsoft",et="Motorola",Ue="Opera",We="Samsung",tt="Sharp",vt="Sony",je="Xiaomi",ze="Zebra",Ae="Facebook",Re="Chromium OS",Ce="Mac OS",ge=function(St,Ut){var le={};for(var re in St)Ut[re]&&Ut[re].length%2===0?le[re]=Ut[re].concat(St[re]):le[re]=St[re];return le},_e=function(St){for(var Ut={},le=0;le<St.length;le++)Ut[St[le].toUpperCase()]=St[le];return Ut},Me=function(St,Ut){return typeof St===Q?Ke(Ut).indexOf(Ke(St))!==-1:!1},Ke=function(St){return St.toLowerCase()},st=function(St){return typeof St===Q?St.replace(/[^\d\.]/g,K).split(".")[0]:q},dt=function(St,Ut){if(typeof St===Q)return St=St.replace(/^\s\s*/,K),typeof Ut===X?St:St.substring(0,be)},$t=function(St,Ut){for(var le=0,re,ae,he,we,Ee,Le;le<Ut.length&&!Ee;){var bt=Ut[le],Lt=Ut[le+1];for(re=ae=0;re<bt.length&&!Ee&&bt[re];)if(Ee=bt[re++].exec(St),Ee)for(he=0;he<Lt.length;he++)Le=Ee[++ae],we=Lt[he],typeof we===Z&&we.length>0?we.length===2?typeof we[1]==J?this[we[0]]=we[1].call(this,Le):this[we[0]]=we[1]:we.length===3?typeof we[1]===J&&!(we[1].exec&&we[1].test)?this[we[0]]=Le?we[1].call(this,Le,we[2]):q:this[we[0]]=Le?Le.replace(we[1],we[2]):q:we.length===4&&(this[we[0]]=Le?we[3].call(this,Le.replace(we[1],we[2])):q):this[we]=Le||q;le+=2}},Et=function(St,Ut){for(var le in Ut)if(typeof Ut[le]===Z&&Ut[le].length>0){for(var re=0;re<Ut[le].length;re++)if(Me(Ut[le][re],St))return le===Y?q:le}else if(Me(Ut[le],St))return le===Y?q:le;return St},rt={"1.0":"/8","1.2":"/1","1.3":"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},jt={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2","8.1":"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Gt={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[ce,[ne,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[ce,[ne,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[ne,ce],[/opios[\/ ]+([\w\.]+)/i],[ce,[ne,Ue+" Mini"]],[/\bopr\/([\w\.]+)/i],[ce,[ne,Ue]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[ne,ce],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[ce,[ne,"UC"+De]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[ce,[ne,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[ce,[ne,"WeChat"]],[/konqueror\/([\w\.]+)/i],[ce,[ne,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[ce,[ne,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[ce,[ne,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[ne,/(.+)/,"$1 Secure "+De],ce],[/\bfocus\/([\w\.]+)/i],[ce,[ne,nt+" Focus"]],[/\bopt\/([\w\.]+)/i],[ce,[ne,Ue+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[ce,[ne,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[ce,[ne,"Dolphin"]],[/coast\/([\w\.]+)/i],[ce,[ne,Ue+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[ce,[ne,"MIUI "+De]],[/fxios\/([-\w\.]+)/i],[ce,[ne,nt]],[/\bqihu|(qi?ho?o?|360)browser/i],[[ne,"360 "+De]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[ne,/(.+)/,"$1 "+De],ce],[/(comodo_dragon)\/([\w\.]+)/i],[[ne,/_/g," "],ce],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[ne,ce],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[ne],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[ne,Ae],ce],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[ne,ce],[/\bgsa\/([\w\.]+) .*safari\//i],[ce,[ne,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[ce,[ne,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[ce,[ne,Be+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[ne,Be+" WebView"],ce],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[ce,[ne,"Android "+De]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[ne,ce],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[ce,[ne,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[ce,ne],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[ne,[ce,Et,rt]],[/(webkit|khtml)\/([\w\.]+)/i],[ne,ce],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[ne,"Netscape"],ce],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[ce,[ne,nt+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[ne,ce],[/(cobalt)\/([\w\.]+)/i],[ne,[ce,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[fe,"amd64"]],[/(ia32(?=;))/i],[[fe,Ke]],[/((?:i[346]|x)86)[;\)]/i],[[fe,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[fe,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[fe,"armhf"]],[/windows (ce|mobile); ppc;/i],[[fe,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[fe,/ower/,K,Ke]],[/(sun4\w)[;\)]/i],[[fe,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[fe,Ke]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[te,[oe,We],[ie,ue]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[te,[oe,We],[ie,de]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[te,[oe,Se],[ie,de]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[te,[oe,Se],[ie,ue]],[/(macintosh);/i],[te,[oe,Se]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[te,[oe,tt],[ie,de]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[te,[oe,ft],[ie,ue]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[te,[oe,ft],[ie,de]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[te,/_/g," "],[oe,je],[ie,de]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[te,/_/g," "],[oe,je],[ie,ue]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[te,[oe,"OPPO"],[ie,de]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[te,[oe,"Vivo"],[ie,de]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[te,[oe,"Realme"],[ie,de]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[te,[oe,et],[ie,de]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[te,[oe,et],[ie,ue]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[te,[oe,it],[ie,ue]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[te,[oe,it],[ie,de]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[te,[oe,"Lenovo"],[ie,ue]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[te,/_/g," "],[oe,"Nokia"],[ie,de]],[/(pixel c)\b/i],[te,[oe,ot],[ie,ue]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[te,[oe,ot],[ie,de]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[te,[oe,vt],[ie,de]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[te,"Xperia Tablet"],[oe,vt],[ie,ue]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[te,[oe,"OnePlus"],[ie,de]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[te,[oe,ye],[ie,ue]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[te,/(.+)/g,"Fire Phone $1"],[oe,ye],[ie,de]],[/(playbook);[-\w\),; ]+(rim)/i],[te,oe,[ie,ue]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[te,[oe,ke],[ie,de]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[te,[oe,xe],[ie,ue]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[te,[oe,xe],[ie,de]],[/(nexus 9)/i],[te,[oe,"HTC"],[ie,ue]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[oe,[te,/_/g," "],[ie,de]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[te,[oe,"Acer"],[ie,ue]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[te,[oe,"Meizu"],[ie,de]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[oe,te,[ie,de]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[oe,te,[ie,ue]],[/(surface duo)/i],[te,[oe,ut],[ie,ue]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[te,[oe,"Fairphone"],[ie,de]],[/(u304aa)/i],[te,[oe,"AT&T"],[ie,de]],[/\bsie-(\w*)/i],[te,[oe,"Siemens"],[ie,de]],[/\b(rct\w+) b/i],[te,[oe,"RCA"],[ie,ue]],[/\b(venue[\d ]{2,7}) b/i],[te,[oe,"Dell"],[ie,ue]],[/\b(q(?:mv|ta)\w+) b/i],[te,[oe,"Verizon"],[ie,ue]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[te,[oe,"Barnes & Noble"],[ie,ue]],[/\b(tm\d{3}\w+) b/i],[te,[oe,"NuVision"],[ie,ue]],[/\b(k88) b/i],[te,[oe,"ZTE"],[ie,ue]],[/\b(nx\d{3}j) b/i],[te,[oe,"ZTE"],[ie,de]],[/\b(gen\d{3}) b.+49h/i],[te,[oe,"Swiss"],[ie,de]],[/\b(zur\d{3}) b/i],[te,[oe,"Swiss"],[ie,ue]],[/\b((zeki)?tb.*\b) b/i],[te,[oe,"Zeki"],[ie,ue]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[oe,"Dragon Touch"],te,[ie,ue]],[/\b(ns-?\w{0,9}) b/i],[te,[oe,"Insignia"],[ie,ue]],[/\b((nxa|next)-?\w{0,9}) b/i],[te,[oe,"NextBook"],[ie,ue]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[oe,"Voice"],te,[ie,de]],[/\b(lvtel\-)?(v1[12]) b/i],[[oe,"LvTel"],te,[ie,de]],[/\b(ph-1) /i],[te,[oe,"Essential"],[ie,de]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[te,[oe,"Envizen"],[ie,ue]],[/\b(trio[-\w\. ]+) b/i],[te,[oe,"MachSpeed"],[ie,ue]],[/\btu_(1491) b/i],[te,[oe,"Rotor"],[ie,ue]],[/(shield[\w ]+) b/i],[te,[oe,"Nvidia"],[ie,ue]],[/(sprint) (\w+)/i],[oe,te,[ie,de]],[/(kin\.[onetw]{3})/i],[[te,/\./g," "],[oe,ut],[ie,de]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[te,[oe,ze],[ie,ue]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[te,[oe,ze],[ie,de]],[/smart-tv.+(samsung)/i],[oe,[ie,pe]],[/hbbtv.+maple;(\d+)/i],[[te,/^/,"SmartTV"],[oe,We],[ie,pe]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[oe,it],[ie,pe]],[/(apple) ?tv/i],[oe,[te,Se+" TV"],[ie,pe]],[/crkey/i],[[te,Be+"cast"],[oe,ot],[ie,pe]],[/droid.+aft(\w)( bui|\))/i],[te,[oe,ye],[ie,pe]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[te,[oe,tt],[ie,pe]],[/(bravia[\w ]+)( bui|\))/i],[te,[oe,vt],[ie,pe]],[/(mitv-\w{5}) bui/i],[te,[oe,je],[ie,pe]],[/Hbbtv.*(technisat) (.*);/i],[oe,te,[ie,pe]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[oe,dt],[te,dt],[ie,pe]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[ie,pe]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[oe,te,[ie,se]],[/droid.+; (shield) bui/i],[te,[oe,"Nvidia"],[ie,se]],[/(playstation [345portablevi]+)/i],[te,[oe,vt],[ie,se]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[te,[oe,ut],[ie,se]],[/((pebble))app/i],[oe,te,[ie,ve]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[te,[oe,Se],[ie,ve]],[/droid.+; (glass) \d/i],[te,[oe,ot],[ie,ve]],[/droid.+; (wt63?0{2,3})\)/i],[te,[oe,ze],[ie,ve]],[/(quest( 2| pro)?)/i],[te,[oe,Ae],[ie,ve]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[oe,[ie,me]],[/(aeobc)\b/i],[te,[oe,ye],[ie,me]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[te,[ie,de]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[te,[ie,ue]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[ie,ue]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[ie,de]],[/(android[-\w\. ]{0,9});.+buil/i],[te,[oe,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[ce,[ne,Ve+"HTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[ce,[ne,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[ne,ce],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[ce,ne]],os:[[/microsoft (windows) (vista|xp)/i],[ne,ce],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[ne,[ce,Et,jt]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[ne,"Windows"],[ce,Et,jt]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/ios;fbsv\/([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[ce,/_/g,"."],[ne,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[ne,Ce],[ce,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[ce,ne],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[ne,ce],[/\(bb(10);/i],[ce,[ne,ke]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[ce,[ne,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[ce,[ne,nt+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[ce,[ne,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[ce,[ne,"watchOS"]],[/crkey\/([\d\.]+)/i],[ce,[ne,Be+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[ne,Re],ce],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[ne,ce],[/(sunos) ?([\w\.\d]*)/i],[[ne,"Solaris"],ce],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[ne,ce]]},At=function(St,Ut){if(typeof St===Z&&(Ut=St,St=q),!(this instanceof At))return new At(St,Ut).getResult();var le=typeof U!==X&&U.navigator?U.navigator:q,re=St||(le&&le.userAgent?le.userAgent:K),ae=le&&le.userAgentData?le.userAgentData:q,he=Ut?ge(Gt,Ut):Gt,we=le&&le.userAgent==re;return this.getBrowser=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.browser),Ee[ee]=st(Ee[ce]),we&&le&&le.brave&&typeof le.brave.isBrave==J&&(Ee[ne]="Brave"),Ee},this.getCPU=function(){var Ee={};return Ee[fe]=q,$t.call(Ee,re,he.cpu),Ee},this.getDevice=function(){var Ee={};return Ee[oe]=q,Ee[te]=q,Ee[ie]=q,$t.call(Ee,re,he.device),we&&!Ee[ie]&&ae&&ae.mobile&&(Ee[ie]=de),we&&Ee[te]=="Macintosh"&&le&&typeof le.standalone!==X&&le.maxTouchPoints&&le.maxTouchPoints>2&&(Ee[te]="iPad",Ee[ie]=ue),Ee},this.getEngine=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.engine),Ee},this.getOS=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.os),we&&!Ee[ne]&&ae&&ae.platform!="Unknown"&&(Ee[ne]=ae.platform.replace(/chrome os/i,Re).replace(/macos/i,Ce)),Ee},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return re},this.setUA=function(Ee){return re=typeof Ee===Q&&Ee.length>be?dt(Ee,be):Ee,this},this.setUA(re),this};At.VERSION=G,At.BROWSER=_e([ne,ce,ee]),At.CPU=_e([fe]),At.DEVICE=_e([te,oe,ie,se,de,pe,ue,ve,me]),At.ENGINE=At.OS=_e([ne,ce]),$.exports&&(I=$.exports=At),I.UAParser=At;var zt=typeof U!==X&&(U.jQuery||U.Zepto);if(zt&&!zt.ua){var nn=new At;zt.ua=nn.getResult(),zt.ua.get=function(){return nn.getUA()},zt.ua.set=function(St){nn.setUA(St);var Ut=nn.getResult();for(var le in Ut)zt.ua[le]=Ut[le]}}})(typeof window=="object"?window:commonjsGlobal)})(uaParser,uaParser.exports);var uaParserExports=uaParser.exports,__dxlog_file$2="/home/runner/work/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/iframe.ts",browser,os$1;if(typeof navigator<"u"){const $=new uaParserExports.UAParser(navigator.userAgent);browser=$.getBrowser().name,os$1=$.getOS().name}var sendToIFrame=($,I,U)=>{if(!$.contentWindow){log$2("IFrame content window missing",{origin:I},{F:__dxlog_file$2,L:24,S:void 0,C:(q,G)=>q(...G)});return}browser==="Chrome"&&os$1==="iOS"?$.contentWindow.postMessage(U,I):$.contentWindow.postMessage(U,I,[U.payload])},sendToParentWindow=($,I)=>{browser==="Chrome"&&os$1==="iOS"?window.parent.postMessage(I,$):window.parent.postMessage(I,$,[I.payload])},createIFramePort=({channel:$,iframe:I,origin:U,onOrigin:q})=>({send:async G=>{if(!U){log$2("no origin set",{channel:$},{F:__dxlog_file$2,L:62,S:void 0,C:(J,X)=>J(...X)});return}log$2("sending",{channel:$,data:G.length},{F:__dxlog_file$2,L:66,S:void 0,C:(J,X)=>J(...X)});const K=G.buffer.slice(G.byteOffset,G.byteOffset+G.byteLength),Y={channel:$,payload:K};I?sendToIFrame(I,U,Y):sendToParentWindow(U,Y)},subscribe:G=>{const K=Y=>{if(!I&&Y.source!==window.parent)return;if(I&&Y.source!==I.contentWindow)return;const X=Y.data&&typeof Y.data=="object"&&"channel"in Y.data&&"payload"in Y.data?Y.data:void 0;(X==null?void 0:X.channel)===$&&(U||(U=Y.origin,q==null||q(U)),log$2("received",X,{F:__dxlog_file$2,L:98,S:void 0,C:(Z,Q)=>Z(...Q)}),G(new Uint8Array(X.payload)))};return window.addEventListener("message",K),()=>window.removeEventListener("message",K)}}),createIFrame=($,I,{hidden:U=!0,allow:q}={})=>{const G=()=>{const K=document.createElement("iframe");return K.id=I,K.src=$,U&&K.setAttribute("style","display: none;"),q&&K.setAttribute("allow",q),document.body.appendChild(K),K};return document.getElementById(I)??G()},__dxlog_file2$1="/home/runner/work/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/worker.ts",createWorkerPort=({port:$,channel:I,subscribe:U})=>({send:async q=>{const G=q.buffer.slice(q.byteOffset,q.byteOffset+q.byteLength);$.postMessage({channel:I,payload:G},[G])},subscribe:U??(q=>{const G=K=>{const Y=K.data;I&&Y.channel!==I||(log$2.debug("Recieved message",Y,{F:__dxlog_file2$1,L:46,S:void 0,C:(J,X)=>J(...X)}),q(new Uint8Array(Y.payload)))};return $.onmessage=G,()=>{$.onmessage=null}})});function _ts_decorate$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$1="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/agent.ts",getUnixSocket=($,I="unix")=>`${I}://`+clientProtocol.getProfilePath(clientProtocol.DX_RUNTIME,$,"agent.sock"),AgentClientServiceProvider=class{constructor($){this._profile=$,this.closed=new Event$1}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return this._client.rpc}async open(){const{WebsocketRpcClient:$}=await Promise.resolve().then(()=>index);this._client=new $({url:getUnixSocket(this._profile,"ws+unix"),requested:clientProtocol.clientServiceBundle,exposed:{},handlers:{}}),this._client.error.on(I=>{this.closed.emit(I)}),await this._client.open()}async close(){var $;try{await(($=this._client)==null?void 0:$.close())}catch(I){log$2.warn("Failed to close",I,{F:__dxlog_file$1,L:72,S:this,C:(U,q)=>U(...q)})}}};AgentClientServiceProvider=_ts_decorate$1([trace.resource({annotation:clientServices.ClientServicesProviderResource})],AgentClientServiceProvider);function _ts_decorate2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var LocalClientServices=class{constructor($){this.closed=new Event$1,this._ctx=new Context,this.signalMetadataTags={runtime:"local-client-services"},this._isOpen=!1,this._params=$,typeof window>"u"?this.signalMetadataTags.origin="undefined":globalThis.__args?(this.signalMetadataTags.runtime="native",this.signalMetadataTags.origin=window.location.origin):this.signalMetadataTags.origin=window.location.origin}get descriptors(){return clientProtocol.clientServiceBundle}get services(){var $;return(($=this._host)==null?void 0:$.services)??{}}get host(){return this._host}async open(){if(this._isOpen)return;const{ClientServicesHost:$}=await import("@dxos/client-services");this._host=new $({...this._params,callbacks:{...this._params.callbacks,onReset:async()=>{var I,U;this.closed.emit(void 0),await((U=(I=this._params.callbacks)==null?void 0:I.onReset)==null?void 0:U.call(I))}}}),await this._host.open(this._ctx),this._isOpen=!0,setIdentityTags({identityService:this._host.services.IdentityService,devicesService:this._host.services.DevicesService,setTag:(I,U)=>{this.signalMetadataTags[I]=U}})}async close(){var $;this._isOpen&&(await(($=this._host)==null?void 0:$.close()),this._isOpen=!1)}};_ts_decorate2([trace.info()],LocalClientServices.prototype,"_isOpen",void 0),_ts_decorate2([synchronized],LocalClientServices.prototype,"open",null),_ts_decorate2([synchronized],LocalClientServices.prototype,"close",null),LocalClientServices=_ts_decorate2([trace.resource({annotation:clientServices.ClientServicesProviderResource})],LocalClientServices);var IFrameManager=class{constructor({source:$,onOpen:I,onMessage:U}){this._source=$,this._onOpen=I,this._onMessage=U,this._messageHandler=this._messageHandler.bind(this)}get source(){return this._source}get iframe(){return this._iframe}async open(){var I;if(this._iframe)return;window.addEventListener("message",this._messageHandler);const $=`__DXOS_CLIENT_${PublicKey.random().toHex()}__`;this._iframe=createIFrame(this._source.toString(),$,{allow:"clipboard-read; clipboard-write"}),await((I=this._onOpen)==null?void 0:I.call(this))}async close(){var $;window.removeEventListener("message",this._messageHandler),($=this._iframe)==null||$.remove(),this._iframe=void 0}async _messageHandler($){var I;(I=this._onMessage)==null||I.call(this,$)}},__dxlog_file4="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/shell-manager.ts",shellStyles=Object.entries({display:"none",position:"fixed",top:0,left:0,width:"100vw",height:"100vh",border:0,"z-index":60}).reduce(($,[I,U])=>`${$}${I}: ${U};`,""),ShellManager=class{constructor($,I=clientProtocol.DEFAULT_SHELL_CHANNEL){this._iframeManager=$,this._channel=I,this.contextUpdate=new Event$1,this._display=ShellDisplay.NONE}get display(){return this._display}async setLayout($){var I;log$2("set layout",$,{F:__dxlog_file4,L:51,S:this,C:(U,q)=>U(...q)}),this._display=ShellDisplay.FULLSCREEN,this.contextUpdate.emit({display:this._display}),await((I=this._shellRpc)==null?void 0:I.rpc.ShellService.setLayout($,{timeout:RPC_TIMEOUT}))}async open(){if(this._shellRpc)return;await this._iframeManager.open();const $=this._iframeManager.iframe;$.setAttribute("style",shellStyles),$.setAttribute("name","dxos-shell"),$.setAttribute("data-testid","dxos-shell"),this.contextUpdate.on(({display:q,reload:G})=>{G&&window.location.reload(),$.style.display=q===ShellDisplay.NONE?"none":"",q===ShellDisplay.NONE&&$.blur()});const I=this._iframeManager.source.origin==="null"?this._iframeManager.source.toString().split("/").slice(0,3).join("/"):this._iframeManager.source.origin,U=createIFramePort({origin:I,channel:this._channel,iframe:this._iframeManager.iframe});this._shellRpc=createProtoRpcPeer({requested:clientProtocol.shellServiceBundle,exposed:clientProtocol.appServiceBundle,handlers:{AppService:{setContext:async q=>{log$2("set context",q,{F:__dxlog_file4,L:98,S:this,C:(G,K)=>G(...K)}),q.display&&(this._display=q.display),this.contextUpdate.emit(q)}}},port:U}),await this._shellRpc.open()}async close(){var $;this._shellRpc&&(await(($=this._shellRpc)==null?void 0:$.close()),this._shellRpc=void 0)}};function _ts_decorate3($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var IFrameClientServicesHost=class{constructor({host:$,source:I=clientProtocol.DEFAULT_VAULT_URL,vault:U=clientProtocol.DEFAULT_INTERNAL_CHANNEL,timeout:q=clientProtocol.PROXY_CONNECTION_TIMEOUT}){this.closed=new Event$1,this._host=$,this._source=I,this._vault=U,this._timeout=q;const G=new Trigger;this._iframeManager=new IFrameManager({source:new URL(this._source,window.location.origin),onOpen:async()=>{var K,Y,J;await asyncTimeout(G.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to load")),(J=(Y=(K=this._iframeManager)==null?void 0:K.iframe)==null?void 0:Y.contentWindow)==null||J.postMessage({channel:this._vault,payload:"init"},this._iframeManager.source.origin)},onMessage:K=>{var X,Z,Q;const{channel:Y,payload:J}=K.data;if(Y===this._vault){if(J==="loaded")G.wake();else if(J==="client"){const ee=new MessageChannel,te=createBundledRpcServer({services:this._host.descriptors,handlers:this._host.services,port:createWorkerPort({port:ee.port1})});(Q=(Z=(X=this._iframeManager)==null?void 0:X.iframe)==null?void 0:Z.contentWindow)==null||Q.postMessage({channel:this._vault,payload:{command:"port",port:ee.port2}},this._iframeManager.source.origin,[ee.port2]),te.open()}}}}),this._shellManager=new ShellManager(this._iframeManager)}get descriptors(){return this._host.descriptors}get services(){return this._host.services}async open(){await this._host.open(new Context),await this._shellManager.open()}async close(){await this._shellManager.close(),await this._iframeManager.close(),await this._host.close(new Context)}};IFrameClientServicesHost=_ts_decorate3([trace.resource()],IFrameClientServicesHost);function _ts_decorate4($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/service-proxy.ts",ClientServicesProxy=class{constructor($,I=3e4){this._port=$,this._timeout=I,this.closed=new Event$1}get proxy(){return invariant(this._proxy,"Client services not open",{F:__dxlog_file5,L:30,S:this,A:["this._proxy","'Client services not open'"]}),this._proxy}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return invariant(this._proxy,"Client services not open",{F:__dxlog_file5,L:39,S:this,A:["this._proxy","'Client services not open'"]}),this._proxy.rpc}async open(){this._proxy||(this._proxy=createProtoRpcPeer({requested:clientProtocol.clientServiceBundle,exposed:{},handlers:{},port:this._port}),await asyncTimeout(this._proxy.open(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Failed to establish dxrpc connection",{timeout:this._timeout})))}async close(){this._proxy&&(await this._proxy.close(),this._proxy=void 0)}};ClientServicesProxy=_ts_decorate4([trace.resource({annotation:clientServices.ClientServicesProviderResource})],ClientServicesProxy);function _ts_decorate5($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file6="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/iframe-service-proxy.ts",IFrameClientServicesProxy=class{constructor({source:$=clientProtocol.DEFAULT_VAULT_URL,shell:I=clientProtocol.DEFAULT_SHELL_CHANNEL,vault:U=clientProtocol.DEFAULT_INTERNAL_CHANNEL,timeout:q=clientProtocol.PROXY_CONNECTION_TIMEOUT,logFilter:G="error,warn"}={}){this.closed=new Event$1,this._instanceId=PublicKey.random().toHex(),this._source=$,this._shell=I,this._vault=U,this._logFilter=parseFilter(G),this._timeout=q;const K=new Trigger,Y=new Trigger;this._iframeManager=new IFrameManager({source:new URL(typeof this._shell=="string"?this._source:`${this._source}#disableshell`,window.location.origin),onOpen:async()=>{var X,Z;await asyncTimeout(K.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to load")),(Z=(X=this._iframeManager.iframe)==null?void 0:X.contentWindow)==null||Z.postMessage({channel:this._vault,payload:"init"},this._iframeManager.source.origin);const J=await asyncTimeout(Y.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to provide MessagePort"));this._appPort=createWorkerPort({port:J})},onMessage:async J=>{const{channel:X,payload:Z}=J.data;X===this._vault&&(Z==="loaded"?K.wake():(Z==null?void 0:Z.command)==="init"&&Y.wake(Z.port))}}),typeof this._shell=="string"&&(this._shellManager=new ShellManager(this._iframeManager))}get proxy(){return this._clientServicesProxy.proxy}get descriptors(){return this._clientServicesProxy.descriptors}get services(){return this._clientServicesProxy.services}async open(){var $;this._clientServicesProxy||(log$2.trace("dxos.sdk.iframe-clientTraceices-proxy",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file6,L:142,S:this,C:(I,U)=>I(...U)}),await this._iframeManager.open(),this._clientServicesProxy=new ClientServicesProxy(this._appPort),await this._clientServicesProxy.open(),this._loggingStream=this._clientServicesProxy.services.LoggingService.queryLogs({filters:this._logFilter},{timeout:RPC_TIMEOUT}),this._loggingStream.subscribe(I=>{switch(I.level){case LogLevel.DEBUG:log$2.debug(`[vault] ${I.message}`,I.context,{F:__dxlog_file6,L:157,S:this,C:(U,q)=>U(...q)});break;case LogLevel.INFO:log$2.info(`[vault] ${I.message}`,I.context,{F:__dxlog_file6,L:160,S:this,C:(U,q)=>U(...q)});break;case LogLevel.WARN:log$2.warn(`[vault] ${I.message}`,I.context,{F:__dxlog_file6,L:163,S:this,C:(U,q)=>U(...q)});break;case LogLevel.ERROR:log$2.error(`[vault] ${I.message}`,I.context,{F:__dxlog_file6,L:166,S:this,C:(U,q)=>U(...q)});break}}),await(($=this._shellManager)==null?void 0:$.open()))}async close(){var $,I,U;await(($=this._shellManager)==null?void 0:$.close()),await this._iframeManager.close(),await((I=this._loggingStream)==null?void 0:I.close()),await((U=this._clientServicesProxy)==null?void 0:U.close()),this._clientServicesProxy=void 0,log$2.trace("dxos.sdk.iframe-clientTraceices-proxy",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file6,L:180,S:this,C:(q,G)=>q(...G)})}};IFrameClientServicesProxy=_ts_decorate5([trace.resource()],IFrameClientServicesProxy);function _ts_decorate6($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file8="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/worker-client-services.ts",WorkerClientServices=class{constructor({config:$,createWorker:I,logFilter:U="error,warn",observabilityGroup:q,signalTelemetryEnabled:G}){this.closed=new Event$1,this.joinedSpace=new Event$1,this._isOpen=!1,this._config=$,this._createWorker=I,this._logFilter=parseFilter(U),this._observabilityGroup=q,this._signalTelemetryEnabled=G??!1}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return this._services.services}get runtime(){return this._runtime}async open(){if(this._isOpen)return;log$2("opening...",void 0,{F:__dxlog_file8,L:88,S:this,C:(K,Y)=>K(...Y)});const{SharedWorkerConnection:$}=await import("@dxos/client-services"),I=new Trigger,U=this._createWorker();U.port.postMessage({dxlog:localStorage.getItem("dxlog")}),U.port.onmessage=K=>{const{command:Y,payload:J}=K.data;Y==="init"&&I.wake(J)};const{systemPort:q,appPort:G}=await I.wait();this._runtime=new $({config:this._config,systemPort:createWorkerPort({port:q})}),await this._runtime.open({origin:location.origin,observabilityGroup:this._observabilityGroup,signalTelemetryEnabled:this._signalTelemetryEnabled}),this._services=new ClientServicesProxy(createWorkerPort({port:G})),await this._services.open(),navigator.locks.request(LOCK_KEY,()=>{log$2("terminated",void 0,{F:__dxlog_file8,L:115,S:this,C:(K,Y)=>K(...Y)}),this._isOpen&&this.closed.emit(new Error("Shared worker terminated."))}),this._loggingStream=this._services.services.LoggingService.queryLogs({filters:this._logFilter},{timeout:RPC_TIMEOUT}),this._loggingStream.subscribe(K=>{switch(K.level){case LogLevel.DEBUG:log$2.debug(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.INFO:log$2.info(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.WARN:log$2.warn(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.ERROR:log$2.error(K.message,K.context,mapLogMeta(K.meta));break}}),log$2("opened",void 0,{F:__dxlog_file8,L:144,S:this,C:(K,Y)=>K(...Y)}),this._isOpen=!0}async close(){var $;this._isOpen&&(log$2("closing...",void 0,{F:__dxlog_file8,L:154,S:this,C:(I,U)=>I(...U)}),await(($=this._loggingStream)==null?void 0:$.close()),await this._runtime.close(),await this._services.close(),log$2("closed",void 0,{F:__dxlog_file8,L:159,S:this,C:(I,U)=>I(...U)}),this._isOpen=!1)}};_ts_decorate6([trace.info()],WorkerClientServices.prototype,"_isOpen",void 0),_ts_decorate6([synchronized],WorkerClientServices.prototype,"open",null),_ts_decorate6([synchronized],WorkerClientServices.prototype,"close",null),WorkerClientServices=_ts_decorate6([trace.resource()],WorkerClientServices);var mapLogMeta=$=>$&&{F:$.file,L:$.line,S:$.scope},i$1=Symbol.for("preact-signals");function t(){if(s$1>1)s$1--;else{for(var $,I=!1;h$1!==void 0;){var U=h$1;for(h$1=void 0,f++;U!==void 0;){var q=U.o;if(U.o=void 0,U.f&=-3,!(8&U.f)&&c(U))try{U.c()}catch(G){I||($=G,I=!0)}U=q}}if(f=0,s$1--,I)throw $}}var o=void 0,h$1=void 0,s$1=0,f=0,v$1=0;function e($){if(o!==void 0){var I=$.n;if(I===void 0||I.t!==o)return I={i:0,S:$,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:I},o.s!==void 0&&(o.s.n=I),o.s=I,$.n=I,32&o.f&&$.S(I),I;if(I.i===-1)return I.i=0,I.n!==void 0&&(I.n.p=I.p,I.p!==void 0&&(I.p.n=I.n),I.p=o.s,I.n=void 0,o.s.n=I,o.s=I),I}}function u($){this.v=$,this.i=0,this.n=void 0,this.t=void 0}u.prototype.brand=i$1,u.prototype.h=function(){return!0},u.prototype.S=function($){this.t!==$&&$.e===void 0&&($.x=this.t,this.t!==void 0&&(this.t.e=$),this.t=$)},u.prototype.U=function($){if(this.t!==void 0){var I=$.e,U=$.x;I!==void 0&&(I.x=U,$.e=void 0),U!==void 0&&(U.e=I,$.x=void 0),$===this.t&&(this.t=U)}},u.prototype.subscribe=function($){var I=this;return E(function(){var U=I.value,q=o;o=void 0;try{$(U)}finally{o=q}})},u.prototype.valueOf=function(){return this.value},u.prototype.toString=function(){return this.value+""},u.prototype.toJSON=function(){return this.value},u.prototype.peek=function(){var $=o;o=void 0;try{return this.value}finally{o=$}},Object.defineProperty(u.prototype,"value",{get:function(){var $=e(this);return $!==void 0&&($.i=this.i),this.v},set:function($){if($!==this.v){if(f>100)throw new Error("Cycle detected");this.v=$,this.i++,v$1++,s$1++;try{for(var I=this.t;I!==void 0;I=I.x)I.t.N()}finally{t()}}}});function c($){for(var I=$.s;I!==void 0;I=I.n)if(I.S.i!==I.i||!I.S.h()||I.S.i!==I.i)return!0;return!1}function a($){for(var I=$.s;I!==void 0;I=I.n){var U=I.S.n;if(U!==void 0&&(I.r=U),I.S.n=I,I.i=-1,I.n===void 0){$.s=I;break}}}function l($){for(var I=$.s,U=void 0;I!==void 0;){var q=I.p;I.i===-1?(I.S.U(I),q!==void 0&&(q.n=I.n),I.n!==void 0&&(I.n.p=q)):U=I,I.S.n=I.r,I.r!==void 0&&(I.r=void 0),I=q}$.s=U}function y($){u.call(this,void 0),this.x=$,this.s=void 0,this.g=v$1-1,this.f=4}(y.prototype=new u).h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===v$1))return!0;if(this.g=v$1,this.f|=1,this.i>0&&!c(this))return this.f&=-2,!0;var $=o;try{a(this),o=this;var I=this.x();(16&this.f||this.v!==I||this.i===0)&&(this.v=I,this.f&=-17,this.i++)}catch(U){this.v=U,this.f|=16,this.i++}return o=$,l(this),this.f&=-2,!0},y.prototype.S=function($){if(this.t===void 0){this.f|=36;for(var I=this.s;I!==void 0;I=I.n)I.S.S(I)}u.prototype.S.call(this,$)},y.prototype.U=function($){if(this.t!==void 0&&(u.prototype.U.call(this,$),this.t===void 0)){this.f&=-33;for(var I=this.s;I!==void 0;I=I.n)I.S.U(I)}},y.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var $=this.t;$!==void 0;$=$.x)$.t.N()}},Object.defineProperty(y.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var $=e(this);if(this.h(),$!==void 0&&($.i=this.i),16&this.f)throw this.v;return this.v}});function _($){var I=$.u;if($.u=void 0,typeof I=="function"){s$1++;var U=o;o=void 0;try{I()}catch(q){throw $.f&=-2,$.f|=8,g($),q}finally{o=U,t()}}}function g($){for(var I=$.s;I!==void 0;I=I.n)I.S.U(I);$.x=void 0,$.s=void 0,_($)}function p$1($){if(o!==this)throw new Error("Out-of-order effect");l(this),o=$,this.f&=-2,8&this.f&&g(this),t()}function b$1($){this.x=$,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32}b$1.prototype.c=function(){var $=this.S();try{if(8&this.f||this.x===void 0)return;var I=this.x();typeof I=="function"&&(this.u=I)}finally{$()}},b$1.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,_(this),a(this),s$1++;var $=o;return o=this,p$1.bind(this,$)},b$1.prototype.N=function(){2&this.f||(this.f|=2,this.o=h$1,h$1=this)},b$1.prototype.d=function(){this.f|=8,1&this.f||g(this)};function E($){var I=new b$1($);try{I.c()}catch(U){throw I.d(),U}return I.d.bind(I)}var shim={exports:{}},useSyncExternalStoreShim_production_min={};/**
|
|
924
924
|
* @license React
|
|
925
925
|
* use-sync-external-store-shim.production.min.js
|
|
926
926
|
*
|
|
@@ -936,7 +936,7 @@ Use Chrome, Firefox or Internet Explorer 11`)}var Buffer$2=requireSafeBuffer().B
|
|
|
936
936
|
*
|
|
937
937
|
* This source code is licensed under the MIT license found in the
|
|
938
938
|
* LICENSE file in the root directory of this source tree.
|
|
939
|
-
*/var hasRequiredUseSyncExternalStoreShim_development;function requireUseSyncExternalStoreShim_development(){return hasRequiredUseSyncExternalStoreShim_development||(hasRequiredUseSyncExternalStoreShim_development=1,process.env.NODE_ENV!=="production"&&function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var $=React,I=$.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function U(de){{for(var ue=arguments.length,pe=new Array(ue>1?ue-1:0),ve=1;ve<ue;ve++)pe[ve-1]=arguments[ve];q("error",de,pe)}}function q(de,ue,pe){{var ve=I.ReactDebugCurrentFrame,me=ve.getStackAddendum();me!==""&&(ue+="%s",pe=pe.concat([me]));var be=pe.map(function(ye){return String(ye)});be.unshift("Warning: "+ue),Function.prototype.apply.call(console[de],console,be)}}function G(de,ue){return de===ue&&(de!==0||1/de===1/ue)||de!==de&&ue!==ue}var K=typeof Object.is=="function"?Object.is:G,Y=$.useState,J=$.useEffect,X=$.useLayoutEffect,Z=$.useDebugValue,Q=!1,ee=!1;function te(de,ue,pe){Q||$.startTransition!==void 0&&(Q=!0,U("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var ve=ue();if(!ee){var me=ue();K(ve,me)||(U("The result of getSnapshot should be cached to avoid an infinite loop"),ee=!0)}var be=Y({inst:{value:ve,getSnapshot:ue}}),ye=be[0].inst,Se=be[1];return X(function(){ye.value=ve,ye.getSnapshot=ue,ne(ye)&&Se({inst:ye})},[de,ve,ue]),J(function(){ne(ye)&&Se({inst:ye});var xe=function(){ne(ye)&&Se({inst:ye})};return de(xe)},[de]),Z(ve),ve}function ne(de){var ue=de.getSnapshot,pe=de.value;try{var ve=ue();return!K(pe,ve)}catch{return!0}}function ie(de,ue,pe){return ue()}var oe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",ce=!oe,fe=ce?ie:te,se=$.useSyncExternalStore!==void 0?$.useSyncExternalStore:fe;useSyncExternalStoreShim_development.useSyncExternalStore=se,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()),useSyncExternalStoreShim_development}process.env.NODE_ENV==="production"?shim.exports=requireUseSyncExternalStoreShim_production_min():shim.exports=requireUseSyncExternalStoreShim_development()
|
|
939
|
+
*/var hasRequiredUseSyncExternalStoreShim_development;function requireUseSyncExternalStoreShim_development(){return hasRequiredUseSyncExternalStoreShim_development||(hasRequiredUseSyncExternalStoreShim_development=1,process.env.NODE_ENV!=="production"&&function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var $=React,I=$.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function U(de){{for(var ue=arguments.length,pe=new Array(ue>1?ue-1:0),ve=1;ve<ue;ve++)pe[ve-1]=arguments[ve];q("error",de,pe)}}function q(de,ue,pe){{var ve=I.ReactDebugCurrentFrame,me=ve.getStackAddendum();me!==""&&(ue+="%s",pe=pe.concat([me]));var be=pe.map(function(ye){return String(ye)});be.unshift("Warning: "+ue),Function.prototype.apply.call(console[de],console,be)}}function G(de,ue){return de===ue&&(de!==0||1/de===1/ue)||de!==de&&ue!==ue}var K=typeof Object.is=="function"?Object.is:G,Y=$.useState,J=$.useEffect,X=$.useLayoutEffect,Z=$.useDebugValue,Q=!1,ee=!1;function te(de,ue,pe){Q||$.startTransition!==void 0&&(Q=!0,U("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var ve=ue();if(!ee){var me=ue();K(ve,me)||(U("The result of getSnapshot should be cached to avoid an infinite loop"),ee=!0)}var be=Y({inst:{value:ve,getSnapshot:ue}}),ye=be[0].inst,Se=be[1];return X(function(){ye.value=ve,ye.getSnapshot=ue,ne(ye)&&Se({inst:ye})},[de,ve,ue]),J(function(){ne(ye)&&Se({inst:ye});var xe=function(){ne(ye)&&Se({inst:ye})};return de(xe)},[de]),Z(ve),ve}function ne(de){var ue=de.getSnapshot,pe=de.value;try{var ve=ue();return!K(pe,ve)}catch{return!0}}function ie(de,ue,pe){return ue()}var oe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",ce=!oe,fe=ce?ie:te,se=$.useSyncExternalStore!==void 0?$.useSyncExternalStore:fe;useSyncExternalStoreShim_development.useSyncExternalStore=se,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()),useSyncExternalStoreShim_development}var hasRequiredShim;function requireShim(){return hasRequiredShim||(hasRequiredShim=1,process.env.NODE_ENV==="production"?shim.exports=requireUseSyncExternalStoreShim_production_min():shim.exports=requireUseSyncExternalStoreShim_development()),shim.exports}var shimExports=requireShim(),jsxDevRuntime={exports:{}},reactJsxDevRuntime_production_min={};/**
|
|
940
940
|
* @license React
|
|
941
941
|
* react-jsx-dev-runtime.production.min.js
|
|
942
942
|
*
|
|
@@ -970,7 +970,7 @@ Check the top-level render call using <`+kt+">.")}return pt}}function Nn(He,pt){
|
|
|
970
970
|
*
|
|
971
971
|
* This source code is licensed under the MIT license found in the
|
|
972
972
|
* LICENSE file in the root directory of this source tree.
|
|
973
|
-
*/var hasRequiredWithSelector_production_min;function requireWithSelector_production_min(){if(hasRequiredWithSelector_production_min)return withSelector_production_min;hasRequiredWithSelector_production_min=1;var $=React,I=
|
|
973
|
+
*/var hasRequiredWithSelector_production_min;function requireWithSelector_production_min(){if(hasRequiredWithSelector_production_min)return withSelector_production_min;hasRequiredWithSelector_production_min=1;var $=React,I=requireShim();function U(Z,Q){return Z===Q&&(Z!==0||1/Z===1/Q)||Z!==Z&&Q!==Q}var q=typeof Object.is=="function"?Object.is:U,G=I.useSyncExternalStore,K=$.useRef,Y=$.useEffect,J=$.useMemo,X=$.useDebugValue;return withSelector_production_min.useSyncExternalStoreWithSelector=function(Z,Q,ee,te,ne){var ie=K(null);if(ie.current===null){var oe={hasValue:!1,value:null};ie.current=oe}else oe=ie.current;ie=J(function(){function fe(ve){if(!se){if(se=!0,de=ve,ve=te(ve),ne!==void 0&&oe.hasValue){var me=oe.value;if(ne(me,ve))return ue=me}return ue=ve}if(me=ue,q(de,ve))return me;var be=te(ve);return ne!==void 0&&ne(me,be)?me:(de=ve,ue=be)}var se=!1,de,ue,pe=ee===void 0?null:ee;return[function(){return fe(Q())},pe===null?void 0:function(){return fe(pe())}]},[Q,ee,te,ne]);var ce=G(Z,ie[0],ie[1]);return Y(function(){oe.hasValue=!0,oe.value=ce},[ce]),X(ce),ce},withSelector_production_min}var withSelector_development={};/**
|
|
974
974
|
* @license React
|
|
975
975
|
* use-sync-external-store-shim/with-selector.development.js
|
|
976
976
|
*
|
|
@@ -978,7 +978,7 @@ Check the top-level render call using <`+kt+">.")}return pt}}function Nn(He,pt){
|
|
|
978
978
|
*
|
|
979
979
|
* This source code is licensed under the MIT license found in the
|
|
980
980
|
* LICENSE file in the root directory of this source tree.
|
|
981
|
-
*/var hasRequiredWithSelector_development;function requireWithSelector_development(){return hasRequiredWithSelector_development||(hasRequiredWithSelector_development=1,process.env.NODE_ENV!=="production"&&function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var $=React,I=
|
|
981
|
+
*/var hasRequiredWithSelector_development;function requireWithSelector_development(){return hasRequiredWithSelector_development||(hasRequiredWithSelector_development=1,process.env.NODE_ENV!=="production"&&function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var $=React,I=requireShim();function U(Q,ee){return Q===ee&&(Q!==0||1/Q===1/ee)||Q!==Q&&ee!==ee}var q=typeof Object.is=="function"?Object.is:U,G=I.useSyncExternalStore,K=$.useRef,Y=$.useEffect,J=$.useMemo,X=$.useDebugValue;function Z(Q,ee,te,ne,ie){var oe=K(null),ce;oe.current===null?(ce={hasValue:!1,value:null},oe.current=ce):ce=oe.current;var fe=J(function(){var pe=!1,ve,me,be=function(ke){if(!pe){pe=!0,ve=ke;var De=ne(ke);if(ie!==void 0&&ce.hasValue){var Be=ce.value;if(ie(Be,De))return me=Be,Be}return me=De,De}var Ve=ve,nt=me;if(q(Ve,ke))return nt;var ot=ne(ke);return ie!==void 0&&ie(nt,ot)?nt:(ve=ke,me=ot,ot)},ye=te===void 0?null:te,Se=function(){return be(ee())},xe=ye===null?void 0:function(){return be(ye())};return[Se,xe]},[ee,te,ne,ie]),se=fe[0],de=fe[1],ue=G(Q,se,de);return Y(function(){ce.hasValue=!0,ce.value=ue},[ue]),X(ue),ue}withSelector_development.useSyncExternalStoreWithSelector=Z,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()),withSelector_development}process.env.NODE_ENV==="production"?withSelector.exports=requireWithSelector_production_min():withSelector.exports=requireWithSelector_development();var withSelectorExports=withSelector.exports;/*! *****************************************************************************
|
|
982
982
|
Copyright (c) Microsoft Corporation.
|
|
983
983
|
|
|
984
984
|
Permission to use, copy, modify, and/or distribute this software for any
|