@helia/libp2p 1.0.1-688bd9de → 1.0.1-ef258e7e
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/index.min.js +1 -1
- package/dist/index.min.js.map +2 -2
- package/package.json +4 -4
package/dist/index.min.js
CHANGED
|
@@ -28,7 +28,7 @@ ${[...t.errors.entries()].map(([s,i])=>`
|
|
|
28
28
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
29
29
|
${e.join(`
|
|
30
30
|
`)}`:`${t} :`}};uw=Mo;z.Constructed=uw;Mo.NAME="CONSTRUCTED";var u1=class extends xt{fromBER(e,t,n){return t}toBER(e){return fn}};u1.override="EndOfContentValueBlock";var dw,d1=class extends ht{constructor(e={}){super(e,u1),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};dw=d1;z.EndOfContent=dw;d1.NAME=Hl;var fw,ti=class extends ht{constructor(e={}){super(e,xt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};fw=ti;z.Null=fw;ti.NAME="NULL";var f1=class extends Zn(xt){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=he.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,n){let o=he.BufferSourceConverter.toUint8Array(e);return Xn(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,A4.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};f1.NAME="BooleanValueBlock";var hw,h1=class extends ht{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,f1),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};hw=h1;z.Boolean=hw;h1.NAME="BOOLEAN";var p1=class extends Zn(un){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n,o){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=un.prototype.fromBER.call(this,e,t,n,o),s===-1)return s;for(let i=0;i<this.value.length;i++){let a=this.value[i].constructor.NAME;if(a===Hl){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==sw)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,t,n),this.blockLength=n;return s}toBER(e,t){return this.isConstructed?un.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};p1.NAME="OctetStringValueBlock";var _4,jn=class extends ht{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},p1),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n,o){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let a=o??Ql(),c=T4(i,0,i.byteLength,a);c.offset!==-1&&c.offset===n&&(this.valueBlock.value=[c.result])}}catch{}}return super.fromBER(e,t,n,o)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Mo.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,t=he.Convert.ToHex(this.valueBlock.valueHexView);return`${e} : ${t}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof _4&&e.push(t.valueBlock.valueHexView);return he.BufferSourceConverter.concat(e)}};_4=jn;z.OctetString=_4;jn.NAME=sw;var m1=class extends Zn(un){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n,o){if(!n)return t;let s=-1;if(this.isConstructed){if(s=un.prototype.fromBER.call(this,e,t,n,o),s===-1)return s;for(let c of this.value){let l=c.constructor.NAME;if(l===Hl){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(l!==iw)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=c.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return s}let i=he.BufferSourceConverter.toUint8Array(e);if(!Xn(this,i,t,n))return-1;let a=i.subarray(t,t+n);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let c=a.subarray(1);try{if(c.byteLength){let l=o??Ql(),u=T4(c,0,c.byteLength,l);u.offset!==-1&&u.offset===n-1&&(this.value=[u.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,t+n}toBER(e,t){if(this.isConstructed)return un.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let o=new Uint8Array(1);return o[0]=0,o.buffer}let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};m1.NAME="BitStringValueBlock";var pw,g1=class extends ht{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},m1),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n,o){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n,o)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Mo.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let i of t)e.push(i.toString(2).padStart(8,"0"));let n=e.join(""),o=this.constructor.NAME,s=n.substring(0,n.length-this.valueBlock.unusedBits);return`${o} : ${s}`}}};pw=g1;z.BitString=pw;g1.NAME=iw;var mw;function dD(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<i?i:c,d=0;for(let f=u;f>=0;f--,d++)!0===d<a.length?l=s[i-d]+a[c-d]+t[0]:l=s[i-d]+t[0],t[0]=l/10,!0===d>=s.length?s=n1(new Uint8Array([l%10]),s):s[i-d]=l%10;return t[0]>0&&(s=n1(t,s)),s}function ow(r){if(r>=Vl.length)for(let e=Vl.length;e<=r;e++){let t=new Uint8Array([0]),n=Vl[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=n1(t,n)),Vl.push(n)}return Vl[r]}function fD(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let d=c;d>=0;d--,u++)l=s[i-u]-a[c-u]-t,!0===l<0?(t=1,s[i-u]=l+10):(t=0,s[i-u]=l);if(t>0)for(let d=i-c+1;d>=0;d--,u++)if(l=s[i-u]-t,l<0)t=1,s[i-u]=l+10;else{t=0,s[i-u]=l;break}return s.slice()}var zl=class extends Zn(xt){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=A4.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(tw(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&(i[1]&128)!==0?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++)(o&1)===1&&(n===e?(t=fD(ow(n),t),i="-"):t=dD(t,ow(n))),n++,o>>=1}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=nw.charAt(t[c]));return a===!1&&(i+=nw.charAt(0)),i}};mw=zl;zl.NAME="IntegerValueBlock";Object.defineProperty(mw.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Kl,Yn=class extends ht{constructor(e={}){super(e,zl),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return o1(),BigInt(this.valueBlock.toString())}static fromBigInt(e){o1();let t=BigInt(e),n=new ql,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(he.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${he.Convert.ToHex(a)}`)+t,u=he.BufferSourceConverter.toUint8Array(he.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new Kl({valueHex:n.final()})}convertToDER(){let e=new Kl({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Kl({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Kl=Yn;z.Integer=Kl;Yn.NAME="INTEGER";var gw,y1=class extends Yn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};gw=y1;z.Enumerated=gw;y1.NAME="ENUMERATED";var Gl=class extends Zn(xt){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=he.BufferSourceConverter.toUint8Array(e);if(!Xn(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ei(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){o1();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Oo(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",fn;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=he.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Gl.NAME="sidBlock";var b1=class extends xt{constructor({value:e=ma,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Gl;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,fn;t.push(o)}return C4(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Gl;if(o>Number.MAX_SAFE_INTEGER){o1();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};b1.NAME="ObjectIdentifierValueBlock";var yw,dn=class extends ht{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,b1),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};yw=dn;z.ObjectIdentifier=yw;dn.NAME="OBJECT IDENTIFIER";var Wl=class extends Zn(Wn){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=he.BufferSourceConverter.toUint8Array(e);if(!Xn(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ei(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Oo(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",fn;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=he.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Wl.NAME="relativeSidBlock";var w1=class extends xt{constructor({value:e=ma,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Wl;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,fn;n.push(s)}return C4(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Wl;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};w1.NAME="RelativeObjectIdentifierValueBlock";var bw,x1=class extends ht{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,w1),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};bw=x1;z.RelativeObjectIdentifier=bw;x1.NAME="RelativeObjectIdentifier";var ww,Xt=class extends Mo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};ww=Xt;z.Sequence=ww;Xt.NAME="SEQUENCE";var xw,E1=class extends Mo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};xw=E1;z.Set=xw;E1.NAME="SET";var v1=class extends Zn(xt){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ma}toJSON(){return{...super.toJSON(),value:this.value}}};v1.NAME="StringValueBlock";var S1=class extends v1{};S1.NAME="SimpleStringValueBlock";var Vt=class extends a1{constructor({...e}={}){super(e,S1)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,he.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Vt.NAME="SIMPLE STRING";var A1=class extends Vt{fromBuffer(e){this.valueBlock.valueHexView=he.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=he.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=he.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(he.Convert.FromUtf8String(e)),this.valueBlock.value=e}};A1.NAME="Utf8StringValueBlock";var Ew,Qn=class extends A1{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Ew=Qn;z.Utf8String=Ew;Qn.NAME="UTF8String";var C1=class extends Vt{fromBuffer(e){this.valueBlock.value=he.Convert.ToUtf16String(e),this.valueBlock.valueHexView=he.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(he.Convert.FromUtf16String(e))}};C1.NAME="BmpStringValueBlock";var vw,I1=class extends C1{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};vw=I1;z.BmpString=vw;I1.NAME="BMPString";var T1=class extends Vt{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=Oo(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};T1.NAME="UniversalStringValueBlock";var Sw,_1=class extends T1{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Sw=_1;z.UniversalString=Sw;_1.NAME="UniversalString";var Aw,R1=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Aw=R1;z.NumericString=Aw;R1.NAME="NumericString";var Cw,L1=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Cw=L1;z.PrintableString=Cw;L1.NAME="PrintableString";var Iw,P1=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Iw=P1;z.TeletexString=Iw;P1.NAME="TeletexString";var Tw,D1=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Tw=D1;z.VideotexString=Tw;D1.NAME="VideotexString";var _w,k1=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};_w=k1;z.IA5String=_w;k1.NAME="IA5String";var Rw,N1=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Rw=N1;z.GraphicString=Rw;N1.NAME="GraphicString";var Lw,jl=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Lw=jl;z.VisibleString=Lw;jl.NAME="VisibleString";var Pw,O1=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Pw=O1;z.GeneralString=Pw;O1.NAME="GeneralString";var Dw,M1=class extends Vt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Dw=M1;z.CharacterString=Dw;M1.NAME="CharacterString";var kw,Yl=class extends jl{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,he.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=Qt(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=Qt(this.month,2),t[2]=Qt(this.day,2),t[3]=Qt(this.hour,2),t[4]=Qt(this.minute,2),t[5]=Qt(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};kw=Yl;z.UTCTime=kw;Yl.NAME="UTCTime";var Nw,B1=class extends Yl{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let d=new Number(e[e.length-1]);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let d=1,f=n.indexOf("+"),h="";if(f===-1&&(f=n.indexOf("-"),d=-1),f!==-1){if(h=n.substring(f+1),n=n.substring(0,f),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=d*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=d*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let d=new Number(`0${n.substring(l)}`);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");s=d.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=60*s;this.minute=Math.floor(d),d=60*(d-this.minute),this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=60*s;this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=1e3*s;this.millisecond=Math.floor(d)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let d=1;d<u.length;d++)switch(d){case 1:this.year=parseInt(u[d],10);break;case 2:this.month=parseInt(u[d],10);break;case 3:this.day=parseInt(u[d],10);break;case 4:this.hour=parseInt(u[d],10)+a;break;case 5:this.minute=parseInt(u[d],10)+c;break;case 6:this.second=parseInt(u[d],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let d=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=d.getUTCFullYear(),this.month=d.getUTCMonth(),this.day=d.getUTCDay(),this.hour=d.getUTCHours(),this.minute=d.getUTCMinutes(),this.second=d.getUTCSeconds(),this.millisecond=d.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(Qt(this.year,4)),t.push(Qt(this.month,2)),t.push(Qt(this.day,2)),t.push(Qt(this.hour,2)),t.push(Qt(this.minute,2)),t.push(Qt(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(Qt(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Nw=B1;z.GeneralizedTime=Nw;B1.NAME="GeneralizedTime";var Ow,U1=class extends Qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Ow=U1;z.DATE=Ow;U1.NAME="DATE";var Mw,F1=class extends Qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Mw=F1;z.TimeOfDay=Mw;F1.NAME="TimeOfDay";var Bw,$1=class extends Qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Bw=$1;z.DateTime=Bw;$1.NAME="DateTime";var Uw,V1=class extends Qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Uw=V1;z.Duration=Uw;V1.NAME="Duration";var Fw,K1=class extends Qn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Fw=K1;z.TIME=Fw;K1.NAME="TIME";async function H1(r,e){let n=await ha.create().encrypt(r,e);return _n.encode(n)}async function R4(r,e,t){if(r.type==="RSA")return gD(r,e,t);if(r.type==="Ed25519")return hD(r,e,t);if(r.type==="secp256k1")return pD(r,e,t);if(r.type==="ECDSA")return mD(r,e,t);throw new Ir}async function hD(r,e,t="libp2p-key"){if(t==="libp2p-key")return H1(Ns(r),e);throw new C(`export format '${t}' is not supported`)}async function pD(r,e,t="libp2p-key"){if(t==="libp2p-key")return H1(Ns(r),e);throw new C("Export format is not supported")}async function mD(r,e,t="libp2p-key"){if(t==="libp2p-key")return H1(Ns(r),e);throw new C(`export format '${t}' is not supported`)}async function gD(r,e,t="pkcs-8"){if(t==="pkcs-8")return yD(r,e);if(t==="libp2p-key")return H1(Ns(r),e);throw new C("Export format is not supported")}async function yD(r,e){let t=Qe.get(),o=new Xt({value:[new Yn({value:0}),new Xt({value:[new dn({value:"1.2.840.113549.1.1.1"}),new ti]}),new jn({valueHex:r.raw})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=t.getRandomValues(new Uint8Array(16)),a=await Jh(en,e,i,{c:1e4,dkLen:32}),c=t.getRandomValues(new Uint8Array(16)),l=await t.subtle.importKey("raw",ie(a),"AES-CBC",!1,["encrypt"]),u=await t.subtle.encrypt({name:"AES-CBC",iv:ie(c)},l,ie(s)),d=new Xt({value:[new jn({valueHex:i}),new Yn({value:1e4}),new Yn({value:32}),new Xt({value:[new dn({value:"1.2.840.113549.2.11"}),new ti]})]}),f=new Xt({value:[new dn({value:"1.2.840.113549.1.5.13"}),new Xt({value:[new Xt({value:[new dn({value:"1.2.840.113549.1.5.12"}),d]}),new Xt({value:[new dn({value:"2.16.840.1.101.3.4.1.42"}),new jn({valueHex:c})]})]})]}),p=new Xt({value:[f,new jn({valueHex:u})]}).toBER(),y=new Uint8Array(p,0,p.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...B(y,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
|
31
|
-
`)}async function L4(r,e){try{let t=await bD(r,e);return ky(t)}catch{}if(!r.includes("BEGIN"))throw new C("Encrypted key was not a libp2p-key or a PEM file");return wD(r,e)}async function bD(r,e){let t=_n.decode(r);return ha.create().decrypt(t,e)}async function wD(r,e){let t=Qe.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let s=O(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=q1(s),{iv:a,salt:c,iterations:l,keySize:u,cipherText:d}=xD(i),f=await Jh(en,e,c,{c:l,dkLen:u}),h=await t.subtle.importKey("raw",ie(f),"AES-CBC",!1,["decrypt"]),p=Xl(await t.subtle.decrypt({name:"AES-CBC",iv:ie(a)},h,ie(d))),{result:y}=q1(p);n=qw(y)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let s=O(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=q1(s);n=qw(i)}else throw new C("Could not parse private key from PEM data");let o=Ny(n);if(o.type!=="RSA")throw new C("Could not parse RSA private key from PEM data");return o}function xD(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new C("Only pkcs5PBES2 encrypted private keys are supported");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new C("Only pkcs5PBKDF2 key derivation functions are supported");let s=n.valueBlock.value[1],i=Xl(s.valueBlock.value[0].getValue()),a=1e4,c=32;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new C("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key");let l=e.valueBlock.value[1].valueBlock.value[1],u=l.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new C("Only AES-CBC encryption schemes are supported")}}}}let d=Xl(l.valueBlock.value[1].getValue());return{cipherText:Xl(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:d}}function qw(r){return Xl(r.valueBlock.value[2].getValue())}function Xl(r){return new Uint8Array(r,0,r.byteLength)}var ED="/pkcs8/",P4="/info/",Zl=new WeakMap,ri={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3};function ga(r){return r==null||typeof r!="string"?!1:r===(0,Hw.default)(r.trim())&&r.length>0}async function Et(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function ni(r){return new Rt(ED+r)}function ya(r){return new Rt(P4+r)}async function vD(r){let e=Ns(r),t=await pt.digest(e);return Ee.encode(t.bytes).substring(1)}var z1=class{components;init;log;self;constructor(e,t){if(this.components=e,this.log=e.logger.forComponent("libp2p:keychain"),this.init={...t,dek:{...v4,...t.dek}},this.self=t.selfKey??"self",this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLength<ri.minKeyLength)throw new Error(`dek.keyLength must be least ${ri.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<ri.minSaltLength)throw new Error(`dek.saltLength must be least ${ri.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<ri.minIterationCount)throw new Error(`dek.iterationCount must be least ${ri.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?$l(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Zl.set(this,{dek:n})}[Symbol.toStringTag]="@libp2p/keychain";[ue]=["@libp2p/keychain"];static generateOptions(){let e=Object.assign({},this.options),t=Math.ceil(ri.minSaltLength/3)*3;return e.dek!=null&&(e.dek.salt=B(crypto.getRandomValues(new Uint8Array(t)),"base64")),e}static get options(){return{dek:{...v4}}}async findKeyByName(e){if(!ga(e))throw await Et(),new C(`Invalid key name '${e}'`);let t=ya(e);try{let n=await this.components.datastore.get(t);return JSON.parse(B(n))}catch(n){throw await Et(),this.log.error("could not read key from datastore - %e",n),new Pe(`Key '${e}' does not exist.`)}}async findKeyById(e){try{let t={prefix:P4};for await(let n of this.components.datastore.query(t)){let o=JSON.parse(B(n.value));if(o.id===e)return o}throw new C(`Key with id '${e}' does not exist.`)}catch(t){throw await Et(),t}}async importKey(e,t){if(!ga(e))throw await Et(),new C(`Invalid key name '${e}'`);if(t==null)throw await Et(),new C("Key is required");let n=ni(e);if(await this.components.datastore.has(n))throw await Et(),new C(`Key '${e}' already exists`);let s,i;try{s=await vD(t);let l=Zl.get(this);if(l==null)throw new C("dek missing");let u=l.dek;i=await R4(t,u,t.type==="RSA"?"pkcs-8":"libp2p-key")}catch(l){throw await Et(),l}let a={name:e,id:s},c=this.components.datastore.batch();return c.put(n,O(i)),c.put(ya(e),O(JSON.stringify(a))),await c.commit(),a}async exportKey(e){if(!ga(e))throw await Et(),new C(`Invalid key name '${e}'`);let t=ni(e);try{let n=await this.components.datastore.get(t),o=B(n),s=Zl.get(this);if(s==null)throw new C("dek missing");let i=s.dek;return await L4(o,i)}catch(n){throw await Et(),n}}async removeKey(e){if(!ga(e)||e===this.self)throw await Et(),new C(`Invalid key name '${e}'`);let t=ni(e),n=await this.findKeyByName(e),o=this.components.datastore.batch();return o.delete(t),o.delete(ya(e)),await o.commit(),n}async listKeys(){let e={prefix:P4},t=[];for await(let n of this.components.datastore.query(e))t.push(JSON.parse(B(n.value)));return t}async renameKey(e,t){if(!ga(e)||e===this.self)throw await Et(),new C(`Invalid old key name '${e}'`);if(!ga(t)||t===this.self)throw await Et(),new C(`Invalid new key name '${t}'`);let n=ni(e),o=ni(t),s=ya(e),i=ya(t);if(await this.components.datastore.has(o))throw await Et(),new C(`Key '${t}' already exists`);try{let c=await this.components.datastore.get(n),l=await this.components.datastore.get(s),u=JSON.parse(B(l));u.name=t;let d=this.components.datastore.batch();return d.put(o,c),d.put(i,O(JSON.stringify(u))),d.delete(n),d.delete(s),await d.commit(),u}catch(c){throw await Et(),c}}async rotateKeychainPass(e,t){if(typeof e!="string")throw await Et(),new C(`Invalid old pass type '${typeof e}'`);if(typeof t!="string")throw await Et(),new C(`Invalid new pass type '${typeof t}'`);if(t.length<20)throw await Et(),new C(`Invalid pass length ${t.length}`);this.log("recreating keychain");let n=Zl.get(this);if(n==null)throw new C("dek missing");let o=n.dek;this.init.pass=t;let s=t!=null&&this.init.dek?.salt!=null?$l(t,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Zl.set(this,{dek:s});let i=await this.listKeys();for(let a of i){let c=await this.components.datastore.get(ni(a.name)),l=B(c),u=await L4(l,o),d=s.toString(),f=await R4(u,d,u.type==="RSA"?"pkcs-8":"libp2p-key"),h=this.components.datastore.batch(),p={name:a.name,id:a.id};h.put(ni(a.name),O(f)),h.put(ya(a.name),O(JSON.stringify(p))),await h.commit()}this.log("keychain reconstructed")}};function zw(r={}){return e=>new z1(e,r)}async function D4(r,e={}){let t=e.selfKey??"self",n=zw(e)({datastore:r,logger:qi()}),o;return await r.has(new Rt(`/pkcs8/${t}`))?o=await n.exportKey(t):(o=await Xd(e.keyType??"Ed25519"),await n.importKey(t,o)),o}function ot(r=0){return new Uint8Array(r)}function Pt(r=0){return new Uint8Array(r)}var ba=!!globalThis.process?.env?.DUMP_SESSION_KEYS,k4=16;function SD(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function G1(r){if(typeof r!="boolean")throw new TypeError(`boolean expected, not ${r}`)}function wa(r){if(typeof r!="number")throw new TypeError("number expected, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError("positive integer expected, got "+r)}function st(r,e,t=""){let n=SD(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function N4(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Gw(r,e,t=!1){st(r,void 0,"output");let n=e.outputLen;if(r.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(t&&!xa(r))throw new Error("invalid output, must be aligned")}function hn(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function qr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function AD(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var oi=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,CD=r=>r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255;var ID=r=>{for(let e=0;e<r.length;e++)r[e]=CD(r[e]);return r},Jn=oi?r=>r:ID;function Ww(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function jw(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Yw(r,e,t){let n=e,o=t||(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(r),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}var Qw=(r,e)=>{function t(n,...o){if(st(n,void 0,"key"),r.nonceLength!==void 0){let u=o[0];st(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let s=r.tagLength;s&&o[1]!==void 0&&st(o[1],void 0,"AAD");let i=e(n,...o),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");st(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,st(u),a(i.encrypt.length,d),i.encrypt(u,d)},decrypt(u,d){if(st(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,d),i.decrypt(u,d)}}}return Object.assign(t,r),t};function Jl(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(st(e,void 0,"output"),e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!xa(e))throw new Error("invalid output, must be aligned");return e}function Xw(r,e,t){wa(r),wa(e),G1(t);let n=new Uint8Array(16),o=AD(n);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(r),t),n}function xa(r){return r.byteOffset%4===0}function Ea(r){return Uint8Array.from(st(r))}var Jw=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),TD=Jn(hn(Jw("expand 16-byte k"))),_D=Jn(hn(Jw("expand 32-byte k")));function ge(r,e){return r<<e|r>>>32-e}var eu=64,RD=16,O4=2**32-1,Zw=Uint32Array.of();function LD(r,e,t,n,o,s,i,a){let c=o.length,l=new Uint8Array(eu),u=hn(l),d=oi&&xa(o)&&xa(s),f=d?hn(o):Zw,h=d?hn(s):Zw;if(!oi){for(let p=0;p<c;i++){if(r(e,t,n,u,i,a),Jn(u),i>=O4)throw new Error("arx: counter overflow");let y=Math.min(eu,c-p);for(let g=0,m;g<y;g++)m=p+g,s[m]=o[m]^l[g];p+=y}return}for(let p=0;p<c;i++){if(r(e,t,n,u,i,a),i>=O4)throw new Error("arx: counter overflow");let y=Math.min(eu,c-p);if(d&&y===eu){let g=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let m=0,b;m<RD;m++)b=g+m,h[b]=f[b]^u[m];p+=eu;continue}for(let g=0,m;g<y;g++)m=p+g,s[m]=o[m]^l[g];p+=y}}function ex(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Ww({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return wa(o),wa(i),G1(s),G1(t),(a,c,l,u,d=0)=>{st(a,void 0,"key"),st(c,void 0,"nonce"),st(l,void 0,"data");let f=l.length;if(u=Jl(f,u,!1),wa(d),d<0||d>=O4)throw new Error("arx: counter overflow");let h=[],p=a.length,y,g;if(p===32)h.push(y=Ea(a)),g=_D;else if(p===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),g=TD,h.push(y);else throw st(a,32,"arx key"),new Error("invalid key size");(!oi||!xa(c))&&h.push(c=Ea(c));let m=hn(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let x=c.subarray(0,16);if(oi)n(g,m,hn(x),m);else{let v=Jn(Uint32Array.from(g));n(v,m,hn(x),m),qr(v),Jn(m)}c=c.subarray(16)}else oi||Jn(m);let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let x=new Uint8Array(12);x.set(c,s?0:12-c.length),c=x,h.push(c)}let w=Jn(hn(c));try{return LD(r,g,m,w,l,u,d,i),u}finally{qr(...h)}}}function vt(r,e){return r[e++]&255|(r[e++]&255)<<8}var M4=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Ea(st(e,32,"key"));let t=vt(e,0),n=vt(e,2),o=vt(e,4),s=vt(e,6),i=vt(e,8),a=vt(e,10),c=vt(e,12),l=vt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=vt(e,16+2*u)}process(e,t,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],d=i[4],f=i[5],h=i[6],p=i[7],y=i[8],g=i[9],m=vt(e,t+0),b=vt(e,t+2),w=vt(e,t+4),x=vt(e,t+6),v=vt(e,t+8),A=vt(e,t+10),S=vt(e,t+12),I=vt(e,t+14),k=s[0]+(m&8191),K=s[1]+((m>>>13|b<<3)&8191),F=s[2]+((b>>>10|w<<6)&8191),E=s[3]+((w>>>7|x<<9)&8191),P=s[4]+((x>>>4|v<<12)&8191),L=s[5]+(v>>>1&8191),_=s[6]+((v>>>14|A<<2)&8191),T=s[7]+((A>>>11|S<<5)&8191),D=s[8]+((S>>>8|I<<8)&8191),N=s[9]+(I>>>5|o),R=0,M=R+k*a+K*(5*g)+F*(5*y)+E*(5*p)+P*(5*h);R=M>>>13,M&=8191,M+=L*(5*f)+_*(5*d)+T*(5*u)+D*(5*l)+N*(5*c),R+=M>>>13,M&=8191;let U=R+k*c+K*a+F*(5*g)+E*(5*y)+P*(5*p);R=U>>>13,U&=8191,U+=L*(5*h)+_*(5*f)+T*(5*d)+D*(5*u)+N*(5*l),R+=U>>>13,U&=8191;let G=R+k*l+K*c+F*a+E*(5*g)+P*(5*y);R=G>>>13,G&=8191,G+=L*(5*p)+_*(5*h)+T*(5*f)+D*(5*d)+N*(5*u),R+=G>>>13,G&=8191;let J=R+k*u+K*l+F*c+E*a+P*(5*g);R=J>>>13,J&=8191,J+=L*(5*y)+_*(5*p)+T*(5*h)+D*(5*f)+N*(5*d),R+=J>>>13,J&=8191;let Q=R+k*d+K*u+F*l+E*c+P*a;R=Q>>>13,Q&=8191,Q+=L*(5*g)+_*(5*y)+T*(5*p)+D*(5*h)+N*(5*f),R+=Q>>>13,Q&=8191;let Ie=R+k*f+K*d+F*u+E*l+P*c;R=Ie>>>13,Ie&=8191,Ie+=L*a+_*(5*g)+T*(5*y)+D*(5*p)+N*(5*h),R+=Ie>>>13,Ie&=8191;let Te=R+k*h+K*f+F*d+E*u+P*l;R=Te>>>13,Te&=8191,Te+=L*c+_*a+T*(5*g)+D*(5*y)+N*(5*p),R+=Te>>>13,Te&=8191;let _e=R+k*p+K*h+F*f+E*d+P*u;R=_e>>>13,_e&=8191,_e+=L*l+_*c+T*a+D*(5*g)+N*(5*y),R+=_e>>>13,_e&=8191;let ye=R+k*y+K*p+F*h+E*f+P*d;R=ye>>>13,ye&=8191,ye+=L*u+_*l+T*c+D*a+N*(5*g),R+=ye>>>13,ye&=8191;let Be=R+k*g+K*y+F*p+E*h+P*f;R=Be>>>13,Be&=8191,Be+=L*d+_*u+T*l+D*c+N*a,R+=Be>>>13,Be&=8191,R=(R<<2)+R|0,R=R+M|0,M=R&8191,R=R>>>13,U+=R,s[0]=M,s[1]=U,s[2]=G,s[3]=J,s[4]=Q,s[5]=Ie,s[6]=Te,s[7]=_e,s[8]=ye,s[9]=Be}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;qr(n)}update(e){N4(this),st(e),e=Ea(e);let{buffer:t,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,qr(this.h,this.r,this.buffer,this.pad)}digestInto(e){N4(this),Gw(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},tx=Yw(32,r=>new M4(r));function PD(r,e,t,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],d=e[1],f=e[2],h=e[3],p=e[4],y=e[5],g=e[6],m=e[7],b=o,w=t[0],x=t[1],v=t[2],A=i,S=a,I=c,k=l,K=u,F=d,E=f,P=h,L=p,_=y,T=g,D=m,N=b,R=w,M=x,U=v;for(let J=0;J<s;J+=2)A=A+K|0,N=ge(N^A,16),L=L+N|0,K=ge(K^L,12),A=A+K|0,N=ge(N^A,8),L=L+N|0,K=ge(K^L,7),S=S+F|0,R=ge(R^S,16),_=_+R|0,F=ge(F^_,12),S=S+F|0,R=ge(R^S,8),_=_+R|0,F=ge(F^_,7),I=I+E|0,M=ge(M^I,16),T=T+M|0,E=ge(E^T,12),I=I+E|0,M=ge(M^I,8),T=T+M|0,E=ge(E^T,7),k=k+P|0,U=ge(U^k,16),D=D+U|0,P=ge(P^D,12),k=k+P|0,U=ge(U^k,8),D=D+U|0,P=ge(P^D,7),A=A+F|0,U=ge(U^A,16),T=T+U|0,F=ge(F^T,12),A=A+F|0,U=ge(U^A,8),T=T+U|0,F=ge(F^T,7),S=S+E|0,N=ge(N^S,16),D=D+N|0,E=ge(E^D,12),S=S+E|0,N=ge(N^S,8),D=D+N|0,E=ge(E^D,7),I=I+P|0,R=ge(R^I,16),L=L+R|0,P=ge(P^L,12),I=I+P|0,R=ge(R^I,8),L=L+R|0,P=ge(P^L,7),k=k+K|0,M=ge(M^k,16),_=_+M|0,K=ge(K^_,12),k=k+K|0,M=ge(M^k,8),_=_+M|0,K=ge(K^_,7);let G=0;n[G++]=i+A|0,n[G++]=a+S|0,n[G++]=c+I|0,n[G++]=l+k|0,n[G++]=u+K|0,n[G++]=d+F|0,n[G++]=f+E|0,n[G++]=h+P|0,n[G++]=p+L|0,n[G++]=y+_|0,n[G++]=g+T|0,n[G++]=m+D|0,n[G++]=b+N|0,n[G++]=w+R|0,n[G++]=x+M|0,n[G++]=v+U|0}var DD=ex(PD,{counterRight:!1,counterLength:4,allowShortKeys:!1});var kD=new Uint8Array(16),rx=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(kD.subarray(t))},ND=new Uint8Array(32);function nx(r,e,t,n,o){o!==void 0&&st(o,void 0,"AAD");let s=r(e,t,ND),i=Xw(n.length,o?o.length:0,!0),a=tx.create(s);o&&rx(a,o),rx(a,n),a.update(i);let c=a.digest();return qr(s,i),c}var OD=r=>(e,t,n)=>({encrypt(s,i){let a=s.length;i=Jl(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=nx(r,e,t,c,n);return i.set(l,a),qr(l),i},decrypt(s,i){i=Jl(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=nx(r,e,t,a,n);if(!jw(c,l))throw qr(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),r(e,t,i,i,1),qr(l),i}}),B4=Qw({blockSize:64,nonceLength:12,tagLength:16},OD(DD));function sx(r,e,t){return Ln(r),t===void 0&&(t=new Uint8Array(r.outputLen)),ks(r,t,e)}var U4=Uint8Array.of(0),ox=Uint8Array.of();function ix(r,e,t,n=32){Ln(r),Ht(n,"length"),mt(e,void 0,"prk");let o=r.outputLen;if(e.length<o)throw new Error('"prk" must be at least HashLen octets');if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);t===void 0?t=ox:mt(t,void 0,"info");let i=new Uint8Array(s*o),a=ks.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)U4[0]=u+1,c.update(u===0?ox:l).update(t).update(U4).digestInto(l),i.set(l,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),At(l,U4),i.slice(0,n)}var F4={hashSHA256(r){return yr(r.subarray())},getHKDF(r,e){let t=sx(yr,e,r),o=ix(yr,t,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=$c.utils.randomSecretKey();return{publicKey:$c.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:$c.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return $c.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return B4(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return B4(n,e,t).decrypt(r.subarray(),o)}};var ax=F4;function cx(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var va=r=>{let e=Pt(2);return e[0]=r>>8,e[1]=r,e};va.bytes=2;var Sa=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};Sa.bytes=2;function lx(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var H4={};$(H4,{base10:()=>KD});var cie=new Uint8Array(0);function ux(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function eo(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function dx(r){return new TextEncoder().encode(r)}function fx(r){return new TextDecoder().decode(r)}function MD(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,g=0,m=0,b=p.length;m!==b&&p[m]===0;)m++,y++;for(var w=(b-m)*u+1>>>0,x=new Uint8Array(w);m!==b;){for(var v=p[m],A=0,S=w-1;(v!==0||A<g)&&S!==-1;S--,A++)v+=256*x[S]>>>0,x[S]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=A,m++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var k=c.repeat(y);I<w;++I)k+=r.charAt(x[I]);return k}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var g=0,m=0;p[y]===c;)g++,y++;for(var b=(p.length-y)*l+1>>>0,w=new Uint8Array(b);p[y];){var x=t[p.charCodeAt(y)];if(x===255)return;for(var v=0,A=b-1;(x!==0||v<m)&&A!==-1;A--,v++)x+=a*w[A]>>>0,w[A]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=v,y++}if(p[y]!==" "){for(var S=b-m;S!==b&&w[S]===0;)S++;for(var I=new Uint8Array(g+(b-S)),k=g;S!==b;)I[k++]=w[S++];return I}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var BD=MD,UD=BD,px=UD;var $4=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},V4=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return mx(this,e)}},K4=class{decoders;constructor(e){this.decoders=e}or(e){return mx(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function mx(r,e){return new K4({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var q4=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new $4(e,t,n),this.decoder=new V4(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Aa({name:r,prefix:e,encode:t,decode:n}){return new q4(r,e,t,n)}function Bo({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=px(t,r);return Aa({prefix:e,name:r,encode:n,decode:s=>eo(o(s))})}function FD(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function $D(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function VD(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ze({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=VD(n);return Aa({prefix:e,name:r,encode(s){return $D(s,n,t)},decode(s){return FD(s,o,t,r)}})}var KD=Bo({prefix:"9",name:"base10",alphabet:"0123456789"});var z4={};$(z4,{base16:()=>qD,base16upper:()=>HD});var qD=ze({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),HD=ze({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var G4={};$(G4,{base2:()=>zD});var zD=ze({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var W4={};$(W4,{base256emoji:()=>QD});var gx=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),GD=gx.reduce((r,e,t)=>(r[t]=e,r),[]),WD=gx.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function jD(r){return r.reduce((e,t)=>(e+=GD[t],e),"")}function YD(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=WD[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var QD=Aa({prefix:"\u{1F680}",name:"base256emoji",encode:jD,decode:YD});var j4={};$(j4,{base32:()=>Ca,base32hex:()=>ek,base32hexpad:()=>rk,base32hexpadupper:()=>nk,base32hexupper:()=>tk,base32pad:()=>ZD,base32padupper:()=>JD,base32upper:()=>XD,base32z:()=>ok});var Ca=ze({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),XD=ze({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ZD=ze({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),JD=ze({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ek=ze({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),tk=ze({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),rk=ze({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),nk=ze({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ok=ze({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Y4={};$(Y4,{base36:()=>tu,base36upper:()=>sk});var tu=Bo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),sk=Bo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Q4={};$(Q4,{base58btc:()=>pn,base58flickr:()=>ik});var pn=Bo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ik=Bo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var X4={};$(X4,{base64:()=>ak,base64pad:()=>ck,base64url:()=>lk,base64urlpad:()=>uk});var ak=ze({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ck=ze({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),lk=ze({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),uk=ze({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Z4={};$(Z4,{base8:()=>dk});var dk=ze({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var J4={};$(J4,{identity:()=>fk});var fk=Aa({prefix:"\0",name:"identity",encode:r=>fx(r),decode:r=>dx(r)});var Aie=new TextEncoder,Cie=new TextDecoder;var tg={};$(tg,{identity:()=>Ok});var mk=wx,yx=128,gk=127,yk=~gk,bk=Math.pow(2,31);function wx(r,e,t){e=e||[],t=t||0;for(var n=t;r>=bk;)e[t++]=r&255|yx,r/=128;for(;r&yk;)e[t++]=r&255|yx,r>>>=7;return e[t]=r|0,wx.bytes=t-n+1,e}var wk=eg,xk=128,bx=127;function eg(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw eg.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&bx)<<o:(i&bx)*Math.pow(2,o),o+=7}while(i>=xk);return eg.bytes=s-n,t}var Ek=Math.pow(2,7),vk=Math.pow(2,14),Sk=Math.pow(2,21),Ak=Math.pow(2,28),Ck=Math.pow(2,35),Ik=Math.pow(2,42),Tk=Math.pow(2,49),_k=Math.pow(2,56),Rk=Math.pow(2,63),Lk=function(r){return r<Ek?1:r<vk?2:r<Sk?3:r<Ak?4:r<Ck?5:r<Ik?6:r<Tk?7:r<_k?8:r<Rk?9:10},Pk={encode:mk,decode:wk,encodingLength:Lk},Dk=Pk,ru=Dk;function nu(r,e=0){return[ru.decode(r,e),ru.decode.bytes]}function Ia(r,e,t=0){return ru.encode(r,e,t),e}function Ta(r){return ru.encodingLength(r)}function Ra(r,e){let t=e.byteLength,n=Ta(r),o=n+Ta(t),s=new Uint8Array(o+t);return Ia(r,s,0),Ia(t,s,n),s.set(e,o),new _a(r,t,e,s)}function xx(r){let e=eo(r),[t,n]=nu(e),[o,s]=nu(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new _a(t,o,i,e)}function Ex(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ux(r.bytes,t.bytes)}}var _a=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var vx=0,kk="identity",Sx=eo;function Nk(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ra(vx,Sx(r))}var Ok={code:vx,name:kk,encode:Sx,digest:Nk};var og={};$(og,{sha256:()=>Bk,sha512:()=>Uk});var Mk=20;function ng({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new rg(r,e,t,n,o)}var rg=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Mk,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Ax(n,this.code,t?.truncate):n.then(o=>Ax(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ax(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ra(e,r)}function Ix(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Bk=ng({name:"sha2-256",code:18,encode:Ix("SHA-256")}),Uk=ng({name:"sha2-512",code:19,encode:Ix("SHA-512")});function Tx(r,e){let{bytes:t,version:n}=r;return n===0?$k(t,sg(r),e??pn.encoder):Vk(t,sg(r),e??Ca.encoder)}var _x=new WeakMap;function sg(r){let e=_x.get(r);if(e==null){let t=new Map;return _x.set(r,t),t}return e}var j1=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==su)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Kk)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Ra(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Ex(e.multihash,n.multihash)}toString(e){return Tx(this,e)}toJSON(){return{"/":Tx(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Rx(n,o,s.bytes))}else if(t[qk]===!0){let{version:n,multihash:o,code:s}=t,i=xx(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==su)throw new Error(`Version 0 CID must use dag-pb (code: ${su}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Rx(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,su,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=eo(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new _a(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,f]=nu(e.subarray(t));return t+=f,d},o=n(),s=su;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=Fk(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return sg(s).set(n,e),s}};function Fk(r,e){switch(r[0]){case"Q":{let t=e??pn;return[pn.prefix,t.decode(`${pn.prefix}${r}`)]}case pn.prefix:{let t=e??pn;return[pn.prefix,t.decode(r)]}case Ca.prefix:{let t=e??Ca;return[Ca.prefix,t.decode(r)]}case tu.prefix:{let t=e??tu;return[tu.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function $k(r,e,t){let{prefix:n}=t;if(n!==pn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Vk(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var su=112,Kk=18;function Rx(r,e,t){let n=Ta(r),o=n+Ta(e),s=new Uint8Array(o+t.byteLength);return Ia(r,s,0),Ia(e,s,n),s.set(t,o),s}var qk=Symbol.for("@ipld/js-cid/CID");var ig={...J4,...G4,...Z4,...H4,...z4,...j4,...Y4,...Q4,...X4,...W4},Wie={...og,...tg};function Px(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Lx=Px("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ag=Px("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Pt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Hk={utf8:Lx,"utf-8":Lx,hex:ig.base16,latin1:ag,ascii:ag,binary:ag,...ig},Y1=Hk;function mn(r,e="utf8"){let t=Y1[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function cg(r,e){!e.enabled||!ba||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${mn(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${mn(r.privateKey,"hex")}`)):e("Missing local static keys."))}function lg(r,e){!e.enabled||!ba||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${mn(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${mn(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Dx(r,e){!e.enabled||!ba||e(r?`REMOTE_STATIC_PUBLIC_KEY ${mn(r.subarray(),"hex")}`:"Missing remote static public key.")}function ug(r,e){!e.enabled||!ba||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${mn(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function dg(r,e,t){!t.enabled||!ba||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&mn(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&mn(e.k,"hex")}`))}function La(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Pt(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function fg(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Nx=Symbol.for("@achingbrain/uint8arraylist");function kx(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Q1(r){return!!r?.[Nx]}var gn=class r{bufs;length;[Nx]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Q1(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Q1(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=kx(this.bufs,e);return t.buf[t.index]}set(e,t){let n=kx(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Q1(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return La(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:La(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Q1(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let f=l;f>=0;f--){let h=this.get(d+f);if(n[f]!==h){u=Math.max(1,f-a[h]);break}}if(u===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Pt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ot(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Pt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ot(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!fg(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function si(r,e="utf8"){let t=Y1[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Pa=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Gk=0,Wk=4294967295,jk="Cipherstate has reached maximum n, a new handshake must be performed",X1=class{n;bytes;view;constructor(e=Gk){this.n=e,this.bytes=ot(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>Wk)throw new Error(jk)}};var ii=ot(0),Da=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new X1(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let o=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},hg=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=si(t,"utf-8");this.h=Yk(e,n),this.ck=this.h,this.cs=new Da(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new Da(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new gn(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,ii);return[new Da(this.crypto,e),new Da(this.crypto,t)]}},pg=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new hg(t,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let o=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},iu=class extends pg{writeMessageA(e){return new gn(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new gn(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new gn(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new Pa(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new Pa(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new Pa(`handshake stage 2 validation fail: ${t.message}`)}}};function Yk(r,e){if(e.length<=32){let t=ot(32);return t.set(e),t}else return r.hash(e)}var Qk=Math.pow(2,7),Xk=Math.pow(2,14),Zk=Math.pow(2,21),Ox=Math.pow(2,28),Mx=Math.pow(2,35),Bx=Math.pow(2,42),Ux=Math.pow(2,49),Kt=128,Uo=127;function au(r){if(r<Qk)return 1;if(r<Xk)return 2;if(r<Zk)return 3;if(r<Ox)return 4;if(r<Mx)return 5;if(r<Bx)return 6;if(r<Ux)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Fx(r,e,t=0){switch(au(r)){case 8:e[t++]=r&255|Kt,r/=128;case 7:e[t++]=r&255|Kt,r/=128;case 6:e[t++]=r&255|Kt,r/=128;case 5:e[t++]=r&255|Kt,r/=128;case 4:e[t++]=r&255|Kt,r>>>=7;case 3:e[t++]=r&255|Kt,r>>>=7;case 2:e[t++]=r&255|Kt,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function $x(r,e){let t=r[e],n=0;if(n+=t&Uo,t<Kt||(t=r[e+1],n+=(t&Uo)<<7,t<Kt)||(t=r[e+2],n+=(t&Uo)<<14,t<Kt)||(t=r[e+3],n+=(t&Uo)<<21,t<Kt)||(t=r[e+4],n+=(t&Uo)*Ox,t<Kt)||(t=r[e+5],n+=(t&Uo)*Mx,t<Kt)||(t=r[e+6],n+=(t&Uo)*Bx,t<Kt)||(t=r[e+7],n+=(t&Uo)*Ux,t<Kt))return n;throw new RangeError("Could not decode varint")}var mg=new Float32Array([-0]),Fo=new Uint8Array(mg.buffer);function Vx(r,e,t){mg[0]=r,e[t]=Fo[0],e[t+1]=Fo[1],e[t+2]=Fo[2],e[t+3]=Fo[3]}function Kx(r,e){return Fo[0]=r[e],Fo[1]=r[e+1],Fo[2]=r[e+2],Fo[3]=r[e+3],mg[0]}var gg=new Float64Array([-0]),Dt=new Uint8Array(gg.buffer);function qx(r,e,t){gg[0]=r,e[t]=Dt[0],e[t+1]=Dt[1],e[t+2]=Dt[2],e[t+3]=Dt[3],e[t+4]=Dt[4],e[t+5]=Dt[5],e[t+6]=Dt[6],e[t+7]=Dt[7]}function Hx(r,e){return Dt[0]=r[e],Dt[1]=r[e+1],Dt[2]=r[e+2],Dt[3]=r[e+3],Dt[4]=r[e+4],Dt[5]=r[e+5],Dt[6]=r[e+6],Dt[7]=r[e+7],gg[0]}var Jk=BigInt(Number.MAX_SAFE_INTEGER),eN=BigInt(Number.MIN_SAFE_INTEGER),fr=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return ai;if(e<Jk&&e>eN)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>zx&&(o=0n,++n>zx&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return ai;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ai}},ai=new fr(0,0);ai.toBigInt=function(){return 0n};ai.zzEncode=ai.zzDecode=function(){return this};ai.length=function(){return 1};var zx=4294967296n;function Gx(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Wx(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function yg(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Hr(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Z1(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var bg=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Hr(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Hr(this,4);return Z1(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Hr(this,4);return Z1(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Hr(this,4);let e=Kx(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Hr(this,4);let e=Hx(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Hr(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Wx(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Hr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Hr(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new fr(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Hr(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Hr(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Hr(this,8);let e=Z1(this.buf,this.pos+=4),t=Z1(this.buf,this.pos+=4);return new fr(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=$x(this.buf,this.pos);return this.pos+=au(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function wg(r){return new bg(r instanceof Uint8Array?r:r.subarray())}function J1(r,e,t){let n=wg(r);return e.decode(n,void 0,t)}function xg(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Pt(i);o+i>e&&(n=Pt(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var ci=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Eg(){}var Sg=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},tN=xg();function rN(r){return globalThis.Buffer!=null?Pt(r):tN(r)}var lu=class{len;head;tail;states;constructor(){this.len=0,this.head=new ci(Eg,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new ci(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ag((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(e0,10,fr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=fr.fromBigInt(e);return this._push(e0,t.length(),t)}uint64Number(e){return this._push(Fx,au(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=fr.fromBigInt(e).zzEncode();return this._push(e0,t.length(),t)}sint64Number(e){let t=fr.fromNumber(e).zzEncode();return this._push(e0,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(vg,1,e?1:0)}fixed32(e){return this._push(cu,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=fr.fromBigInt(e);return this._push(cu,4,t.lo)._push(cu,4,t.hi)}fixed64Number(e){let t=fr.fromNumber(e);return this._push(cu,4,t.lo)._push(cu,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Vx,4,e)}double(e){return this._push(qx,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(vg,1,0):this.uint32(t)._push(oN,t,e)}string(e){let t=Gx(e);return t!==0?this.uint32(t)._push(yg,t,e):this._push(vg,1,0)}fork(){return this.states=new Sg(this),this.head=this.tail=new ci(Eg,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new ci(Eg,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=rN(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function vg(r,e,t){e[t]=r&255}function nN(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ag=class extends ci{next;constructor(e,t){super(nN,e,t),this.next=void 0}};function e0(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function cu(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function oN(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(lu.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(sN,e,r),this},lu.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(iN,e,r),this});function sN(r,e,t){e.set(r,t)}function iN(r,e,t){r.length<40?yg(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(si(r),t)}function Cg(){return new lu}function t0(r,e){let t=Cg();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var uu;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(uu||(uu={}));function Ig(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function r0(r,e){return Ig("message",uu.LENGTH_DELIMITED,r,e)}var du=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var n0;(function(r){let e;r.codec=()=>(e==null&&(e=r0((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);if(t.streamMuxers!=null)for(let s of t.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new du('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(t.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new du('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>t0(t,r.codec()),r.decode=(t,n)=>J1(t,r.codec(),n)})(n0||(n0={}));var fu;(function(r){let e;r.codec=()=>(e==null&&(e=r0((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),n0.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={identityKey:ot(0),identitySig:ot(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.identityKey=t.bytes();break}case 2:{s.identitySig=t.bytes();break}case 4:{s.extensions=n0.codec().decode(t,t.uint32(),{limits:o.limits?.extensions});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>t0(t,r.codec()),r.decode=(t,n)=>J1(t,r.codec(),n)})(fu||(fu={}));async function _g(r,e,t){let n=await r.sign(Qx(e));return fu.encode({identityKey:ct(r.publicKey),identitySig:n,extensions:t})}async function Rg(r,e,t){try{let n=fu.decode(r),o=nt(n.identityKey);if(t?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let s=Qx(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new fd(n.message)}}function Qx(r){let e=si("noise-libp2p-static-key:");return r instanceof Uint8Array?La([e,r],e.length+r.length):(r.prepend(e),r)}var Tg=class extends To{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new Pf({lengthDecoder:Sa,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let t=new gn;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),t.append(va(s.byteLength)),t.append(s)}return t}decrypt(e){let t=new gn;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-k4<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-k4);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),t.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function Lg(r,e,t){return new Tg(r,e,t)}async function Xx(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await _g(s,a.publicKey,l),d=new iu({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});cg(d.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(d.writeMessageA(ii),e),t.trace("Stage 0 - Initiator finished sending first message."),lg(d.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let f=d.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),ug(d.re,t),Dx(d.rs,t),t.trace("Initiator going to check remote's signature...");let h=await Rg(f,d.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(d.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[p,y]=d.ss.split();return dg(p,y,t),{payload:h,encrypt:g=>p.encryptWithAd(ii,g),decrypt:(g,m)=>y.decryptWithAd(ii,g,m)}}async function Zx(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await _g(s,a.publicKey,l),d=new iu({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});cg(d.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),ug(d.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(d.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),lg(d.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let f=d.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let h=await Rg(f,d.rs,c),[p,y]=d.ss.split();return dg(p,y,t),{payload:h,encrypt:g=>y.encryptWithAd(ii,g),decrypt:(g,m)=>p.decryptWithAd(ii,g,m)}}var o0=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??ax;this.crypto=cx(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?lx(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ot(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[ue]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,o=Po(e,{lengthEncoder:va,lengthDecoder:Sa,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=nt(s.payload.identityKey);return{connection:Lg(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:nn(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let o=t.get(n);if(o!=null)return o}if(e.length)throw new hd("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=e.log?.newScope("noise")??this.log,o=Po(e,{lengthEncoder:va,lengthDecoder:Sa,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=nt(s.payload.identityKey);return{connection:Lg(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:nn(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Xx({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Zx({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function s0(r={}){return e=>new o0(e,r)}function to(r=0){return new Uint8Array(r)}function pu(r=0){return new Uint8Array(r)}function Pg(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=pu(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function Jx(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var tE=Symbol.for("@achingbrain/uint8arraylist");function eE(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function i0(r){return!!r?.[tE]}var ka=class r{bufs;length;[tE]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(i0(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(i0(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=eE(this.bufs,e);return t.buf[t.index]}set(e,t){let n=eE(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(i0(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Pg(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Pg(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!i0(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let f=l;f>=0;f--){let h=this.get(d+f);if(n[f]!==h){u=Math.max(1,f-a[h]);break}}if(u===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=pu(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=to(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=to(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=to(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=pu(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=to(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=to(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=to(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=to(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=to(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Jx(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var $e;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})($e||($e={}));var be;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(be||(be={}));var ale=Object.values(be).filter(r=>typeof r!="string"),rE=0,it;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(it||(it={}));var yn=12;var ro=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function nE(r){return r?.reason!==null}var hr=class extends ro{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,it.ProtocolError),this.name="InvalidFrameError"}},Na=class extends ro{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,it.ProtocolError),this.name="UnRequestedPingError"}},Oa=class extends ro{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,it.ProtocolError),this.name="NotMatchingPingError"}};var a0=class extends ro{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,it.ProtocolError),this.name="StreamAlreadyExistsError"}},c0=class extends ro{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,it.ProtocolError),this.name="DecodeInvalidVersionError"}},l0=class extends ro{static name="BothClientsError";constructor(e="Both clients"){super(e,it.ProtocolError),this.name="BothClientsError"}},Ma=class extends ro{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,it.ProtocolError),this.name="ReceiveWindowExceededError"}};var fle=new Set([hr.name,Na.name,Oa.name,a0.name,c0.name,l0.name,Ma.name]),mu=256*1024,u0=16*1024*1024;var gu={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:mu,maxStreamWindowSize:u0,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function oE(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new C("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new C("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new C("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new C("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<mu)throw new C("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new C("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new C("MaxStreamWindowSize must be less than equal MAX_UINT32")}function iE(r){return r.header.type===$e.Data&&r.data!==null}var sE=2**24;function aN(r){if(r[0]!==rE)throw new hr("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*sE+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*sE+(r[9]<<16)+(r[10]<<8)+r[11]}}var d0=class{buffer;constructor(){this.buffer=new ka}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=yn;if(this.buffer.byteLength<yn)return;let t=aN(this.buffer.subarray(0,yn));if(t.type===$e.Data){if(e+=t.length,this.buffer.byteLength<e)return;let n=this.buffer.sublist(yn,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}};function Dg(r){let e=new Uint8Array(yn);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}var qt;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(qt||(qt={}));var f0=class extends Lo{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??mu;super({...e,maxMessageSize:t-yn}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??u0,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let n=()=>{this.state=qt.Finished};this.addEventListener("close",n)}sendData(e){let t=e.byteLength,n=0,o=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){o=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}let s=Math.min(this.sendWindowCapacity,e.byteLength),i=this.getSendFlags(),a=e.sublist(0,s);e.consume(s);let c=this.sendFrame({type:$e.Data,flag:i,streamID:this.streamId,length:s},a);if(this.sendWindowCapacity-=s,n+=s,!c){o=c,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:o}}sendReset(){this.sendFrame({type:$e.WindowUpdate,flag:be.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|be.FIN;this.sendFrame({type:$e.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=qt.Paused}sendResume(){this.state=qt.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-yn,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!iE(e))throw new hr("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new Ma("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&be.ACK)===be.ACK&&this.state===qt.SYNSent&&(this.state=qt.Established),(e&be.FIN)===be.FIN&&this.onRemoteCloseWrite(),(e&be.RST)===be.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case qt.Init:return this.state=qt.SYNSent,be.SYN;case qt.SYNReceived:return this.state=qt.Established,be.ACK;default:return 0}}sendWindowUpdate(){if(this.state===qt.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>-1&&t-this.epochStart<=n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let o=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:$e.WindowUpdate,flag:e,streamID:this.streamId,length:o})}};function aE(r){return{type:$e[r.type],flags:[(r.flag&be.SYN)===be.SYN?"SYN":void 0,(r.flag&be.ACK)===be.ACK?"ACK":void 0,(r.flag&be.FIN)===be.FIN?"FIN":void 0,(r.flag&be.RST)===be.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var cE="/yamux/1.0.0",h0=class{protocol=cE;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[ue]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new kg(e,{...this._init})}},kg=class extends Ro{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:cE,name:"yamux"}),this.client=e.direction==="outbound",oE(t),this.enableKeepAlive=t.enableKeepAlive??gu.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??gu.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??gu.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??gu.maxOutboundStreams,this.decoder=new d0,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=ia(async n=>{try{await this.ping(n)}catch(o){this.log.error("ping error: %s",o)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new Ar("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Ar("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new xi("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,qt.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new Ar("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Ar("Muxer closed locally");if(this.activePing!=null)return De(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await De(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??it.NormalTermination;this.log.trace("muxer close reason=%s",it[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=it.InternalError;nE(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(this.streams.find(s=>s.streamId===e)!=null)throw new C("Stream already exists with that id");let o=new f0({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return o.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),o}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:n,length:o}=e.header;if(this.log.trace("received frame %o",aE(e.header)),t===0)switch(n){case $e.Ping:{this.handlePing(e.header);return}case $e.GoAway:{this.handleGoAway(o);return}default:throw new hr("Invalid frame type")}else switch(e.header.type){case $e.Data:case $e.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new hr("Invalid frame type")}}handlePing(e){if(e.flag===be.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,be.ACK);else if(e.flag===be.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new hr("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new Na("ping not requested");if(this.activePing.id!==e)throw new Oa("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",it[e]??"unknown"),this.remoteGoAway=e,e===it.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:n,type:o}=e.header;(n&be.SYN)===be.SYN&&this.incomingStream(t);let s=this.streams.find(i=>i.streamId===t);if(s===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(o){case $e.WindowUpdate:{s.handleWindowUpdate(e);return}case $e.Data:{s.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new C("Both endpoints are clients");if(this.streams.find(n=>n.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:$e.WindowUpdate,flag:be.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:$e.WindowUpdate,flag:be.RST,streamID:e,length:0});return}let t=this._newStream(e,qt.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===$e.Data){if(t==null)throw new hr("Invalid frame");n=new ka(Dg(e),t)}else n=Dg(e);return this.log.trace("sending frame %o",aE(e)),this.send(n)}sendPing(e,t=be.SYN){t===be.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:$e.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=it.NormalTermination){this.log("sending GoAway reason=%s",it[e]),this.localGoAway=e,this.sendFrame({type:$e.GoAway,flag:0,streamID:0,length:e})}};function lE(r={}){return()=>new h0(r)}async function*yu(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var p0=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*Ba(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),Ai(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new p0("Incoming message too long");let i=o.split(t);o=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var li=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},xr=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};var m0={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},g0=class{url;started;httpQueue;shutDownController;timeout;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(e,t){this.log=e.logger.forComponent("helia:delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new jt({concurrency:t.concurrentRequests??m0.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??m0.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.cacheName=t.cacheName??m0.cacheName,this.cacheTTL=t.cacheTTL??m0.cacheTTL}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&this.log("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){this.log("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=me([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers(),a=0;this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let c=new URL(`${this.url}routing/v1/providers/${e}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l=await this.#r(c.toString(),{headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:o});if(!l.ok){if(l.status===404)return;throw l.status===422?new li("Request does not conform to schema or semantic constraints"):new xr(`Unexpected status code: ${l.status}`)}let u=l.headers.get("Content-Type");if(u==null)throw new xr("No Content-Type header received");if(l.body==null){if(u!=="application/x-ndjson")throw new xr("Routing response had no body");return}if(u.startsWith("application/json")){let f=(await l.json()).Providers??[];for(let h of f){let p=this.#e(h);p!=null&&(a++,yield p)}}else if(u.includes("application/x-ndjson"))for await(let d of Ba(yu(l.body))){let f=this.#e(d);f!=null&&(a++,yield f)}else throw new xr(`Unsupported Content-Type: ${u}`)}finally{o.clear(),i.resolve(),this.log("getProviders finished found %d providers for %c",a,e)}}async*getPeers(e,t={}){this.log("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=me([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.url}routing/v1/peers/${e}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c=await this.#r(a.toString(),{headers:{Accept:"application/x-ndjson"},signal:o});if(c.status===404)return;if(c.status===422)throw new li("Request does not conform to schema or semantic constraints");if(c.body==null)throw new xr("Routing response had no body");if(c.headers.get("Content-Type")?.startsWith("application/json")){let d=(await c.json()).Peers??[];for(let f of d){let h=this.#e(f);h!=null&&(yield h)}}else for await(let u of Ba(yu(c.body))){let d=this.#e(u);d!=null&&(yield d)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),i.resolve(),this.log("getPeers finished: %c",e)}}async*getClosestPeers(e,t={}){let n;if(ae.asCID(e)===e||e instanceof ae)n=e.toV1().toString();else throw new C("Key must be CID");this.log("getClosestPeers starts: %s",n);let o=AbortSignal.timeout(this.timeout),s=me([this.shutDownController.signal,o,t.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));try{await i.promise;let c=new URL(`${this.url}routing/v1/dht/closest/peers/${n}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l=await this.#r(c.toString(),{headers:{Accept:"application/x-ndjson"},signal:s});if(l.status===404)return;if(l.status===422)throw new li("Request does not conform to schema or semantic constraints");if(l.body==null)throw new xr("Routing response had no body");if(l.headers.get("Content-Type")?.startsWith("application/json")){let f=(await l.json()).Peers??[];for(let h of f){let p=this.#e(h);p!=null&&(yield p)}}else for await(let d of Ba(yu(l.body))){let f=this.#e(d);f!=null&&(yield f)}}catch(c){this.log.error("getClosestPeers errored - %e",c)}finally{s.clear(),a.resolve(),this.log("getClosestPeers finished: %s",n)}}async getIPNS(e,t={}){this.log("getIPNS starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=me([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await s.promise;let c=await this.#r(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(this.log("getIPNS GET %s %d",a,c.status),c.status===404)throw new Pe("No matching records found");if(c.status===422)throw new li("Request does not conform to schema or semantic constraints");if(!c.ok)throw new xr(`Unexpected status code: ${c.status}`);let l=c.headers.get("Content-Type");if(l==null||!l.includes("application/vnd.ipfs.ipns-record"))throw new Pe("No matching records found");if(c.body==null)throw new xr("GET ipns response had no body");let u=await c.arrayBuffer();return new Uint8Array(u,0,u.byteLength)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),i.resolve(),this.log("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=me([this.shutDownController.signal,o,n.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${e}`;try{await i.promise;let l=await this.#r(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:ie(t),signal:s});if(this.log("putIPNS PUT %s %d",c,l.status),l.status!==200)throw new xr("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{s.clear(),a.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(V)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:ae.createV1(114,cN(e.ID)),Addrs:n,Protocols:t}}catch(t){this.log.error("could not conform record to peer schema - %e",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#r(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",o),this.logResponse(c),c;this.log("evicting cached response for %s",o),await this.cache?.delete(e)}else this.cache!=null&&this.log("cache miss for %s",o)}let s=this.inFlightRequests.get(o);if(s!=null){let c=await s;return this.log("deduplicating outgoing request for %s",o),c.clone()}this.log("outgoing request:"),this.logRequest(e,t);let i=fetch(e,t).then(async c=>{if(this.log("incoming response:"),this.logResponse(c),this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,u=new Headers(c.headers);u.set("x-cache-expires",l.toString());let d=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:u});await this.cache.put(e,d)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(e,t){let n=new Headers(t.headers);this.log("%s %s HTTP/1.1",t.method??"GET",e);for(let[o,s]of n.entries())this.log("%s: %s",o,s)}logResponse(e){this.log("HTTP/1.1 %d %s",e.status,e.statusText);for(let[t,n]of e.headers.entries())this.log("%s: %s",t,n)}};function cN(r){let e=Ee.baseDecode(r);return ve(e)}function lN(r){return r[Symbol.asyncIterator]!=null}function uN(r){if(lN(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var uE=uN;var y0=O("/ipns/");function dE(r){return Z(r.subarray(0,y0.byteLength),y0)}var b0=class{client;constructor(e){this.client=e}get[is](){return this}async start(){await this.client.start()}async stop(){await this.client.stop()}async*findProviders(e,t={}){try{yield*Kr(this.client.getProviders(e,t),n=>({id:Mt(n.ID),multiaddrs:n.Addrs??[],routing:"delegated-http-routing-v1"}))}catch(n){if(n instanceof Pe)return;throw n}}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!dE(e))return;let o=ve(e.slice(y0.length)),s=ae.createV1(114,o);await this.client.putIPNS(s,t,n)}async get(e,t){if(!dE(e))throw new Pe("Not found");let n=ve(e.slice(y0.length)),o=ae.createV1(114,n);try{return await this.client.getIPNS(o,t)}catch(s){throw s.name==="BadResponseError"?new Pe("Not found"):s}}toString(){return`DelegatedRoutingV1HttpApiClientContentRouting(${this.client.url})`}},w0=class{client;constructor(e){this.client=e}get[ds](){return this}async start(){await this.client.start()}async stop(){await this.client.stop()}async findPeer(e,t={}){let n=await uE(this.client.getPeers(e.toCID(),t));if(n!=null)return{id:Mt(n.ID),multiaddrs:n.Addrs??[]};throw new Pe("Not found")}async*getClosestPeers(e,t={}){let n;try{n=ae.decode(e)}catch{try{n=ae.createV1(114,Ue.decode(e))}catch{n=ae.createV1(Cd,nr.digest(e))}}for await(let o of this.client.getClosestPeers(n,t))yield{id:Mt(o.ID),multiaddrs:o.Addrs??[]}}toString(){return`DelegatedRoutingV1HttpApiClientPeerRouting(${this.client.url})`}};function fE(r){return e=>new g0(e,r)}function hE(r){return e=>new b0(fE(r)(e))}function pE(r){return e=>new w0(fE(r)(e))}function x0(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}var mE="libp2p",gE="autonat",yE="1.0.0";var Me;(function(r){let e;(function(f){f.DIAL="DIAL",f.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(f){f[f.DIAL=0]="DIAL",f[f.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),(function(f){f.codec=()=>rt(t)})(e=r.MessageType||(r.MessageType={}));let n;(function(f){f.OK="OK",f.E_DIAL_ERROR="E_DIAL_ERROR",f.E_DIAL_REFUSED="E_DIAL_REFUSED",f.E_BAD_REQUEST="E_BAD_REQUEST",f.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let o;(function(f){f[f.OK=0]="OK",f[f.E_DIAL_ERROR=100]="E_DIAL_ERROR",f[f.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",f[f.E_BAD_REQUEST=200]="E_BAD_REQUEST",f[f.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(o||(o={})),(function(f){f.codec=()=>rt(o)})(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(f){let h;f.codec=()=>(h==null&&(h=ne((m,b,w={})=>{if(w.lengthDelimited!==!1&&b.fork(),m.id!=null&&(b.uint32(10),b.bytes(m.id)),m.addrs!=null&&m.addrs.length>0)for(let x of m.addrs)b.uint32(18),b.bytes(x);w.lengthDelimited!==!1&&b.ldelim()},(m,b,w={})=>{let x={addrs:[]},v=b==null?m.len:m.pos+b;for(;m.pos<v;){let A=m.uint32();switch(A>>>3){case 1:{x.id=m.bytes();break}case 2:{if(w.limits?.addrs!=null&&x.addrs.length===w.limits.addrs)throw new fe('Decode error - repeated field "addrs" had too many elements');x.addrs.push(m.bytes());break}default:{m.skipType(A&7);break}}}return x},function*(m,b,w,x={}){let v={addrs:0},A=b==null?m.len:m.pos+b;for(;m.pos<A;){let S=m.uint32();switch(S>>>3){case 1:{yield{field:`${w}.id`,value:m.bytes()};break}case 2:{if(x.limits?.addrs!=null&&v.addrs===x.limits.addrs)throw new fe('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${w}.addrs[]`,index:v.addrs,value:m.bytes()},v.addrs++;break}default:{m.skipType(S&7);break}}}})),h);function p(m){return te(m,f.codec())}f.encode=p;function y(m,b){return ee(m,f.codec(),b)}f.decode=y;function g(m,b){return re(m,f.codec(),b)}f.stream=g})(s=r.PeerInfo||(r.PeerInfo={}));let i;(function(f){let h;f.codec=()=>(h==null&&(h=ne((m,b,w={})=>{w.lengthDelimited!==!1&&b.fork(),m.peer!=null&&(b.uint32(10),r.PeerInfo.codec().encode(m.peer,b)),w.lengthDelimited!==!1&&b.ldelim()},(m,b,w={})=>{let x={},v=b==null?m.len:m.pos+b;for(;m.pos<v;){let A=m.uint32();A>>>3===1?x.peer=r.PeerInfo.codec().decode(m,m.uint32(),{limits:w.limits?.peer}):m.skipType(A&7)}return x},function*(m,b,w,x={}){let v=b==null?m.len:m.pos+b;for(;m.pos<v;){let A=m.uint32();A>>>3===1?yield*r.PeerInfo.codec().stream(m,m.uint32(),`${w}.peer`,{limits:x.limits?.peer}):m.skipType(A&7)}})),h);function p(m){return te(m,f.codec())}f.encode=p;function y(m,b){return ee(m,f.codec(),b)}f.decode=y;function g(m,b){return re(m,f.codec(),b)}f.stream=g})(i=r.Dial||(r.Dial={}));let a;(function(f){let h;f.codec=()=>(h==null&&(h=ne((m,b,w={})=>{w.lengthDelimited!==!1&&b.fork(),m.status!=null&&(b.uint32(8),r.ResponseStatus.codec().encode(m.status,b)),m.statusText!=null&&(b.uint32(18),b.string(m.statusText)),m.addr!=null&&(b.uint32(26),b.bytes(m.addr)),w.lengthDelimited!==!1&&b.ldelim()},(m,b,w={})=>{let x={},v=b==null?m.len:m.pos+b;for(;m.pos<v;){let A=m.uint32();switch(A>>>3){case 1:{x.status=r.ResponseStatus.codec().decode(m);break}case 2:{x.statusText=m.string();break}case 3:{x.addr=m.bytes();break}default:{m.skipType(A&7);break}}}return x},function*(m,b,w,x={}){let v=b==null?m.len:m.pos+b;for(;m.pos<v;){let A=m.uint32();switch(A>>>3){case 1:{yield{field:`${w}.status`,value:r.ResponseStatus.codec().decode(m)};break}case 2:{yield{field:`${w}.statusText`,value:m.string()};break}case 3:{yield{field:`${w}.addr`,value:m.bytes()};break}default:{m.skipType(A&7);break}}}})),h);function p(m){return te(m,f.codec())}f.encode=p;function y(m,b){return ee(m,f.codec(),b)}f.decode=y;function g(m,b){return re(m,f.codec(),b)}f.stream=g})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=ne((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.type!=null&&(h.uint32(8),r.MessageType.codec().encode(f.type,h)),f.dial!=null&&(h.uint32(18),r.Dial.codec().encode(f.dial,h)),f.dialResponse!=null&&(h.uint32(26),r.DialResponse.codec().encode(f.dialResponse,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={},g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{y.type=r.MessageType.codec().decode(f);break}case 2:{y.dial=r.Dial.codec().decode(f,f.uint32(),{limits:p.limits?.dial});break}case 3:{y.dialResponse=r.DialResponse.codec().decode(f,f.uint32(),{limits:p.limits?.dialResponse});break}default:{f.skipType(m&7);break}}}return y},function*(f,h,p,y={}){let g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.type`,value:r.MessageType.codec().decode(f)};break}case 2:{yield*r.Dial.codec().stream(f,f.uint32(),`${p}.dial`,{limits:y.limits?.dial});break}case 3:{yield*r.DialResponse.codec().stream(f,f.uint32(),`${p}.dialResponse`,{limits:y.limits?.dialResponse});break}default:{f.skipType(m&7);break}}}})),c);function l(f){return te(f,r.codec())}r.encode=l;function u(f,h){return ee(f,r.codec(),h)}r.decode=u;function d(f,h){return re(f,r.codec(),h)}r.stream=d})(Me||(Me={}));var gN=4,yN=8,E0=class{components;protocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;started;log;topologyId;dialResults;findPeers;addressFilter;connectionThreshold;constructor(e,t){this.components=e,this.log=e.logger.forComponent("libp2p:auto-nat"),this.started=!1,this.protocol=`/${t.protocolPrefix??mE}/${gE}/${yE}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??20,this.connectionThreshold=t.connectionThreshold??80,this.maxMessageSize=t.maxMessageSize??8192,this.dialResults=ft({name:"libp2p_autonat_dial_results",metrics:e.metrics}),this.findPeers=ia(this.findRandomPeers.bind(this),6e4),this.addressFilter=Wt(1024)}[Symbol.toStringTag]="@libp2p/autonat";[ue]=["@libp2p/autonat"];get[rr](){return["@libp2p/identify"]}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,(e,t)=>{this.handleIncomingAutonatStream(e,t).catch(n=>{this.log.error("error handling incoming autonat stream - %e",n)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.topologyId=await this.components.registrar.register(this.protocol,{onConnect:(e,t)=>{this.verifyExternalAddresses(t).catch(n=>{this.log.error("could not verify addresses - %e",n)})}}),this.findPeers.start(),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.topologyId!=null&&await this.components.registrar.unhandle(this.topologyId),this.dialResults.clear(),this.findPeers.stop(),this.started=!1}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every(e=>e.expires>Date.now()?!0:e.verified)}async findRandomPeers(e){if(this.allAddressesAreVerified())return;let t=me([AbortSignal.timeout(1e4),e?.signal]);try{this.log("starting random walk to find peers to run AutoNAT");for await(let n of this.components.randomWalk.walk({signal:t})){if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable %s",n.id,n.multiaddrs.map(o=>o.toString()).join(", "));continue}try{this.log.trace("dial random peer %p",n.id),await this.components.connectionManager.openConnection(n.multiaddrs,{signal:t})}catch{}if(this.allAddressesAreVerified()){this.log("stopping random walk, all addresses are verified");return}if(!this.hasConnectionCapacity()){this.log("stopping random walk, too close to max connections");return}}}catch{}}async handleIncomingAutonatStream(e,t){let n=AbortSignal.timeout(this.timeout);try{let o=ke(e,{maxDataLength:this.maxMessageSize}).pb(Me),s=await o.read({signal:n}),i=await this.handleAutonatMessage(s,t,{signal:n});await o.write(i,{signal:n}),await e.close({signal:n})}catch(o){this.log.error("error handling incoming autonat stream - %e",o),e.abort(o)}}async handleAutonatMessage(e,t,n){let o=this.components.addressManager.getAddresses().map(d=>Y(d).host),s=e.dial;if(s==null)return this.log.error("dial was missing from message"),{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}};let i,a=s.peer;if(a?.id==null)return this.log.error("peerId missing from message"),{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}};try{let d=ve(a.id);i=Xe(d)}catch(d){return this.log.error("invalid PeerId - %e",d),{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}}}if(this.log("incoming request from %p",i),!t.remotePeer.equals(i))return this.log("target peer %p did not equal sending peer %p",i,t.remotePeer),{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}};let c=a.addrs.map(d=>V(d)).filter(d=>{try{let f=Y(d);return Ze(d)?!1:f.host!==Y(t.remoteAddr).host?(this.log.trace("not dialing %a - target host did not match remote host %a",d,t.remoteAddr),!1):o.includes(f.host)?!1:this.components.transportManager.dialTransportForMultiaddr(d)==null?(this.log.trace("not dialing %a - transport unsupported",d),!1):!0}catch{return!1}}).map(d=>(d.getComponents().find(f=>f.code===421)?.value==null&&(d=d.encapsulate(`/p2p/${i.toString()}`)),d));if(c.length===0)return this.log("refused to dial all multiaddrs for %p from message",i),{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}};this.log("dial multiaddrs %s for peer %p",c.map(d=>d.toString()).join(", "),i);let l="",u=c[0];for(let d of c){let f;u=d;try{if(f=await this.components.connectionManager.openConnection(d,n),!f.remoteAddr.equals(d))throw this.log.error("tried to dial %a but dialed %a",d,f.remoteAddr),new Error("Unexpected remote address");return this.log("successfully dialed %p via %a",i,d),{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.OK,addr:f.remoteAddr.decapsulateCode(421).bytes}}}catch(h){this.log.error("could not dial %p - %e",i,h),l=h.message}finally{f!=null&&await f.close()}}return{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.E_DIAL_ERROR,statusText:l,addr:u.bytes}}}getFirstUnverifiedMultiaddr(e,t){let n=this.components.addressManager.getAddressesWithMetadata().sort((o,s)=>o.type==="observed"&&s.type!=="observed"?1:s.type==="observed"&&o.type!=="observed"?-1:0).filter(o=>!(!(o.expires<Date.now())||Y(o.multiaddr).type==="ip6"&&(!t||!sf(o.multiaddr))||Ze(o.multiaddr)));for(let o of n){let s=o.multiaddr.toString(),i=this.dialResults.get(s);if(i!=null){if(i.networkSegments.includes(e)){this.log.trace("%a already has a network segment result from %s",i.multiaddr,e);continue}if(i.queue.size>10){this.log.trace("%a already has enough peers queued",i.multiaddr);continue}}if(i==null){let a=o.expires<Date.now();if(a&&this.addressFilter.remove?.(s),this.addressFilter.has(s))continue;this.addressFilter.add(s),this.log.trace("creating dial result %s %s",a?"to revalidate":"for",s),i={multiaddr:o.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:Vm(),queue:new Yt({concurrency:3,maxSize:50}),type:o.type,lastVerified:o.lastVerified},this.dialResults.set(s,i)}return i}}removeOutdatedMultiaddrResults(){let e=new Set(this.components.addressManager.getAddressesWithMetadata().filter(({expires:t})=>t<Date.now()).map(({multiaddr:t})=>t.toString()));for(let t of this.dialResults.keys())e.has(t)||(this.log.trace("remove results for %a",t),this.dialResults.delete(t))}async verifyExternalAddresses(e){if(!this.isStarted())return;this.removeOutdatedMultiaddrResults();let n=(await this.components.peerStore.get(e.remotePeer)).addresses.some(({multiaddr:i})=>Y(i).type==="ip6"),o=this.getNetworkSegment(e.remoteAddr),s=this.getFirstUnverifiedMultiaddr(o,n);if(s==null){this.log.trace("no unverified public addresses found for peer %p to verify, not requesting verification",e.remotePeer);return}if(!this.hasConnectionCapacity()){s.lastVerified!=null?(this.log("automatically re-verifying %a because we are too close to the connection limit",s.multiaddr),this.confirmAddress(s)):this.log("skipping verifying %a because we are too close to the connection limit",s.multiaddr);return}s.queue.add(async i=>{await this.askPeerToVerify(e,o,i)},{peerId:e.remotePeer,multiaddr:s.multiaddr}).catch(i=>{s?.result==null&&this.log.error("error from %p verifying address %a - %e",e.remotePeer,s?.multiaddr,i)})}async askPeerToVerify(e,t,n){let o=this.dialResults.get(n.multiaddr.toString());if(o==null){this.log("%a was verified while %p was queued",n.multiaddr,e.remotePeer);return}let s=AbortSignal.timeout(this.timeout);this.log.trace("asking %a to verify multiaddr %s",e.remoteAddr,n.multiaddr);let i=await e.newStream(this.protocol,{signal:s});try{let a=ke(i).pb(Me),[,c]=await Promise.all([a.write({type:Me.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toMultihash().bytes,addrs:[n.multiaddr.bytes]}}},{signal:s}),a.read({signal:s})]);if(c.type!==Me.MessageType.DIAL_RESPONSE||c.dialResponse==null){this.log("invalid autonat response from %p - %j",e.remotePeer,c);return}let l=c.dialResponse.status;if(this.log.trace("autonat response from %p for %a is %s",e.remotePeer,n.multiaddr,l),l!==Me.ResponseStatus.OK&&l!==Me.ResponseStatus.E_DIAL_ERROR)return;if(o=this.dialResults.get(n.multiaddr.toString()),o==null){this.log.trace("peer reported %a as %s but there is no result object",n.multiaddr,c.dialResponse.status);return}if(o.networkSegments.includes(t)){this.log.trace("%a results included network segment %s",n.multiaddr,t);return}if(o.result!=null){this.log.trace("already resolved result for %a, ignoring response from",n.multiaddr,e.remotePeer);return}if(o.verifyingPeers.has(e.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",e.remotePeer,n.multiaddr);return}if(o.verifyingPeers.add(e.remotePeer),o.networkSegments.push(t),l===Me.ResponseStatus.OK){if(o.success++,o.type!=="observed"){this.confirmAddress(o);return}}else l===Me.ResponseStatus.E_DIAL_ERROR&&o.failure++;this.log("%a success %d failure %d",o.multiaddr,o.success,o.failure),o.success===gN&&this.confirmAddress(o),o.failure===yN&&this.unconfirmAddress(o)}finally{try{await i.close({signal:s})}catch(a){i.abort(a)}}}hasConnectionCapacity(){let t=this.components.connectionManager.getConnections().length,n=this.components.connectionManager.getMaxConnections();return t/n*100<this.connectionThreshold}confirmAddress(e){this.log("%s address %a is externally dialable",e.type,e.multiaddr),this.components.addressManager.confirmObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!0,e.queue.abort()}unconfirmAddress(e){this.log("%s address %a is not externally dialable",e.type,e.multiaddr),this.components.addressManager.removeObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!1,e.queue.abort()}getNetworkSegment(e){let t=Y(e);switch(t.type){case"ip4":return t.host.split(".")[0].padStart(3,"0");case"ip6":return t.host.split(":")[0].padStart(4,"0");default:throw new C(`Remote address ${e} was not an IPv4 or Ipv6 address`)}}};function bE(r={}){return e=>new E0(e,r)}var bN="bootstrap",wN=50,xN=1e3,Ng=class extends se{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??xN,this.list=t.list.map(n=>V(n)).filter(n=>ta.matches(n)?n.getComponents().findLast(s=>s.code===421)?.value==null?(this.log.error("invalid bootstrap multiaddr without peer id"),!1):!0:(this.log.error("invalid multiaddr %a",n),!1)).map(n=>({id:Oe(n.getComponents().findLast(o=>o.code===421)?.value??""),multiaddrs:[n]})),this._init=t}[us]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[ue]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??bN]:{value:this._init.tagValue??wN,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function wE(r){return e=>new Ng(e,r)}var Og=1e3,xE=60*Og;var Zue=120*xE,EE=1,v0=5e3,vE=100;var bu=`${fs}-circuit-relay`,Jue=2*xE,ede=BigInt(1<<17),ui="/libp2p/circuit/relay/0.2.0/hop",Mg="/libp2p/circuit/relay/0.2.0/stop",tde=30*Og,rde=30*Og,Bg=300,SE=4096,AE=.001;var Ko;(function(r){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(t||(t={})),(function(a){a.codec=()=>rt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ne((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),$o.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),wu.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),Vo.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),at.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=$o.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.reservation=wu.codec().decode(a,a.uint32(),{limits:l.limits?.reservation});break}case 4:{u.limit=Vo.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 5:{u.status=at.codec().decode(a);break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*$o.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*wu.codec().stream(a,a.uint32(),`${l}.reservation`,{limits:u.limits?.reservation});break}case 4:{yield*Vo.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 5:{yield{field:`${l}.status`,value:at.codec().decode(a)};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return te(a,r.codec())}r.encode=o;function s(a,c){return ee(a,r.codec(),c)}r.decode=s;function i(a,c){return re(a,r.codec(),c)}r.stream=i})(Ko||(Ko={}));var bn;(function(r){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(t||(t={})),(function(a){a.codec=()=>rt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ne((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),$o.codec().encode(a.peer,c)),a.limit!=null&&(c.uint32(26),Vo.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(32),at.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=$o.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.limit=Vo.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 4:{u.status=at.codec().decode(a);break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*$o.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*Vo.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 4:{yield{field:`${l}.status`,value:at.codec().decode(a)};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return te(a,r.codec())}r.encode=o;function s(a,c){return ee(a,r.codec(),c)}r.decode=s;function i(a,c){return re(a,r.codec(),c)}r.stream=i})(bn||(bn={}));var $o;(function(r){let e;r.codec=()=>(e==null&&(e=ne((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.id!=null&&s.id.byteLength>0&&(i.uint32(10),i.bytes(s.id)),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(18),i.bytes(c);a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={id:de(0),addrs:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.id=s.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new fe('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={addrs:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{yield{field:`${a}.id`,value:s.bytes()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new fe('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:s.bytes()},l.addrs++;break}default:{s.skipType(d&7);break}}}})),e);function t(s){return te(s,r.codec())}r.encode=t;function n(s,i){return ee(s,r.codec(),i)}r.decode=n;function o(s,i){return re(s,r.codec(),i)}r.stream=o})($o||($o={}));var wu;(function(r){let e;r.codec=()=>(e==null&&(e=ne((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.expire!=null&&s.expire!==0n&&(i.uint32(8),i.uint64(s.expire)),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(18),i.bytes(c);s.voucher!=null&&(i.uint32(26),Eu.codec().encode(s.voucher,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={expire:0n,addrs:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.expire=s.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new fe('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}case 3:{c.voucher=Eu.codec().decode(s,s.uint32(),{limits:a.limits?.voucher});break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={addrs:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{yield{field:`${a}.expire`,value:s.uint64()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new fe('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:s.bytes()},l.addrs++;break}case 3:{yield*Eu.codec().stream(s,s.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{s.skipType(d&7);break}}}})),e);function t(s){return te(s,r.codec())}r.encode=t;function n(s,i){return ee(s,r.codec(),i)}r.decode=n;function o(s,i){return re(s,r.codec(),i)}r.stream=o})(wu||(wu={}));var Vo;(function(r){let e;r.codec=()=>(e==null&&(e=ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.duration!=null&&(i.uint32(8),i.uint32(s.duration)),s.data!=null&&(i.uint32(16),i.uint64(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.duration=s.uint32();break}case 2:{c.data=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.duration`,value:s.uint32()};break}case 2:{yield{field:`${a}.data`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return te(s,r.codec())}r.encode=t;function n(s,i){return ee(s,r.codec(),i)}r.decode=n;function o(s,i){return re(s,r.codec(),i)}r.stream=o})(Vo||(Vo={}));var at;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(at||(at={}));var Ug;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Ug||(Ug={}));(function(r){r.codec=()=>rt(Ug)})(at||(at={}));var xu;(function(r){let e;r.codec=()=>(e==null&&(e=ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.relay!=null&&s.relay.byteLength>0&&(i.uint32(10),i.bytes(s.relay)),s.peer!=null&&s.peer.byteLength>0&&(i.uint32(18),i.bytes(s.peer)),s.expiration!=null&&s.expiration!==0n&&(i.uint32(24),i.uint64(s.expiration)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={relay:de(0),peer:de(0),expiration:0n},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.relay=s.bytes();break}case 2:{c.peer=s.bytes();break}case 3:{c.expiration=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.relay`,value:s.bytes()};break}case 2:{yield{field:`${a}.peer`,value:s.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return te(s,r.codec())}r.encode=t;function n(s,i){return ee(s,r.codec(),i)}r.decode=n;function o(s,i){return re(s,r.codec(),i)}r.stream=o})(xu||(xu={}));var Eu;(function(r){let e;r.codec=()=>(e==null&&(e=ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&(i.uint32(26),xu.codec().encode(s.payload,i)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:de(0),payloadType:de(0),signature:de(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=xu.codec().decode(s,s.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield*xu.codec().stream(s,s.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return te(s,r.codec())}r.encode=t;function n(s,i){return ee(s,r.codec(),i)}r.decode=n;function o(s,i){return re(s,r.codec(),i)}r.stream=o})(Eu||(Eu={}));var vu=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},S0=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},A0=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function Fg(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var Su=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},C0=Ce(pe(ta.matchers[0],Ae(290))),I0=Ce(Ae(290));var T0=class extends se{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(ui,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(ui)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let s=CE(n),i=CE(o);return s>i?-1:i>s?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Yt({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p - %e",n.id,o)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,o)})}async dialPeer({peerId:e,signal:t}){let n=me([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function CE(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(B(e)).getTime()}var $g=class extends se{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??v0,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(I0.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(C0.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let s=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(s)}}else throw new ls(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>V(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function IE(r){return new $g(r)}var TE="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var _E=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=TE[t[r]&63];return e};var EN=60*1e3*10,vN=60*1e3*5,SN=30*1e3,_0=class extends se{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Tt,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??vE,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??v0,this.started=!1,this.relayFilter=Wt(100),this.reserveQueue=new Yt({concurrency:t?.reservationConcurrency??EE,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(s=>s.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(s=>{this.log("could not remove relay %p - %e",n.detail,s)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(bu)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[bu]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=_E();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new ls("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new A0("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new ls("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let o=Date.now();try{let s=this.reservations.get(e);if(s!=null){let p=this.connectionManager.getConnections(e),y=!1;if(p.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),p.map(g=>g.id).includes(s.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),y=!0),y&&Fg(s.reservation.expire)>EN)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:s};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new vu("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(e,{signal:i});if(dt.matches(a.remoteAddr))throw new S0("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=Fg(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-vN,SN),Math.pow(2,31)-1),d=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async p=>{this.log.error("could not refresh reservation to relay %p - %e",e,p),await this.#t(e)}).catch(p=>{this.log.error("could not remove expired reservation to relay %p - %e",e,p)})},u),f;if(t==="discovered"){let p=this.pendingReservations.pop();if(p==null)throw new vu("Made reservation on relay but did not need any more discovered relays");f={timeout:d,reservation:c,type:t,connection:a.id,id:p}}else f={timeout:d,reservation:c,type:t,connection:a.id};this.reservations.set(e,f),await this.peerStore.merge(e,{tags:{[bu]:{value:1,ttl:l}}}),this.#r();let h={relay:e,details:f};return this.safeDispatchEvent("relay:created-reservation",{detail:h}),h}catch(s){throw t==="discovered"&&s.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-o,s),(s.name==="DialError"||s.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),s}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(ui,t),s=ke(n).pb(Ko);this.log.trace("send RESERVE to %p",e.remotePeer),await s.write({type:Ko.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await s.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===at.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of i.reservation.addrs){let u=V(l);u.getComponents().find(d=>d.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=V(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return i.reservation.addrs=[...c].map(l=>V(l).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[bu]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=Wt(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var Vg=class extends _o{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function Kg(r){return new Vg(r)}var AN=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(V)}catch{return!1}return!0},RE={maxInboundStopStreams:Bg,maxOutboundStopStreams:Bg,stopTimeout:3e4},R0=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??RE.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??RE.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new T0(e,{filter:t.discoveryFilter??O3(SE,AE)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,o)})}),this.reservationStore=new _0(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[ue]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[rr](){return this.discovery!=null?["@libp2p/identify"]:[]}[fo]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(Mg,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await Tr(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Zr(this.discovery,this.reservationStore),await this.components.registrar.unhandle(Mg),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),o=V(n[0]),s=V(n[n.length-1]),i=o.getComponents().find(h=>h.code===421)?.value,a=s.getComponents().find(h=>h.code===421)?.value;if(i==null||a==null){let h=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${h}`),new lo(`C${h}`)}let c=Oe(i),l=Oe(a),d=this.components.connectionManager.getConnections(c)[0];d==null?(await this.components.peerStore.merge(c,{multiaddrs:[o]}),t.onProgress?.(new X("circuit-relay:open-connection")),d=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new X("circuit-relay:reuse-connection"));let f;try{t.onProgress?.(new X("circuit-relay:open-hop-stream")),f=await d.newStream(ui,t);let h=ke(f).pb(Ko);t.onProgress?.(new X("circuit-relay:write-connect-message")),await h.write({type:Ko.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[V(s).bytes]}},t),t.onProgress?.(new X("circuit-relay:read-connect-response"));let p=await h.read(t);if(p.status!==at.OK)throw new oe(`failed to connect via relay with status ${p?.status?.toString()??"undefined"}`);let y=new Su(p.limit),g=Kg({stream:h.unwrap().unwrap(),remoteAddr:e,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:y.onData,onDataWrite:y.onData,log:f.log.newScope("circuit-relay:connection")}),m=await this.components.upgrader.upgradeOutbound(g,{...t,limits:y.getLimits()});return m.log("outbound relayed connection established to %p with limits %o, over connection %s",m.remotePeer,p.limit??"none",d.id),m}catch(h){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,h),f?.abort(h),h}}createListener(e){return IE({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>C0.exactMatch(t)||I0.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>dt.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(d){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",d)}let o=ke(e).pb(bn),s=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,s.type),s?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:bn.Type.STATUS,status:at.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(s.type!==bn.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:bn.Type.STATUS,status:at.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!AN(s)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:bn.Type.STATUS,status:at.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=Xe(ve(s.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:bn.Type.STATUS,status:at.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:bn.Type.STATUS,status:at.OK},{signal:n});let a=new Su(s.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.components.addressManager.getAddresses()[0],u=Kg({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,s.limit??"none",t.id)}finally{n?.clear()}}};function LE(r={}){return e=>new R0(e,r)}var zr;(function(r){let e;(function(a){a.UNUSED="UNUSED",a.CONNECT="CONNECT",a.SYNC="SYNC"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.UNUSED=0]="UNUSED",a[a.CONNECT=100]="CONNECT",a[a.SYNC=300]="SYNC"})(t||(t={})),(function(a){a.codec=()=>rt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ne((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.observedAddresses!=null&&a.observedAddresses.length>0)for(let u of a.observedAddresses)c.uint32(18),c.bytes(u);l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={observedAddresses:[]},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{if(l.limits?.observedAddresses!=null&&u.observedAddresses.length===l.limits.observedAddresses)throw new fe('Decode error - repeated field "observedAddresses" had too many elements');u.observedAddresses.push(a.bytes());break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={observedAddresses:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{if(u.limits?.observedAddresses!=null&&d.observedAddresses===u.limits.observedAddresses)throw new fe('Streaming decode error - repeated field "observedAddresses" had too many elements');yield{field:`${l}.observedAddresses[]`,index:d.observedAddresses,value:a.bytes()},d.observedAddresses++;break}default:{a.skipType(h&7);break}}}})),n);function o(a){return te(a,r.codec())}r.encode=o;function s(a,c){return ee(a,r.codec(),c)}r.decode=s;function i(a,c){return re(a,r.codec(),c)}r.stream=i})(zr||(zr={}));function qg(r,e){return dt.matches(r)||e.dialTransportForMultiaddr(r)==null?!1:x9.matches(r)?!0:A9.matches(r)?!Ze(r):!1}var PE=1024*4,DE=100,L0={timeout:5e3,retries:3,maxInboundStreams:1,maxOutboundStreams:1},P0=class{started;timeout;retries;maxInboundStreams;maxOutboundStreams;peerStore;registrar;connectionManager;addressManager;transportManager;topologyId;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:dcutr"),this.started=!1,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.timeout=t.timeout??L0.timeout,this.retries=t.retries??L0.retries,this.maxInboundStreams=t.maxInboundStreams??L0.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??L0.maxOutboundStreams,this.handleIncomingUpgrade=this.handleIncomingUpgrade.bind(this)}[Symbol.toStringTag]="@libp2p/dcutr";[rr]=["@libp2p/identify"];isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.registrar.register(Au,{notifyOnLimitedConnection:!0,onConnect:(e,t)=>{dt.exactMatch(t.remoteAddr)&&t.direction==="inbound"&&this.upgradeInbound(t).catch(n=>{this.log.error("error during outgoing DCUtR attempt - %e",n)})}}),await this.registrar.handle(Au,this.handleIncomingUpgrade,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){await this.registrar.unhandle(Au),this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async upgradeInbound(e){if(await this.attemptUnilateralConnectionUpgrade(e))return;let t;for(let n=0;n<this.retries;n++){let o={signal:AbortSignal.timeout(this.timeout)};try{t=await e.newStream([Au],{signal:o.signal,runOnLimitedConnection:!0});let s=ke(t,{maxDataLength:PE}).pb(zr);this.log("B sending connect to %p",e.remotePeer);let i=Date.now();await s.write({type:zr.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(d=>d.bytes)},o),this.log("B receiving connect from %p",e.remotePeer);let a=await s.read(o);if(a.type!==zr.Type.CONNECT)throw this.log("A sent wrong message type"),new oe("DCUtR message type was incorrect");let c=this.getDialableMultiaddrs(a.observedAddresses);if(c.length===0)throw this.log("A did not have any dialable multiaddrs"),new oe("DCUtR connect message had no multiaddrs");let l=Date.now()-i;this.log("A sending sync, rtt %dms",l),await s.write({type:zr.Type.SYNC,observedAddresses:[]},o),this.log("A waiting for half RTT"),await K9(l/2),this.log("B dialing",c);let u=await this.connectionManager.openConnection(c,{signal:o.signal,priority:DE,force:!0,initiator:!1});this.log("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,u.remoteAddr),await e.close(o);break}catch(s){if(this.log.error("error while attempting DCUtR on attempt %d of %d - %e",n+1,this.retries,s),t?.abort(s),n===this.retries)throw s}finally{t!=null&&await t.close(o)}}}async attemptUnilateralConnectionUpgrade(e){let n=(await this.peerStore.get(e.remotePeer)).addresses.map(o=>{let s=o.multiaddr;return s.getComponents().find(i=>i.code===421)?.value==null?s.encapsulate(`/p2p/${e.remotePeer}`):s}).filter(o=>qg(o,this.transportManager));if(n.length>0){let o=AbortSignal.timeout(this.timeout);try{this.log("attempting unilateral connection upgrade to %a",n);let s=await this.connectionManager.openConnection(n,{signal:o,force:!0});if(dt.exactMatch(s.remoteAddr))throw new Error("Could not open a new, non-limited, connection");return this.log("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,s.remoteAddr),await e.close({signal:o}),!0}catch(s){this.log.error("unilateral connection upgrade to %p on addresses %a failed - %e",e.remotePeer,n,s)}}else this.log("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}async handleIncomingUpgrade(e,t){let n={signal:AbortSignal.timeout(this.timeout)},o=ke(e,{maxDataLength:PE}).pb(zr);this.log("A receiving connect");let s=await o.read(n);if(s.type!==zr.Type.CONNECT)throw this.log("B sent wrong message type"),new oe("DCUtR message type was incorrect");if(s.observedAddresses.length===0)throw this.log("B sent no multiaddrs"),new oe("DCUtR connect message had no multiaddrs");let i=this.getDialableMultiaddrs(s.observedAddresses);if(i.length===0)throw this.log("B had no dialable multiaddrs in %o",s.observedAddresses.map(l=>V(l))),new oe("DCUtR connect message had no dialable multiaddrs");if(this.log("A sending connect"),await o.write({type:zr.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(l=>l.bytes)}),this.log("A receiving sync"),(await o.read(n)).type!==zr.Type.SYNC)throw new oe("DCUtR message type was incorrect");this.log("A dialing",i);let c=await this.connectionManager.openConnection(i,{signal:n.signal,priority:DE,force:!0});this.log("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,c.remoteAddr),await t.close(n),await e.close(n)}getDialableMultiaddrs(e){let t=[];for(let n of e)if(!(n==null||n.length===0))try{let o=V(n);if(!qg(o,this.transportManager))continue;t.push(o)}catch{}return t}};var Au="/libp2p/dcutr";function kE(r={}){return e=>new P0(e,r)}var jg={};$(jg,{base10:()=>PN});var Cfe=new Uint8Array(0);function NE(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function no(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function OE(r){return new TextEncoder().encode(r)}function ME(r){return new TextDecoder().decode(r)}function CN(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,g=0,m=0,b=p.length;m!==b&&p[m]===0;)m++,y++;for(var w=(b-m)*u+1>>>0,x=new Uint8Array(w);m!==b;){for(var v=p[m],A=0,S=w-1;(v!==0||A<g)&&S!==-1;S--,A++)v+=256*x[S]>>>0,x[S]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=A,m++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var k=c.repeat(y);I<w;++I)k+=r.charAt(x[I]);return k}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var g=0,m=0;p[y]===c;)g++,y++;for(var b=(p.length-y)*l+1>>>0,w=new Uint8Array(b);p[y];){var x=t[p.charCodeAt(y)];if(x===255)return;for(var v=0,A=b-1;(x!==0||v<m)&&A!==-1;A--,v++)x+=a*w[A]>>>0,w[A]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=v,y++}if(p[y]!==" "){for(var S=b-m;S!==b&&w[S]===0;)S++;for(var I=new Uint8Array(g+(b-S)),k=g;S!==b;)I[k++]=w[S++];return I}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var IN=CN,TN=IN,UE=TN;var Hg=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},zg=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return FE(this,e)}},Gg=class{decoders;constructor(e){this.decoders=e}or(e){return FE(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function FE(r,e){return new Gg({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Wg=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Hg(e,t,n),this.decoder=new zg(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ua({name:r,prefix:e,encode:t,decode:n}){return new Wg(r,e,t,n)}function qo({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=UE(t,r);return Ua({prefix:e,name:r,encode:n,decode:s=>no(o(s))})}function _N(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function RN(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function LN(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Ge({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=LN(n);return Ua({prefix:e,name:r,encode(s){return RN(s,n,t)},decode(s){return _N(s,o,t,r)}})}var PN=qo({prefix:"9",name:"base10",alphabet:"0123456789"});var Yg={};$(Yg,{base16:()=>DN,base16upper:()=>kN});var DN=Ge({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),kN=Ge({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Qg={};$(Qg,{base2:()=>NN});var NN=Ge({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Xg={};$(Xg,{base256emoji:()=>FN});var $E=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),ON=$E.reduce((r,e,t)=>(r[t]=e,r),[]),MN=$E.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function BN(r){return r.reduce((e,t)=>(e+=ON[t],e),"")}function UN(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=MN[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var FN=Ua({prefix:"\u{1F680}",name:"base256emoji",encode:BN,decode:UN});var Zg={};$(Zg,{base32:()=>Fa,base32hex:()=>qN,base32hexpad:()=>zN,base32hexpadupper:()=>GN,base32hexupper:()=>HN,base32pad:()=>VN,base32padupper:()=>KN,base32upper:()=>$N,base32z:()=>WN});var Fa=Ge({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$N=Ge({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),VN=Ge({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),KN=Ge({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),qN=Ge({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),HN=Ge({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),zN=Ge({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),GN=Ge({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),WN=Ge({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Jg={};$(Jg,{base36:()=>Cu,base36upper:()=>jN});var Cu=qo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),jN=qo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var e6={};$(e6,{base58btc:()=>wn,base58flickr:()=>YN});var wn=qo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),YN=qo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var t6={};$(t6,{base64:()=>QN,base64pad:()=>XN,base64url:()=>ZN,base64urlpad:()=>JN});var QN=Ge({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),XN=Ge({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ZN=Ge({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),JN=Ge({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var r6={};$(r6,{base8:()=>eO});var eO=Ge({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var n6={};$(n6,{identity:()=>tO});var tO=Ua({prefix:"\0",name:"identity",encode:r=>ME(r),decode:r=>OE(r)});var Vfe=new TextEncoder,Kfe=new TextDecoder;var s6={};$(s6,{identity:()=>AO});var oO=qE,VE=128,sO=127,iO=~sO,aO=Math.pow(2,31);function qE(r,e,t){e=e||[],t=t||0;for(var n=t;r>=aO;)e[t++]=r&255|VE,r/=128;for(;r&iO;)e[t++]=r&255|VE,r>>>=7;return e[t]=r|0,qE.bytes=t-n+1,e}var cO=o6,lO=128,KE=127;function o6(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw o6.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&KE)<<o:(i&KE)*Math.pow(2,o),o+=7}while(i>=lO);return o6.bytes=s-n,t}var uO=Math.pow(2,7),dO=Math.pow(2,14),fO=Math.pow(2,21),hO=Math.pow(2,28),pO=Math.pow(2,35),mO=Math.pow(2,42),gO=Math.pow(2,49),yO=Math.pow(2,56),bO=Math.pow(2,63),wO=function(r){return r<uO?1:r<dO?2:r<fO?3:r<hO?4:r<pO?5:r<mO?6:r<gO?7:r<yO?8:r<bO?9:10},xO={encode:oO,decode:cO,encodingLength:wO},EO=xO,Iu=EO;function Tu(r,e=0){return[Iu.decode(r,e),Iu.decode.bytes]}function $a(r,e,t=0){return Iu.encode(r,e,t),e}function Va(r){return Iu.encodingLength(r)}function qa(r,e){let t=e.byteLength,n=Va(r),o=n+Va(t),s=new Uint8Array(o+t);return $a(r,s,0),$a(t,s,n),s.set(e,o),new Ka(r,t,e,s)}function HE(r){let e=no(r),[t,n]=Tu(e),[o,s]=Tu(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ka(t,o,i,e)}function zE(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&NE(r.bytes,t.bytes)}}var Ka=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var GE=0,vO="identity",WE=no;function SO(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return qa(GE,WE(r))}var AO={code:GE,name:vO,encode:WE,digest:SO};var c6={};$(c6,{sha256:()=>IO,sha512:()=>TO});var CO=20;function a6({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new i6(r,e,t,n,o)}var i6=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??CO,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?jE(n,this.code,t?.truncate):n.then(o=>jE(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function jE(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return qa(e,r)}function QE(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var IO=a6({name:"sha2-256",code:18,encode:QE("SHA-256")}),TO=a6({name:"sha2-512",code:19,encode:QE("SHA-512")});function XE(r,e){let{bytes:t,version:n}=r;return n===0?RO(t,l6(r),e??wn.encoder):LO(t,l6(r),e??Fa.encoder)}var ZE=new WeakMap;function l6(r){let e=ZE.get(r);if(e==null){let t=new Map;return ZE.set(r,t),t}return e}var k0=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ru)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==PO)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=qa(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&zE(e.multihash,n.multihash)}toString(e){return XE(this,e)}toJSON(){return{"/":XE(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??JE(n,o,s.bytes))}else if(t[DO]===!0){let{version:n,multihash:o,code:s}=t,i=HE(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ru)throw new Error(`Version 0 CID must use dag-pb (code: ${Ru}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=JE(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ru,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=no(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Ka(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,f]=Tu(e.subarray(t));return t+=f,d},o=n(),s=Ru;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=_O(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return l6(s).set(n,e),s}};function _O(r,e){switch(r[0]){case"Q":{let t=e??wn;return[wn.prefix,t.decode(`${wn.prefix}${r}`)]}case wn.prefix:{let t=e??wn;return[wn.prefix,t.decode(r)]}case Fa.prefix:{let t=e??Fa;return[Fa.prefix,t.decode(r)]}case Cu.prefix:{let t=e??Cu;return[Cu.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function RO(r,e,t){let{prefix:n}=t;if(n!==wn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function LO(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Ru=112,PO=18;function JE(r,e,t){let n=Va(r),o=n+Va(e),s=new Uint8Array(o+t.byteLength);return $a(r,s,0),$a(e,s,n),s.set(t,o),s}var DO=Symbol.for("@ipld/js-cid/CID");var u6={...n6,...Qg,...r6,...jg,...Yg,...Zg,...Jg,...e6,...t6,...Xg},uhe={...c6,...s6};function ev(r=0){return new Uint8Array(r)}function rv(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var tv=rv("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),d6=rv("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ev(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),kO={utf8:tv,"utf-8":tv,hex:u6.base16,latin1:d6,ascii:d6,binary:d6,...u6},nv=kO;function f6(r,e="utf8"){let t=nv[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function H(r){if(r!==void 0&&r!==H.REQUEST&&r!==H.RESPONSE)throw new Error("type must be REQUEST or RESPONSE");r===void 0||this.initialize(r),this.maxHeaderSize=H.maxHeaderSize}H.prototype.initialize=function(r,e){if(r!==H.REQUEST&&r!==H.RESPONSE)throw new Error("type must be REQUEST or RESPONSE");this.type=r,this.state=r+"_LINE",this.info={headers:[],upgrade:!1},this.trailers=[],this.line="",this.isChunked=!1,this.connection="",this.headerSize=0,this.body_bytes=null,this.isUserCall=!1,this.hadError=!1};H.encoding="ascii";H.maxHeaderSize=80*1024;H.REQUEST="REQUEST";H.RESPONSE="RESPONSE";var ov=H.kOnHeaders=1,h6=H.kOnHeadersComplete=2,N0=H.kOnBody=3,p6=H.kOnMessageComplete=4;H.prototype[ov]=H.prototype[h6]=H.prototype[N0]=H.prototype[p6]=function(){};var sv=!0;Object.defineProperty(H,"kOnExecute",{get:function(){return sv=!1,99}});var iv=H.methods=["DELETE","GET","HEAD","POST","PUT","CONNECT","OPTIONS","TRACE","COPY","LOCK","MKCOL","MOVE","PROPFIND","PROPPATCH","SEARCH","UNLOCK","BIND","REBIND","UNBIND","ACL","REPORT","MKACTIVITY","CHECKOUT","MERGE","M-SEARCH","NOTIFY","SUBSCRIBE","UNSUBSCRIBE","PATCH","PURGE","MKCALENDAR","LINK","UNLINK","SOURCE"],av=iv.indexOf("CONNECT");H.prototype.reinitialize=H;H.prototype.close=H.prototype.pause=H.prototype.resume=H.prototype.remove=H.prototype.free=function(){};H.prototype._compatMode0_11=!1;H.prototype.getAsyncId=function(){return 0};var NO={REQUEST_LINE:!0,RESPONSE_LINE:!0,HEADER:!0};H.prototype.execute=function(r,e,t){if(!(this instanceof H))throw new TypeError("not a HTTPParser");e=e||0,t=typeof t=="number"?t:r.length,this.chunk=r,this.offset=e;var n=this.end=e+t;try{for(;this.offset<n&&!this[this.state](););}catch(o){if(this.isUserCall)throw o;return this.hadError=!0,o}return this.chunk=null,t=this.offset-e,NO[this.state]&&(this.headerSize+=t,this.headerSize>(this.maxHeaderSize||H.maxHeaderSize))?new Error("max header size exceeded"):t};var OO={REQUEST_LINE:!0,RESPONSE_LINE:!0,BODY_RAW:!0};H.prototype.finish=function(){if(!this.hadError){if(!OO[this.state])return new Error("invalid state for EOF");this.state==="BODY_RAW"&&this.userCall()(this[p6]())}};H.prototype.consume=H.prototype.unconsume=H.prototype.getCurrentBuffer=function(){};H.prototype.userCall=function(){this.isUserCall=!0;var r=this;return function(e){return r.isUserCall=!1,e}};H.prototype.nextRequest=function(){this.userCall()(this[p6]()),this.reinitialize(this.type)};H.prototype.consumeLine=function(){for(var r=this.end,e=this.chunk,t=this.offset;t<r;t++)if(e[t]===10){var n=this.line+f6(e.subarray(this.offset,t),H.encoding);return n.charAt(n.length-1)==="\r"&&(n=n.substr(0,n.length-1)),this.line="",this.offset=t+1,n}this.line+=f6(e.subarray(this.offset,this.end),H.encoding),this.offset=this.end};var MO=/^([^: \t]+):[ \t]*((?:.*[^ \t])|)/,BO=/^[ \t]+(.*[^ \t])/;H.prototype.parseHeader=function(r,e){if(r.indexOf("\r")!==-1)throw O0("HPE_LF_EXPECTED");var t=MO.exec(r),n=t&&t[1];if(n)e.push(n),e.push(t[2]);else{var o=BO.exec(r);o&&e.length&&(e[e.length-1]&&(e[e.length-1]+=" "),e[e.length-1]+=o[1])}};var UO=/^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/;H.prototype.REQUEST_LINE=function(){var r=this.consumeLine();if(r){var e=UO.exec(r);if(e===null)throw O0("HPE_INVALID_CONSTANT");if(this.info.method=this._compatMode0_11?e[1]:iv.indexOf(e[1]),this.info.method===-1)throw new Error("invalid request method");this.info.url=e[2],this.info.versionMajor=+e[3],this.info.versionMinor=+e[4],this.body_bytes=0,this.state="HEADER"}};var FO=/^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/;H.prototype.RESPONSE_LINE=function(){var r=this.consumeLine();if(r){var e=FO.exec(r);if(e===null)throw O0("HPE_INVALID_CONSTANT");this.info.versionMajor=+e[1],this.info.versionMinor=+e[2];var t=this.info.statusCode=+e[3];this.info.statusMessage=e[4],((t/100|0)===1||t===204||t===304)&&(this.body_bytes=0),this.state="HEADER"}};H.prototype.shouldKeepAlive=function(){if(this.info.versionMajor>0&&this.info.versionMinor>0){if(this.connection.indexOf("close")!==-1)return!1}else if(this.connection.indexOf("keep-alive")===-1)return!1;return!!(this.body_bytes!==null||this.isChunked)};H.prototype.HEADER=function(){var r=this.consumeLine();if(r!==void 0){var e=this.info;if(r)this.parseHeader(r,e.headers);else{for(var t=e.headers,n=!1,o,s=!1,i=0;i<t.length;i+=2)switch(t[i].toLowerCase()){case"transfer-encoding":this.isChunked=t[i+1].toLowerCase()==="chunked";break;case"content-length":if(o=+t[i+1],n){if(o!==this.body_bytes)throw O0("HPE_UNEXPECTED_CONTENT_LENGTH")}else n=!0,this.body_bytes=o;break;case"connection":this.connection+=t[i+1].toLowerCase();break;case"upgrade":s=!0;break}this.isChunked&&n&&(n=!1,this.body_bytes=null),s&&this.connection.indexOf("upgrade")!=-1?e.upgrade=this.type===H.REQUEST||e.statusCode===101:e.upgrade=e.method===av,this.isChunked&&e.upgrade&&(this.isChunked=!1),e.shouldKeepAlive=this.shouldKeepAlive();var a;if(sv?a=this.userCall()(this[h6](e)):a=this.userCall()(this[h6](e.versionMajor,e.versionMinor,e.headers,e.method,e.url,e.statusCode,e.statusMessage,e.upgrade,e.shouldKeepAlive)),a===2)return this.nextRequest(),!0;if(this.isChunked&&!a)this.state="BODY_CHUNKHEAD";else{if(a||this.body_bytes===0)return this.nextRequest(),e.upgrade;this.body_bytes===null?this.state="BODY_RAW":this.state="BODY_SIZED"}}}};H.prototype.BODY_CHUNKHEAD=function(){var r=this.consumeLine();r!==void 0&&(this.body_bytes=parseInt(r,16),this.body_bytes?this.state="BODY_CHUNK":this.state="BODY_CHUNKTRAILERS")};H.prototype.BODY_CHUNK=function(){var r=Math.min(this.end-this.offset,this.body_bytes);this.userCall()(this[N0](this.chunk.slice(this.offset,this.offset+r),0,r)),this.offset+=r,this.body_bytes-=r,this.body_bytes||(this.state="BODY_CHUNKEMPTYLINE")};H.prototype.BODY_CHUNKEMPTYLINE=function(){var r=this.consumeLine();if(r!==void 0){if(r!=="")throw new Error("Expected empty line");this.state="BODY_CHUNKHEAD"}};H.prototype.BODY_CHUNKTRAILERS=function(){var r=this.consumeLine();r!==void 0&&(r?this.parseHeader(r,this.trailers):(this.trailers.length&&this.userCall()(this[ov](this.trailers,"")),this.nextRequest()))};H.prototype.BODY_RAW=function(){this.userCall()(this[N0](this.chunk.slice(this.offset,this.end),0,this.end-this.offset)),this.offset=this.end};H.prototype.BODY_SIZED=function(){var r=Math.min(this.end-this.offset,this.body_bytes);this.userCall()(this[N0](this.chunk.slice(this.offset,this.offset+r),0,r)),this.offset+=r,this.body_bytes-=r,this.body_bytes||this.nextRequest()};["Headers","HeadersComplete","Body","MessageComplete"].forEach(function(r){var e=H["kOn"+r];Object.defineProperty(H.prototype,"on"+r,{get:function(){return this[e]},set:function(t){return this._compatMode0_11=!0,av="CONNECT",this[e]=t}})});function O0(r){var e=new Error("Parse Error");return e.code=r,e}var $O=[6,53,56,54,55];function cv(r){return dv("sni",r)?.value}function lv(r){let e=dv("tcp",r)?.value;return e==null?"":`:${e}`}function dv(r,e){return e.find(t=>t.name===r)}function uv(r){return r.some(({code:e})=>e===448)}function Gr(r,e){let t=fv[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var fv={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Gr(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Gr(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Gr(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Gr(t,e)}`},http:(r,e)=>{let t=uv(e),n=cv(e),o=lv(e);if(t&&n!=null)return`https://${n}${o}`;let s=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Gr(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Gr(t,e),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Gr(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Gr(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Gr(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=uv(e),n=cv(e),o=lv(e);if(t&&n!=null)return`wss://${n}${o}`;let s=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Gr(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Gr(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function M0(r,e){let n=V(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=fv[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return e?.assumeHttp!==!1&&$O.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var hv="[a-fA-F\\d:]",Ho=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${hv})|(?<=${hv})(?=\\s|$))`:"",Wr="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Je="[a-fA-F\\d]{1,4}",B0=`
|
|
31
|
+
`)}async function L4(r,e){try{let t=await bD(r,e);return ky(t)}catch{}if(!r.includes("BEGIN"))throw new C("Encrypted key was not a libp2p-key or a PEM file");return wD(r,e)}async function bD(r,e){let t=_n.decode(r);return ha.create().decrypt(t,e)}async function wD(r,e){let t=Qe.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let s=O(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=q1(s),{iv:a,salt:c,iterations:l,keySize:u,cipherText:d}=xD(i),f=await Jh(en,e,c,{c:l,dkLen:u}),h=await t.subtle.importKey("raw",ie(f),"AES-CBC",!1,["decrypt"]),p=Xl(await t.subtle.decrypt({name:"AES-CBC",iv:ie(a)},h,ie(d))),{result:y}=q1(p);n=qw(y)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let s=O(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=q1(s);n=qw(i)}else throw new C("Could not parse private key from PEM data");let o=Ny(n);if(o.type!=="RSA")throw new C("Could not parse RSA private key from PEM data");return o}function xD(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new C("Only pkcs5PBES2 encrypted private keys are supported");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new C("Only pkcs5PBKDF2 key derivation functions are supported");let s=n.valueBlock.value[1],i=Xl(s.valueBlock.value[0].getValue()),a=1e4,c=32;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new C("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key");let l=e.valueBlock.value[1].valueBlock.value[1],u=l.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new C("Only AES-CBC encryption schemes are supported")}}}}let d=Xl(l.valueBlock.value[1].getValue());return{cipherText:Xl(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:d}}function qw(r){return Xl(r.valueBlock.value[2].getValue())}function Xl(r){return new Uint8Array(r,0,r.byteLength)}var ED="/pkcs8/",P4="/info/",Zl=new WeakMap,ri={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3};function ga(r){return r==null||typeof r!="string"?!1:r===(0,Hw.default)(r.trim())&&r.length>0}async function Et(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function ni(r){return new Rt(ED+r)}function ya(r){return new Rt(P4+r)}async function vD(r){let e=Ns(r),t=await pt.digest(e);return Ee.encode(t.bytes).substring(1)}var z1=class{components;init;log;self;constructor(e,t){if(this.components=e,this.log=e.logger.forComponent("libp2p:keychain"),this.init={...t,dek:{...v4,...t.dek}},this.self=t.selfKey??"self",this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLength<ri.minKeyLength)throw new Error(`dek.keyLength must be least ${ri.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<ri.minSaltLength)throw new Error(`dek.saltLength must be least ${ri.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<ri.minIterationCount)throw new Error(`dek.iterationCount must be least ${ri.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?$l(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Zl.set(this,{dek:n})}[Symbol.toStringTag]="@libp2p/keychain";[ue]=["@libp2p/keychain"];static generateOptions(){let e=Object.assign({},this.options),t=Math.ceil(ri.minSaltLength/3)*3;return e.dek!=null&&(e.dek.salt=B(crypto.getRandomValues(new Uint8Array(t)),"base64")),e}static get options(){return{dek:{...v4}}}async findKeyByName(e){if(!ga(e))throw await Et(),new C(`Invalid key name '${e}'`);let t=ya(e);try{let n=await this.components.datastore.get(t);return JSON.parse(B(n))}catch(n){throw await Et(),this.log.error("could not read key from datastore - %e",n),new Pe(`Key '${e}' does not exist.`)}}async findKeyById(e){try{let t={prefix:P4};for await(let n of this.components.datastore.query(t)){let o=JSON.parse(B(n.value));if(o.id===e)return o}throw new C(`Key with id '${e}' does not exist.`)}catch(t){throw await Et(),t}}async importKey(e,t){if(!ga(e))throw await Et(),new C(`Invalid key name '${e}'`);if(t==null)throw await Et(),new C("Key is required");let n=ni(e);if(await this.components.datastore.has(n))throw await Et(),new C(`Key '${e}' already exists`);let s,i;try{s=await vD(t);let l=Zl.get(this);if(l==null)throw new C("dek missing");let u=l.dek;i=await R4(t,u,t.type==="RSA"?"pkcs-8":"libp2p-key")}catch(l){throw await Et(),l}let a={name:e,id:s},c=this.components.datastore.batch();return c.put(n,O(i)),c.put(ya(e),O(JSON.stringify(a))),await c.commit(),a}async exportKey(e){if(!ga(e))throw await Et(),new C(`Invalid key name '${e}'`);let t=ni(e);try{let n=await this.components.datastore.get(t),o=B(n),s=Zl.get(this);if(s==null)throw new C("dek missing");let i=s.dek;return await L4(o,i)}catch(n){throw await Et(),n}}async removeKey(e){if(!ga(e)||e===this.self)throw await Et(),new C(`Invalid key name '${e}'`);let t=ni(e),n=await this.findKeyByName(e),o=this.components.datastore.batch();return o.delete(t),o.delete(ya(e)),await o.commit(),n}async listKeys(){let e={prefix:P4},t=[];for await(let n of this.components.datastore.query(e))t.push(JSON.parse(B(n.value)));return t}async renameKey(e,t){if(!ga(e)||e===this.self)throw await Et(),new C(`Invalid old key name '${e}'`);if(!ga(t)||t===this.self)throw await Et(),new C(`Invalid new key name '${t}'`);let n=ni(e),o=ni(t),s=ya(e),i=ya(t);if(await this.components.datastore.has(o))throw await Et(),new C(`Key '${t}' already exists`);try{let c=await this.components.datastore.get(n),l=await this.components.datastore.get(s),u=JSON.parse(B(l));u.name=t;let d=this.components.datastore.batch();return d.put(o,c),d.put(i,O(JSON.stringify(u))),d.delete(n),d.delete(s),await d.commit(),u}catch(c){throw await Et(),c}}async rotateKeychainPass(e,t){if(typeof e!="string")throw await Et(),new C(`Invalid old pass type '${typeof e}'`);if(typeof t!="string")throw await Et(),new C(`Invalid new pass type '${typeof t}'`);if(t.length<20)throw await Et(),new C(`Invalid pass length ${t.length}`);this.log("recreating keychain");let n=Zl.get(this);if(n==null)throw new C("dek missing");let o=n.dek;this.init.pass=t;let s=t!=null&&this.init.dek?.salt!=null?$l(t,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Zl.set(this,{dek:s});let i=await this.listKeys();for(let a of i){let c=await this.components.datastore.get(ni(a.name)),l=B(c),u=await L4(l,o),d=s.toString(),f=await R4(u,d,u.type==="RSA"?"pkcs-8":"libp2p-key"),h=this.components.datastore.batch(),p={name:a.name,id:a.id};h.put(ni(a.name),O(f)),h.put(ya(a.name),O(JSON.stringify(p))),await h.commit()}this.log("keychain reconstructed")}};function zw(r={}){return e=>new z1(e,r)}async function D4(r,e={}){let t=e.selfKey??"self",n=zw(e)({datastore:r,logger:qi()}),o;return await r.has(new Rt(`/pkcs8/${t}`))?o=await n.exportKey(t):(o=await Xd(e.keyType??"Ed25519"),await n.importKey(t,o)),o}function ot(r=0){return new Uint8Array(r)}function Pt(r=0){return new Uint8Array(r)}var ba=!!globalThis.process?.env?.DUMP_SESSION_KEYS,k4=16;function SD(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function G1(r){if(typeof r!="boolean")throw new TypeError(`boolean expected, not ${r}`)}function wa(r){if(typeof r!="number")throw new TypeError("number expected, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError("positive integer expected, got "+r)}function st(r,e,t=""){let n=SD(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function N4(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Gw(r,e,t=!1){st(r,void 0,"output");let n=e.outputLen;if(r.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(t&&!xa(r))throw new Error("invalid output, must be aligned")}function hn(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function qr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function AD(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var oi=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,CD=r=>r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255;var ID=r=>{for(let e=0;e<r.length;e++)r[e]=CD(r[e]);return r},Jn=oi?r=>r:ID;function Ww(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function jw(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Yw(r,e,t){let n=e,o=t||(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(r),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}var Qw=(r,e)=>{function t(n,...o){if(st(n,void 0,"key"),r.nonceLength!==void 0){let u=o[0];st(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let s=r.tagLength;s&&o[1]!==void 0&&st(o[1],void 0,"AAD");let i=e(n,...o),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");st(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,st(u),a(i.encrypt.length,d),i.encrypt(u,d)},decrypt(u,d){if(st(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,d),i.decrypt(u,d)}}}return Object.assign(t,r),t};function Jl(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(st(e,void 0,"output"),e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!xa(e))throw new Error("invalid output, must be aligned");return e}function Xw(r,e,t){wa(r),wa(e),G1(t);let n=new Uint8Array(16),o=AD(n);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(r),t),n}function xa(r){return r.byteOffset%4===0}function Ea(r){return Uint8Array.from(st(r))}var Jw=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),TD=Jn(hn(Jw("expand 16-byte k"))),_D=Jn(hn(Jw("expand 32-byte k")));function ge(r,e){return r<<e|r>>>32-e}var eu=64,RD=16,O4=2**32-1,Zw=Uint32Array.of();function LD(r,e,t,n,o,s,i,a){let c=o.length,l=new Uint8Array(eu),u=hn(l),d=oi&&xa(o)&&xa(s),f=d?hn(o):Zw,h=d?hn(s):Zw;if(!oi){for(let p=0;p<c;i++){if(r(e,t,n,u,i,a),Jn(u),i>=O4)throw new Error("arx: counter overflow");let y=Math.min(eu,c-p);for(let g=0,m;g<y;g++)m=p+g,s[m]=o[m]^l[g];p+=y}return}for(let p=0;p<c;i++){if(r(e,t,n,u,i,a),i>=O4)throw new Error("arx: counter overflow");let y=Math.min(eu,c-p);if(d&&y===eu){let g=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let m=0,b;m<RD;m++)b=g+m,h[b]=f[b]^u[m];p+=eu;continue}for(let g=0,m;g<y;g++)m=p+g,s[m]=o[m]^l[g];p+=y}}function ex(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Ww({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return wa(o),wa(i),G1(s),G1(t),(a,c,l,u,d=0)=>{st(a,void 0,"key"),st(c,void 0,"nonce"),st(l,void 0,"data");let f=l.length;if(u=Jl(f,u,!1),wa(d),d<0||d>=O4)throw new Error("arx: counter overflow");let h=[],p=a.length,y,g;if(p===32)h.push(y=Ea(a)),g=_D;else if(p===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),g=TD,h.push(y);else throw st(a,32,"arx key"),new Error("invalid key size");(!oi||!xa(c))&&h.push(c=Ea(c));let m=hn(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let x=c.subarray(0,16);if(oi)n(g,m,hn(x),m);else{let v=Jn(Uint32Array.from(g));n(v,m,hn(x),m),qr(v),Jn(m)}c=c.subarray(16)}else oi||Jn(m);let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let x=new Uint8Array(12);x.set(c,s?0:12-c.length),c=x,h.push(c)}let w=Jn(hn(c));try{return LD(r,g,m,w,l,u,d,i),u}finally{qr(...h)}}}function vt(r,e){return r[e++]&255|(r[e++]&255)<<8}var M4=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Ea(st(e,32,"key"));let t=vt(e,0),n=vt(e,2),o=vt(e,4),s=vt(e,6),i=vt(e,8),a=vt(e,10),c=vt(e,12),l=vt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=vt(e,16+2*u)}process(e,t,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],d=i[4],f=i[5],h=i[6],p=i[7],y=i[8],g=i[9],m=vt(e,t+0),b=vt(e,t+2),w=vt(e,t+4),x=vt(e,t+6),v=vt(e,t+8),A=vt(e,t+10),S=vt(e,t+12),I=vt(e,t+14),k=s[0]+(m&8191),K=s[1]+((m>>>13|b<<3)&8191),F=s[2]+((b>>>10|w<<6)&8191),E=s[3]+((w>>>7|x<<9)&8191),P=s[4]+((x>>>4|v<<12)&8191),L=s[5]+(v>>>1&8191),_=s[6]+((v>>>14|A<<2)&8191),T=s[7]+((A>>>11|S<<5)&8191),D=s[8]+((S>>>8|I<<8)&8191),N=s[9]+(I>>>5|o),R=0,M=R+k*a+K*(5*g)+F*(5*y)+E*(5*p)+P*(5*h);R=M>>>13,M&=8191,M+=L*(5*f)+_*(5*d)+T*(5*u)+D*(5*l)+N*(5*c),R+=M>>>13,M&=8191;let U=R+k*c+K*a+F*(5*g)+E*(5*y)+P*(5*p);R=U>>>13,U&=8191,U+=L*(5*h)+_*(5*f)+T*(5*d)+D*(5*u)+N*(5*l),R+=U>>>13,U&=8191;let G=R+k*l+K*c+F*a+E*(5*g)+P*(5*y);R=G>>>13,G&=8191,G+=L*(5*p)+_*(5*h)+T*(5*f)+D*(5*d)+N*(5*u),R+=G>>>13,G&=8191;let J=R+k*u+K*l+F*c+E*a+P*(5*g);R=J>>>13,J&=8191,J+=L*(5*y)+_*(5*p)+T*(5*h)+D*(5*f)+N*(5*d),R+=J>>>13,J&=8191;let Q=R+k*d+K*u+F*l+E*c+P*a;R=Q>>>13,Q&=8191,Q+=L*(5*g)+_*(5*y)+T*(5*p)+D*(5*h)+N*(5*f),R+=Q>>>13,Q&=8191;let Ie=R+k*f+K*d+F*u+E*l+P*c;R=Ie>>>13,Ie&=8191,Ie+=L*a+_*(5*g)+T*(5*y)+D*(5*p)+N*(5*h),R+=Ie>>>13,Ie&=8191;let Te=R+k*h+K*f+F*d+E*u+P*l;R=Te>>>13,Te&=8191,Te+=L*c+_*a+T*(5*g)+D*(5*y)+N*(5*p),R+=Te>>>13,Te&=8191;let _e=R+k*p+K*h+F*f+E*d+P*u;R=_e>>>13,_e&=8191,_e+=L*l+_*c+T*a+D*(5*g)+N*(5*y),R+=_e>>>13,_e&=8191;let ye=R+k*y+K*p+F*h+E*f+P*d;R=ye>>>13,ye&=8191,ye+=L*u+_*l+T*c+D*a+N*(5*g),R+=ye>>>13,ye&=8191;let Be=R+k*g+K*y+F*p+E*h+P*f;R=Be>>>13,Be&=8191,Be+=L*d+_*u+T*l+D*c+N*a,R+=Be>>>13,Be&=8191,R=(R<<2)+R|0,R=R+M|0,M=R&8191,R=R>>>13,U+=R,s[0]=M,s[1]=U,s[2]=G,s[3]=J,s[4]=Q,s[5]=Ie,s[6]=Te,s[7]=_e,s[8]=ye,s[9]=Be}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;qr(n)}update(e){N4(this),st(e),e=Ea(e);let{buffer:t,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,qr(this.h,this.r,this.buffer,this.pad)}digestInto(e){N4(this),Gw(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},tx=Yw(32,r=>new M4(r));function PD(r,e,t,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],d=e[1],f=e[2],h=e[3],p=e[4],y=e[5],g=e[6],m=e[7],b=o,w=t[0],x=t[1],v=t[2],A=i,S=a,I=c,k=l,K=u,F=d,E=f,P=h,L=p,_=y,T=g,D=m,N=b,R=w,M=x,U=v;for(let J=0;J<s;J+=2)A=A+K|0,N=ge(N^A,16),L=L+N|0,K=ge(K^L,12),A=A+K|0,N=ge(N^A,8),L=L+N|0,K=ge(K^L,7),S=S+F|0,R=ge(R^S,16),_=_+R|0,F=ge(F^_,12),S=S+F|0,R=ge(R^S,8),_=_+R|0,F=ge(F^_,7),I=I+E|0,M=ge(M^I,16),T=T+M|0,E=ge(E^T,12),I=I+E|0,M=ge(M^I,8),T=T+M|0,E=ge(E^T,7),k=k+P|0,U=ge(U^k,16),D=D+U|0,P=ge(P^D,12),k=k+P|0,U=ge(U^k,8),D=D+U|0,P=ge(P^D,7),A=A+F|0,U=ge(U^A,16),T=T+U|0,F=ge(F^T,12),A=A+F|0,U=ge(U^A,8),T=T+U|0,F=ge(F^T,7),S=S+E|0,N=ge(N^S,16),D=D+N|0,E=ge(E^D,12),S=S+E|0,N=ge(N^S,8),D=D+N|0,E=ge(E^D,7),I=I+P|0,R=ge(R^I,16),L=L+R|0,P=ge(P^L,12),I=I+P|0,R=ge(R^I,8),L=L+R|0,P=ge(P^L,7),k=k+K|0,M=ge(M^k,16),_=_+M|0,K=ge(K^_,12),k=k+K|0,M=ge(M^k,8),_=_+M|0,K=ge(K^_,7);let G=0;n[G++]=i+A|0,n[G++]=a+S|0,n[G++]=c+I|0,n[G++]=l+k|0,n[G++]=u+K|0,n[G++]=d+F|0,n[G++]=f+E|0,n[G++]=h+P|0,n[G++]=p+L|0,n[G++]=y+_|0,n[G++]=g+T|0,n[G++]=m+D|0,n[G++]=b+N|0,n[G++]=w+R|0,n[G++]=x+M|0,n[G++]=v+U|0}var DD=ex(PD,{counterRight:!1,counterLength:4,allowShortKeys:!1});var kD=new Uint8Array(16),rx=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(kD.subarray(t))},ND=new Uint8Array(32);function nx(r,e,t,n,o){o!==void 0&&st(o,void 0,"AAD");let s=r(e,t,ND),i=Xw(n.length,o?o.length:0,!0),a=tx.create(s);o&&rx(a,o),rx(a,n),a.update(i);let c=a.digest();return qr(s,i),c}var OD=r=>(e,t,n)=>({encrypt(s,i){let a=s.length;i=Jl(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=nx(r,e,t,c,n);return i.set(l,a),qr(l),i},decrypt(s,i){i=Jl(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=nx(r,e,t,a,n);if(!jw(c,l))throw qr(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),r(e,t,i,i,1),qr(l),i}}),B4=Qw({blockSize:64,nonceLength:12,tagLength:16},OD(DD));function sx(r,e,t){return Ln(r),t===void 0&&(t=new Uint8Array(r.outputLen)),ks(r,t,e)}var U4=Uint8Array.of(0),ox=Uint8Array.of();function ix(r,e,t,n=32){Ln(r),Ht(n,"length"),mt(e,void 0,"prk");let o=r.outputLen;if(e.length<o)throw new Error('"prk" must be at least HashLen octets');if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);t===void 0?t=ox:mt(t,void 0,"info");let i=new Uint8Array(s*o),a=ks.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)U4[0]=u+1,c.update(u===0?ox:l).update(t).update(U4).digestInto(l),i.set(l,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),At(l,U4),i.slice(0,n)}var F4={hashSHA256(r){return yr(r.subarray())},getHKDF(r,e){let t=sx(yr,e,r),o=ix(yr,t,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=$c.utils.randomSecretKey();return{publicKey:$c.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:$c.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return $c.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return B4(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return B4(n,e,t).decrypt(r.subarray(),o)}};var ax=F4;function cx(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var va=r=>{let e=Pt(2);return e[0]=r>>8,e[1]=r,e};va.bytes=2;var Sa=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};Sa.bytes=2;function lx(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var H4={};$(H4,{base10:()=>KD});var cie=new Uint8Array(0);function ux(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function eo(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function dx(r){return new TextEncoder().encode(r)}function fx(r){return new TextDecoder().decode(r)}function MD(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,g=0,m=0,b=p.length;m!==b&&p[m]===0;)m++,y++;for(var w=(b-m)*u+1>>>0,x=new Uint8Array(w);m!==b;){for(var v=p[m],A=0,S=w-1;(v!==0||A<g)&&S!==-1;S--,A++)v+=256*x[S]>>>0,x[S]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=A,m++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var k=c.repeat(y);I<w;++I)k+=r.charAt(x[I]);return k}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var g=0,m=0;p[y]===c;)g++,y++;for(var b=(p.length-y)*l+1>>>0,w=new Uint8Array(b);p[y];){var x=t[p.charCodeAt(y)];if(x===255)return;for(var v=0,A=b-1;(x!==0||v<m)&&A!==-1;A--,v++)x+=a*w[A]>>>0,w[A]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=v,y++}if(p[y]!==" "){for(var S=b-m;S!==b&&w[S]===0;)S++;for(var I=new Uint8Array(g+(b-S)),k=g;S!==b;)I[k++]=w[S++];return I}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var BD=MD,UD=BD,px=UD;var $4=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},V4=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return mx(this,e)}},K4=class{decoders;constructor(e){this.decoders=e}or(e){return mx(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function mx(r,e){return new K4({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var q4=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new $4(e,t,n),this.decoder=new V4(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Aa({name:r,prefix:e,encode:t,decode:n}){return new q4(r,e,t,n)}function Bo({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=px(t,r);return Aa({prefix:e,name:r,encode:n,decode:s=>eo(o(s))})}function FD(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function $D(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function VD(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function ze({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=VD(n);return Aa({prefix:e,name:r,encode(s){return $D(s,n,t)},decode(s){return FD(s,o,t,r)}})}var KD=Bo({prefix:"9",name:"base10",alphabet:"0123456789"});var z4={};$(z4,{base16:()=>qD,base16upper:()=>HD});var qD=ze({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),HD=ze({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var G4={};$(G4,{base2:()=>zD});var zD=ze({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var W4={};$(W4,{base256emoji:()=>QD});var gx=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),GD=gx.reduce((r,e,t)=>(r[t]=e,r),[]),WD=gx.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function jD(r){return r.reduce((e,t)=>(e+=GD[t],e),"")}function YD(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=WD[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var QD=Aa({prefix:"\u{1F680}",name:"base256emoji",encode:jD,decode:YD});var j4={};$(j4,{base32:()=>Ca,base32hex:()=>ek,base32hexpad:()=>rk,base32hexpadupper:()=>nk,base32hexupper:()=>tk,base32pad:()=>ZD,base32padupper:()=>JD,base32upper:()=>XD,base32z:()=>ok});var Ca=ze({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),XD=ze({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ZD=ze({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),JD=ze({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ek=ze({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),tk=ze({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),rk=ze({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),nk=ze({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ok=ze({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Y4={};$(Y4,{base36:()=>tu,base36upper:()=>sk});var tu=Bo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),sk=Bo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Q4={};$(Q4,{base58btc:()=>pn,base58flickr:()=>ik});var pn=Bo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ik=Bo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var X4={};$(X4,{base64:()=>ak,base64pad:()=>ck,base64url:()=>lk,base64urlpad:()=>uk});var ak=ze({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ck=ze({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),lk=ze({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),uk=ze({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Z4={};$(Z4,{base8:()=>dk});var dk=ze({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var J4={};$(J4,{identity:()=>fk});var fk=Aa({prefix:"\0",name:"identity",encode:r=>fx(r),decode:r=>dx(r)});var Aie=new TextEncoder,Cie=new TextDecoder;var tg={};$(tg,{identity:()=>Ok});var mk=wx,yx=128,gk=127,yk=~gk,bk=Math.pow(2,31);function wx(r,e,t){e=e||[],t=t||0;for(var n=t;r>=bk;)e[t++]=r&255|yx,r/=128;for(;r&yk;)e[t++]=r&255|yx,r>>>=7;return e[t]=r|0,wx.bytes=t-n+1,e}var wk=eg,xk=128,bx=127;function eg(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw eg.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&bx)<<o:(i&bx)*Math.pow(2,o),o+=7}while(i>=xk);return eg.bytes=s-n,t}var Ek=Math.pow(2,7),vk=Math.pow(2,14),Sk=Math.pow(2,21),Ak=Math.pow(2,28),Ck=Math.pow(2,35),Ik=Math.pow(2,42),Tk=Math.pow(2,49),_k=Math.pow(2,56),Rk=Math.pow(2,63),Lk=function(r){return r<Ek?1:r<vk?2:r<Sk?3:r<Ak?4:r<Ck?5:r<Ik?6:r<Tk?7:r<_k?8:r<Rk?9:10},Pk={encode:mk,decode:wk,encodingLength:Lk},Dk=Pk,ru=Dk;function nu(r,e=0){return[ru.decode(r,e),ru.decode.bytes]}function Ia(r,e,t=0){return ru.encode(r,e,t),e}function Ta(r){return ru.encodingLength(r)}function Ra(r,e){let t=e.byteLength,n=Ta(r),o=n+Ta(t),s=new Uint8Array(o+t);return Ia(r,s,0),Ia(t,s,n),s.set(e,o),new _a(r,t,e,s)}function xx(r){let e=eo(r),[t,n]=nu(e),[o,s]=nu(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new _a(t,o,i,e)}function Ex(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ux(r.bytes,t.bytes)}}var _a=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var vx=0,kk="identity",Sx=eo;function Nk(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ra(vx,Sx(r))}var Ok={code:vx,name:kk,encode:Sx,digest:Nk};var og={};$(og,{sha256:()=>Bk,sha512:()=>Uk});var Mk=20;function ng({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new rg(r,e,t,n,o)}var rg=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Mk,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Ax(n,this.code,t?.truncate):n.then(o=>Ax(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ax(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ra(e,r)}function Ix(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Bk=ng({name:"sha2-256",code:18,encode:Ix("SHA-256")}),Uk=ng({name:"sha2-512",code:19,encode:Ix("SHA-512")});function Tx(r,e){let{bytes:t,version:n}=r;return n===0?$k(t,sg(r),e??pn.encoder):Vk(t,sg(r),e??Ca.encoder)}var _x=new WeakMap;function sg(r){let e=_x.get(r);if(e==null){let t=new Map;return _x.set(r,t),t}return e}var j1=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==su)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Kk)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Ra(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Ex(e.multihash,n.multihash)}toString(e){return Tx(this,e)}toJSON(){return{"/":Tx(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Rx(n,o,s.bytes))}else if(t[qk]===!0){let{version:n,multihash:o,code:s}=t,i=xx(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==su)throw new Error(`Version 0 CID must use dag-pb (code: ${su}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Rx(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,su,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=eo(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new _a(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,f]=nu(e.subarray(t));return t+=f,d},o=n(),s=su;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=Fk(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return sg(s).set(n,e),s}};function Fk(r,e){switch(r[0]){case"Q":{let t=e??pn;return[pn.prefix,t.decode(`${pn.prefix}${r}`)]}case pn.prefix:{let t=e??pn;return[pn.prefix,t.decode(r)]}case Ca.prefix:{let t=e??Ca;return[Ca.prefix,t.decode(r)]}case tu.prefix:{let t=e??tu;return[tu.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function $k(r,e,t){let{prefix:n}=t;if(n!==pn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Vk(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var su=112,Kk=18;function Rx(r,e,t){let n=Ta(r),o=n+Ta(e),s=new Uint8Array(o+t.byteLength);return Ia(r,s,0),Ia(e,s,n),s.set(t,o),s}var qk=Symbol.for("@ipld/js-cid/CID");var ig={...J4,...G4,...Z4,...H4,...z4,...j4,...Y4,...Q4,...X4,...W4},Wie={...og,...tg};function Px(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Lx=Px("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ag=Px("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Pt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Hk={utf8:Lx,"utf-8":Lx,hex:ig.base16,latin1:ag,ascii:ag,binary:ag,...ig},Y1=Hk;function mn(r,e="utf8"){let t=Y1[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function cg(r,e){!e.enabled||!ba||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${mn(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${mn(r.privateKey,"hex")}`)):e("Missing local static keys."))}function lg(r,e){!e.enabled||!ba||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${mn(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${mn(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Dx(r,e){!e.enabled||!ba||e(r?`REMOTE_STATIC_PUBLIC_KEY ${mn(r.subarray(),"hex")}`:"Missing remote static public key.")}function ug(r,e){!e.enabled||!ba||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${mn(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function dg(r,e,t){!t.enabled||!ba||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&mn(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&mn(e.k,"hex")}`))}function La(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Pt(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function fg(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Nx=Symbol.for("@achingbrain/uint8arraylist");function kx(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Q1(r){return!!r?.[Nx]}var gn=class r{bufs;length;[Nx]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Q1(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Q1(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=kx(this.bufs,e);return t.buf[t.index]}set(e,t){let n=kx(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Q1(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return La(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:La(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Q1(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let f=l;f>=0;f--){let h=this.get(d+f);if(n[f]!==h){u=Math.max(1,f-a[h]);break}}if(u===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Pt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ot(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Pt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ot(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!fg(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function si(r,e="utf8"){let t=Y1[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Pa=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Gk=0,Wk=4294967295,jk="Cipherstate has reached maximum n, a new handshake must be performed",X1=class{n;bytes;view;constructor(e=Gk){this.n=e,this.bytes=ot(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>Wk)throw new Error(jk)}};var ii=ot(0),Da=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new X1(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let o=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},hg=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=si(t,"utf-8");this.h=Yk(e,n),this.ck=this.h,this.cs=new Da(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new Da(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new gn(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,ii);return[new Da(this.crypto,e),new Da(this.crypto,t)]}},pg=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new hg(t,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let o=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},iu=class extends pg{writeMessageA(e){return new gn(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new gn(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new gn(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new Pa(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new Pa(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new Pa(`handshake stage 2 validation fail: ${t.message}`)}}};function Yk(r,e){if(e.length<=32){let t=ot(32);return t.set(e),t}else return r.hash(e)}var Qk=Math.pow(2,7),Xk=Math.pow(2,14),Zk=Math.pow(2,21),Ox=Math.pow(2,28),Mx=Math.pow(2,35),Bx=Math.pow(2,42),Ux=Math.pow(2,49),Kt=128,Uo=127;function au(r){if(r<Qk)return 1;if(r<Xk)return 2;if(r<Zk)return 3;if(r<Ox)return 4;if(r<Mx)return 5;if(r<Bx)return 6;if(r<Ux)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Fx(r,e,t=0){switch(au(r)){case 8:e[t++]=r&255|Kt,r/=128;case 7:e[t++]=r&255|Kt,r/=128;case 6:e[t++]=r&255|Kt,r/=128;case 5:e[t++]=r&255|Kt,r/=128;case 4:e[t++]=r&255|Kt,r>>>=7;case 3:e[t++]=r&255|Kt,r>>>=7;case 2:e[t++]=r&255|Kt,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function $x(r,e){let t=r[e],n=0;if(n+=t&Uo,t<Kt||(t=r[e+1],n+=(t&Uo)<<7,t<Kt)||(t=r[e+2],n+=(t&Uo)<<14,t<Kt)||(t=r[e+3],n+=(t&Uo)<<21,t<Kt)||(t=r[e+4],n+=(t&Uo)*Ox,t<Kt)||(t=r[e+5],n+=(t&Uo)*Mx,t<Kt)||(t=r[e+6],n+=(t&Uo)*Bx,t<Kt)||(t=r[e+7],n+=(t&Uo)*Ux,t<Kt))return n;throw new RangeError("Could not decode varint")}var mg=new Float32Array([-0]),Fo=new Uint8Array(mg.buffer);function Vx(r,e,t){mg[0]=r,e[t]=Fo[0],e[t+1]=Fo[1],e[t+2]=Fo[2],e[t+3]=Fo[3]}function Kx(r,e){return Fo[0]=r[e],Fo[1]=r[e+1],Fo[2]=r[e+2],Fo[3]=r[e+3],mg[0]}var gg=new Float64Array([-0]),Dt=new Uint8Array(gg.buffer);function qx(r,e,t){gg[0]=r,e[t]=Dt[0],e[t+1]=Dt[1],e[t+2]=Dt[2],e[t+3]=Dt[3],e[t+4]=Dt[4],e[t+5]=Dt[5],e[t+6]=Dt[6],e[t+7]=Dt[7]}function Hx(r,e){return Dt[0]=r[e],Dt[1]=r[e+1],Dt[2]=r[e+2],Dt[3]=r[e+3],Dt[4]=r[e+4],Dt[5]=r[e+5],Dt[6]=r[e+6],Dt[7]=r[e+7],gg[0]}var Jk=BigInt(Number.MAX_SAFE_INTEGER),eN=BigInt(Number.MIN_SAFE_INTEGER),fr=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return ai;if(e<Jk&&e>eN)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>zx&&(o=0n,++n>zx&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return ai;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ai}},ai=new fr(0,0);ai.toBigInt=function(){return 0n};ai.zzEncode=ai.zzDecode=function(){return this};ai.length=function(){return 1};var zx=4294967296n;function Gx(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Wx(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function yg(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Hr(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Z1(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var bg=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Hr(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Hr(this,4);return Z1(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Hr(this,4);return Z1(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Hr(this,4);let e=Kx(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Hr(this,4);let e=Hx(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Hr(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Wx(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Hr(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Hr(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new fr(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Hr(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Hr(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Hr(this,8);let e=Z1(this.buf,this.pos+=4),t=Z1(this.buf,this.pos+=4);return new fr(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=$x(this.buf,this.pos);return this.pos+=au(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function wg(r){return new bg(r instanceof Uint8Array?r:r.subarray())}function J1(r,e,t){let n=wg(r);return e.decode(n,void 0,t)}function xg(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Pt(i);o+i>e&&(n=Pt(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var ci=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Eg(){}var Sg=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},tN=xg();function rN(r){return globalThis.Buffer!=null?Pt(r):tN(r)}var lu=class{len;head;tail;states;constructor(){this.len=0,this.head=new ci(Eg,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new ci(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ag((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(e0,10,fr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=fr.fromBigInt(e);return this._push(e0,t.length(),t)}uint64Number(e){return this._push(Fx,au(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=fr.fromBigInt(e).zzEncode();return this._push(e0,t.length(),t)}sint64Number(e){let t=fr.fromNumber(e).zzEncode();return this._push(e0,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(vg,1,e?1:0)}fixed32(e){return this._push(cu,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=fr.fromBigInt(e);return this._push(cu,4,t.lo)._push(cu,4,t.hi)}fixed64Number(e){let t=fr.fromNumber(e);return this._push(cu,4,t.lo)._push(cu,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Vx,4,e)}double(e){return this._push(qx,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(vg,1,0):this.uint32(t)._push(oN,t,e)}string(e){let t=Gx(e);return t!==0?this.uint32(t)._push(yg,t,e):this._push(vg,1,0)}fork(){return this.states=new Sg(this),this.head=this.tail=new ci(Eg,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new ci(Eg,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=rN(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function vg(r,e,t){e[t]=r&255}function nN(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ag=class extends ci{next;constructor(e,t){super(nN,e,t),this.next=void 0}};function e0(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function cu(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function oN(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(lu.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(sN,e,r),this},lu.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(iN,e,r),this});function sN(r,e,t){e.set(r,t)}function iN(r,e,t){r.length<40?yg(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(si(r),t)}function Cg(){return new lu}function t0(r,e){let t=Cg();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var uu;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(uu||(uu={}));function Ig(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function r0(r,e){return Ig("message",uu.LENGTH_DELIMITED,r,e)}var du=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var n0;(function(r){let e;r.codec=()=>(e==null&&(e=r0((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);if(t.streamMuxers!=null)for(let s of t.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new du('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(t.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new du('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>t0(t,r.codec()),r.decode=(t,n)=>J1(t,r.codec(),n)})(n0||(n0={}));var fu;(function(r){let e;r.codec=()=>(e==null&&(e=r0((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),n0.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={identityKey:ot(0),identitySig:ot(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.identityKey=t.bytes();break}case 2:{s.identitySig=t.bytes();break}case 4:{s.extensions=n0.codec().decode(t,t.uint32(),{limits:o.limits?.extensions});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>t0(t,r.codec()),r.decode=(t,n)=>J1(t,r.codec(),n)})(fu||(fu={}));async function _g(r,e,t){let n=await r.sign(Qx(e));return fu.encode({identityKey:ct(r.publicKey),identitySig:n,extensions:t})}async function Rg(r,e,t){try{let n=fu.decode(r),o=nt(n.identityKey);if(t?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let s=Qx(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new fd(n.message)}}function Qx(r){let e=si("noise-libp2p-static-key:");return r instanceof Uint8Array?La([e,r],e.length+r.length):(r.prepend(e),r)}var Tg=class extends To{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new Pf({lengthDecoder:Sa,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let t=new gn;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),t.append(va(s.byteLength)),t.append(s)}return t}decrypt(e){let t=new gn;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-k4<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-k4);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),t.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function Lg(r,e,t){return new Tg(r,e,t)}async function Xx(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await _g(s,a.publicKey,l),d=new iu({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});cg(d.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(d.writeMessageA(ii),e),t.trace("Stage 0 - Initiator finished sending first message."),lg(d.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let f=d.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),ug(d.re,t),Dx(d.rs,t),t.trace("Initiator going to check remote's signature...");let h=await Rg(f,d.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(d.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[p,y]=d.ss.split();return dg(p,y,t),{payload:h,encrypt:g=>p.encryptWithAd(ii,g),decrypt:(g,m)=>y.decryptWithAd(ii,g,m)}}async function Zx(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await _g(s,a.publicKey,l),d=new iu({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});cg(d.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),ug(d.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(d.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),lg(d.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let f=d.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let h=await Rg(f,d.rs,c),[p,y]=d.ss.split();return dg(p,y,t),{payload:h,encrypt:g=>y.encryptWithAd(ii,g),decrypt:(g,m)=>p.decryptWithAd(ii,g,m)}}var o0=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??ax;this.crypto=cx(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?lx(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ot(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[ue]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,o=Po(e,{lengthEncoder:va,lengthDecoder:Sa,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=nt(s.payload.identityKey);return{connection:Lg(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:nn(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let o=t.get(n);if(o!=null)return o}if(e.length)throw new hd("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=e.log?.newScope("noise")??this.log,o=Po(e,{lengthEncoder:va,lengthDecoder:Sa,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=nt(s.payload.identityKey);return{connection:Lg(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:nn(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Xx({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Zx({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function s0(r={}){return e=>new o0(e,r)}function to(r=0){return new Uint8Array(r)}function pu(r=0){return new Uint8Array(r)}function Pg(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=pu(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function Jx(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var tE=Symbol.for("@achingbrain/uint8arraylist");function eE(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function i0(r){return!!r?.[tE]}var ka=class r{bufs;length;[tE]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(i0(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(i0(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=eE(this.bufs,e);return t.buf[t.index]}set(e,t){let n=eE(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(i0(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return Pg(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Pg(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!i0(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let f=l;f>=0;f--){let h=this.get(d+f);if(n[f]!==h){u=Math.max(1,f-a[h]);break}}if(u===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=pu(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=to(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=to(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=to(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=pu(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=to(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=to(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=to(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=to(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=to(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Jx(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var $e;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})($e||($e={}));var be;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(be||(be={}));var ale=Object.values(be).filter(r=>typeof r!="string"),rE=0,it;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(it||(it={}));var yn=12;var ro=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function nE(r){return r?.reason!==null}var hr=class extends ro{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,it.ProtocolError),this.name="InvalidFrameError"}},Na=class extends ro{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,it.ProtocolError),this.name="UnRequestedPingError"}},Oa=class extends ro{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,it.ProtocolError),this.name="NotMatchingPingError"}};var a0=class extends ro{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,it.ProtocolError),this.name="StreamAlreadyExistsError"}},c0=class extends ro{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,it.ProtocolError),this.name="DecodeInvalidVersionError"}},l0=class extends ro{static name="BothClientsError";constructor(e="Both clients"){super(e,it.ProtocolError),this.name="BothClientsError"}},Ma=class extends ro{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,it.ProtocolError),this.name="ReceiveWindowExceededError"}};var fle=new Set([hr.name,Na.name,Oa.name,a0.name,c0.name,l0.name,Ma.name]),mu=256*1024,u0=16*1024*1024;var gu={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:mu,maxStreamWindowSize:u0,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function oE(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new C("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new C("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new C("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new C("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<mu)throw new C("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new C("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new C("MaxStreamWindowSize must be less than equal MAX_UINT32")}function iE(r){return r.header.type===$e.Data&&r.data!==null}var sE=2**24;function aN(r){if(r[0]!==rE)throw new hr("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*sE+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*sE+(r[9]<<16)+(r[10]<<8)+r[11]}}var d0=class{buffer;constructor(){this.buffer=new ka}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=yn;if(this.buffer.byteLength<yn)return;let t=aN(this.buffer.subarray(0,yn));if(t.type===$e.Data){if(e+=t.length,this.buffer.byteLength<e)return;let n=this.buffer.sublist(yn,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}};function Dg(r){let e=new Uint8Array(yn);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}var qt;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(qt||(qt={}));var f0=class extends Lo{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??mu;super({...e,maxMessageSize:t-yn}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??u0,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let n=()=>{this.state=qt.Finished};this.addEventListener("close",n)}sendData(e){let t=e.byteLength,n=0,o=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){o=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}let s=Math.min(this.sendWindowCapacity,e.byteLength),i=this.getSendFlags(),a=e.sublist(0,s);e.consume(s);let c=this.sendFrame({type:$e.Data,flag:i,streamID:this.streamId,length:s},a);if(this.sendWindowCapacity-=s,n+=s,!c){o=c,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:o}}sendReset(){this.sendFrame({type:$e.WindowUpdate,flag:be.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|be.FIN;this.sendFrame({type:$e.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=qt.Paused}sendResume(){this.state=qt.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-yn,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!iE(e))throw new hr("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new Ma("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&be.ACK)===be.ACK&&this.state===qt.SYNSent&&(this.state=qt.Established),(e&be.FIN)===be.FIN&&this.onRemoteCloseWrite(),(e&be.RST)===be.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case qt.Init:return this.state=qt.SYNSent,be.SYN;case qt.SYNReceived:return this.state=qt.Established,be.ACK;default:return 0}}sendWindowUpdate(){if(this.state===qt.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>-1&&t-this.epochStart<=n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let o=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:$e.WindowUpdate,flag:e,streamID:this.streamId,length:o})}};function aE(r){return{type:$e[r.type],flags:[(r.flag&be.SYN)===be.SYN?"SYN":void 0,(r.flag&be.ACK)===be.ACK?"ACK":void 0,(r.flag&be.FIN)===be.FIN?"FIN":void 0,(r.flag&be.RST)===be.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var cE="/yamux/1.0.0",h0=class{protocol=cE;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[ue]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new kg(e,{...this._init})}},kg=class extends Ro{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:cE,name:"yamux"}),this.client=e.direction==="outbound",oE(t),this.enableKeepAlive=t.enableKeepAlive??gu.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??gu.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??gu.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??gu.maxOutboundStreams,this.decoder=new d0,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=ia(async n=>{try{await this.ping(n)}catch(o){this.log.error("ping error: %s",o)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new Ar("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Ar("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new xi("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,qt.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new Ar("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Ar("Muxer closed locally");if(this.activePing!=null)return De(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await De(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??it.NormalTermination;this.log.trace("muxer close reason=%s",it[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=it.InternalError;nE(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(this.streams.find(s=>s.streamId===e)!=null)throw new C("Stream already exists with that id");let o=new f0({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return o.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),o}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:n,length:o}=e.header;if(this.log.trace("received frame %o",aE(e.header)),t===0)switch(n){case $e.Ping:{this.handlePing(e.header);return}case $e.GoAway:{this.handleGoAway(o);return}default:throw new hr("Invalid frame type")}else switch(e.header.type){case $e.Data:case $e.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new hr("Invalid frame type")}}handlePing(e){if(e.flag===be.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,be.ACK);else if(e.flag===be.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new hr("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new Na("ping not requested");if(this.activePing.id!==e)throw new Oa("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",it[e]??"unknown"),this.remoteGoAway=e,e===it.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:n,type:o}=e.header;(n&be.SYN)===be.SYN&&this.incomingStream(t);let s=this.streams.find(i=>i.streamId===t);if(s===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(o){case $e.WindowUpdate:{s.handleWindowUpdate(e);return}case $e.Data:{s.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new C("Both endpoints are clients");if(this.streams.find(n=>n.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:$e.WindowUpdate,flag:be.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:$e.WindowUpdate,flag:be.RST,streamID:e,length:0});return}let t=this._newStream(e,qt.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===$e.Data){if(t==null)throw new hr("Invalid frame");n=new ka(Dg(e),t)}else n=Dg(e);return this.log.trace("sending frame %o",aE(e)),this.send(n)}sendPing(e,t=be.SYN){t===be.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:$e.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=it.NormalTermination){this.log("sending GoAway reason=%s",it[e]),this.localGoAway=e,this.sendFrame({type:$e.GoAway,flag:0,streamID:0,length:e})}};function lE(r={}){return()=>new h0(r)}async function*yu(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var p0=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*Ba(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),Ai(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new p0("Incoming message too long");let i=o.split(t);o=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var li=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},xr=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};var m0={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},g0=class{url;started;httpQueue;shutDownController;timeout;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(e,t){this.log=e.logger.forComponent("delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new jt({concurrency:t.concurrentRequests??m0.concurrentRequests}),this.inFlightRequests=new Map,this.url=t.url instanceof URL?t.url:new URL(t.url),this.timeout=t.timeout??m0.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.cacheName=t.cacheName??m0.cacheName,this.cacheTTL=t.cacheTTL??m0.cacheTTL}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&this.log("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){this.log("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=me([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers(),a=0;this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let c=new URL(`${this.url}routing/v1/providers/${e}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l=await this.#r(c.toString(),{headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:o});if(!l.ok){if(l.status===404)return;throw l.status===422?new li("Request does not conform to schema or semantic constraints"):new xr(`Unexpected status code: ${l.status}`)}let u=l.headers.get("Content-Type");if(u==null)throw new xr("No Content-Type header received");if(l.body==null){if(u!=="application/x-ndjson")throw new xr("Routing response had no body");return}if(u.startsWith("application/json")){let f=(await l.json()).Providers??[];for(let h of f){let p=this.#e(h);p!=null&&(a++,yield p)}}else if(u.includes("application/x-ndjson"))for await(let d of Ba(yu(l.body))){let f=this.#e(d);f!=null&&(a++,yield f)}else throw new xr(`Unsupported Content-Type: ${u}`)}finally{o.clear(),i.resolve(),this.log("getProviders finished found %d providers for %c",a,e)}}async*getPeers(e,t={}){this.log("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=me([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.url}routing/v1/peers/${e}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c=await this.#r(a.toString(),{headers:{Accept:"application/x-ndjson"},signal:o});if(c.status===404)return;if(c.status===422)throw new li("Request does not conform to schema or semantic constraints");if(c.body==null)throw new xr("Routing response had no body");if(c.headers.get("Content-Type")?.startsWith("application/json")){let d=(await c.json()).Peers??[];for(let f of d){let h=this.#e(f);h!=null&&(yield h)}}else for await(let u of Ba(yu(c.body))){let d=this.#e(u);d!=null&&(yield d)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),i.resolve(),this.log("getPeers finished: %c",e)}}async*getClosestPeers(e,t={}){let n;if(ae.asCID(e)===e||e instanceof ae)n=e.toV1().toString();else throw new C("Key must be CID");this.log("getClosestPeers starts: %s",n);let o=AbortSignal.timeout(this.timeout),s=me([this.shutDownController.signal,o,t.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));try{await i.promise;let c=new URL(`${this.url}routing/v1/dht/closest/peers/${n}`);this.#t(c,t.filterAddrs,t.filterProtocols);let l=await this.#r(c.toString(),{headers:{Accept:"application/x-ndjson"},signal:s});if(l.status===404)return;if(l.status===422)throw new li("Request does not conform to schema or semantic constraints");if(l.body==null)throw new xr("Routing response had no body");if(l.headers.get("Content-Type")?.startsWith("application/json")){let f=(await l.json()).Peers??[];for(let h of f){let p=this.#e(h);p!=null&&(yield p)}}else for await(let d of Ba(yu(l.body))){let f=this.#e(d);f!=null&&(yield f)}}catch(c){this.log.error("getClosestPeers errored - %e",c)}finally{s.clear(),a.resolve(),this.log("getClosestPeers finished: %s",n)}}async getIPNS(e,t={}){this.log("getIPNS starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=me([this.shutDownController.signal,n,t.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.url}routing/v1/ipns/${e}`;try{await s.promise;let c=await this.#r(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(this.log("getIPNS GET %s %d",a,c.status),c.status===404)throw new Pe("No matching records found");if(c.status===422)throw new li("Request does not conform to schema or semantic constraints");if(!c.ok)throw new xr(`Unexpected status code: ${c.status}`);let l=c.headers.get("Content-Type");if(l==null||!l.includes("application/vnd.ipfs.ipns-record"))throw new Pe("No matching records found");if(c.body==null)throw new xr("GET ipns response had no body");let u=await c.arrayBuffer();return new Uint8Array(u,0,u.byteLength)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),i.resolve(),this.log("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){this.log("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=me([this.shutDownController.signal,o,n.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${e}`;try{await i.promise;let l=await this.#r(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:ie(t),signal:s});if(this.log("putIPNS PUT %s %d",c,l.status),l.status!==200)throw new xr("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{s.clear(),a.resolve(),this.log("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(V)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:ae.createV1(114,cN(e.ID)),Addrs:n,Protocols:t}}catch(t){this.log.error("could not conform record to peer schema - %e",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#r(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",o),this.logResponse(c),c;this.log("evicting cached response for %s",o),await this.cache?.delete(e)}else this.cache!=null&&this.log("cache miss for %s",o)}let s=this.inFlightRequests.get(o);if(s!=null){let c=await s;return this.log("deduplicating outgoing request for %s",o),c.clone()}this.log("outgoing request:"),this.logRequest(e,t);let i=fetch(e,t).then(async c=>{if(this.log("incoming response:"),this.logResponse(c),this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,u=new Headers(c.headers);u.set("x-cache-expires",l.toString());let d=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:u});await this.cache.put(e,d)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(e,t){let n=new Headers(t.headers);this.log("%s %s HTTP/1.1",t.method??"GET",e);for(let[o,s]of n.entries())this.log("%s: %s",o,s)}logResponse(e){this.log("HTTP/1.1 %d %s",e.status,e.statusText);for(let[t,n]of e.headers.entries())this.log("%s: %s",t,n)}};function cN(r){let e=Ee.baseDecode(r);return ve(e)}function lN(r){return r[Symbol.asyncIterator]!=null}function uN(r){if(lN(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var uE=uN;var y0=O("/ipns/");function dE(r){return Z(r.subarray(0,y0.byteLength),y0)}var b0=class{client;constructor(e){this.client=e}get[is](){return this}async start(){await this.client.start()}async stop(){await this.client.stop()}async*findProviders(e,t={}){try{yield*Kr(this.client.getProviders(e,t),n=>({id:Mt(n.ID),multiaddrs:n.Addrs??[],routing:"delegated-http-routing-v1"}))}catch(n){if(n instanceof Pe)return;throw n}}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!dE(e))return;let o=ve(e.slice(y0.length)),s=ae.createV1(114,o);await this.client.putIPNS(s,t,n)}async get(e,t){if(!dE(e))throw new Pe("Not found");let n=ve(e.slice(y0.length)),o=ae.createV1(114,n);try{return await this.client.getIPNS(o,t)}catch(s){throw s.name==="BadResponseError"?new Pe("Not found"):s}}toString(){return`DelegatedRoutingV1HttpApiClientContentRouting(${this.client.url})`}},w0=class{client;constructor(e){this.client=e}get[ds](){return this}async start(){await this.client.start()}async stop(){await this.client.stop()}async findPeer(e,t={}){let n=await uE(this.client.getPeers(e.toCID(),t));if(n!=null)return{id:Mt(n.ID),multiaddrs:n.Addrs??[]};throw new Pe("Not found")}async*getClosestPeers(e,t={}){let n;try{n=ae.decode(e)}catch{try{n=ae.createV1(114,Ue.decode(e))}catch{n=ae.createV1(Cd,nr.digest(e))}}for await(let o of this.client.getClosestPeers(n,t))yield{id:Mt(o.ID),multiaddrs:o.Addrs??[]}}toString(){return`DelegatedRoutingV1HttpApiClientPeerRouting(${this.client.url})`}};function fE(r){return e=>new g0(e,r)}function hE(r){return e=>new b0(fE(r)(e))}function pE(r){return e=>new w0(fE(r)(e))}function x0(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}var mE="libp2p",gE="autonat",yE="1.0.0";var Me;(function(r){let e;(function(f){f.DIAL="DIAL",f.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(f){f[f.DIAL=0]="DIAL",f[f.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),(function(f){f.codec=()=>rt(t)})(e=r.MessageType||(r.MessageType={}));let n;(function(f){f.OK="OK",f.E_DIAL_ERROR="E_DIAL_ERROR",f.E_DIAL_REFUSED="E_DIAL_REFUSED",f.E_BAD_REQUEST="E_BAD_REQUEST",f.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let o;(function(f){f[f.OK=0]="OK",f[f.E_DIAL_ERROR=100]="E_DIAL_ERROR",f[f.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",f[f.E_BAD_REQUEST=200]="E_BAD_REQUEST",f[f.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(o||(o={})),(function(f){f.codec=()=>rt(o)})(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(f){let h;f.codec=()=>(h==null&&(h=ne((m,b,w={})=>{if(w.lengthDelimited!==!1&&b.fork(),m.id!=null&&(b.uint32(10),b.bytes(m.id)),m.addrs!=null&&m.addrs.length>0)for(let x of m.addrs)b.uint32(18),b.bytes(x);w.lengthDelimited!==!1&&b.ldelim()},(m,b,w={})=>{let x={addrs:[]},v=b==null?m.len:m.pos+b;for(;m.pos<v;){let A=m.uint32();switch(A>>>3){case 1:{x.id=m.bytes();break}case 2:{if(w.limits?.addrs!=null&&x.addrs.length===w.limits.addrs)throw new fe('Decode error - repeated field "addrs" had too many elements');x.addrs.push(m.bytes());break}default:{m.skipType(A&7);break}}}return x},function*(m,b,w,x={}){let v={addrs:0},A=b==null?m.len:m.pos+b;for(;m.pos<A;){let S=m.uint32();switch(S>>>3){case 1:{yield{field:`${w}.id`,value:m.bytes()};break}case 2:{if(x.limits?.addrs!=null&&v.addrs===x.limits.addrs)throw new fe('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${w}.addrs[]`,index:v.addrs,value:m.bytes()},v.addrs++;break}default:{m.skipType(S&7);break}}}})),h);function p(m){return te(m,f.codec())}f.encode=p;function y(m,b){return ee(m,f.codec(),b)}f.decode=y;function g(m,b){return re(m,f.codec(),b)}f.stream=g})(s=r.PeerInfo||(r.PeerInfo={}));let i;(function(f){let h;f.codec=()=>(h==null&&(h=ne((m,b,w={})=>{w.lengthDelimited!==!1&&b.fork(),m.peer!=null&&(b.uint32(10),r.PeerInfo.codec().encode(m.peer,b)),w.lengthDelimited!==!1&&b.ldelim()},(m,b,w={})=>{let x={},v=b==null?m.len:m.pos+b;for(;m.pos<v;){let A=m.uint32();A>>>3===1?x.peer=r.PeerInfo.codec().decode(m,m.uint32(),{limits:w.limits?.peer}):m.skipType(A&7)}return x},function*(m,b,w,x={}){let v=b==null?m.len:m.pos+b;for(;m.pos<v;){let A=m.uint32();A>>>3===1?yield*r.PeerInfo.codec().stream(m,m.uint32(),`${w}.peer`,{limits:x.limits?.peer}):m.skipType(A&7)}})),h);function p(m){return te(m,f.codec())}f.encode=p;function y(m,b){return ee(m,f.codec(),b)}f.decode=y;function g(m,b){return re(m,f.codec(),b)}f.stream=g})(i=r.Dial||(r.Dial={}));let a;(function(f){let h;f.codec=()=>(h==null&&(h=ne((m,b,w={})=>{w.lengthDelimited!==!1&&b.fork(),m.status!=null&&(b.uint32(8),r.ResponseStatus.codec().encode(m.status,b)),m.statusText!=null&&(b.uint32(18),b.string(m.statusText)),m.addr!=null&&(b.uint32(26),b.bytes(m.addr)),w.lengthDelimited!==!1&&b.ldelim()},(m,b,w={})=>{let x={},v=b==null?m.len:m.pos+b;for(;m.pos<v;){let A=m.uint32();switch(A>>>3){case 1:{x.status=r.ResponseStatus.codec().decode(m);break}case 2:{x.statusText=m.string();break}case 3:{x.addr=m.bytes();break}default:{m.skipType(A&7);break}}}return x},function*(m,b,w,x={}){let v=b==null?m.len:m.pos+b;for(;m.pos<v;){let A=m.uint32();switch(A>>>3){case 1:{yield{field:`${w}.status`,value:r.ResponseStatus.codec().decode(m)};break}case 2:{yield{field:`${w}.statusText`,value:m.string()};break}case 3:{yield{field:`${w}.addr`,value:m.bytes()};break}default:{m.skipType(A&7);break}}}})),h);function p(m){return te(m,f.codec())}f.encode=p;function y(m,b){return ee(m,f.codec(),b)}f.decode=y;function g(m,b){return re(m,f.codec(),b)}f.stream=g})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=ne((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.type!=null&&(h.uint32(8),r.MessageType.codec().encode(f.type,h)),f.dial!=null&&(h.uint32(18),r.Dial.codec().encode(f.dial,h)),f.dialResponse!=null&&(h.uint32(26),r.DialResponse.codec().encode(f.dialResponse,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={},g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{y.type=r.MessageType.codec().decode(f);break}case 2:{y.dial=r.Dial.codec().decode(f,f.uint32(),{limits:p.limits?.dial});break}case 3:{y.dialResponse=r.DialResponse.codec().decode(f,f.uint32(),{limits:p.limits?.dialResponse});break}default:{f.skipType(m&7);break}}}return y},function*(f,h,p,y={}){let g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.type`,value:r.MessageType.codec().decode(f)};break}case 2:{yield*r.Dial.codec().stream(f,f.uint32(),`${p}.dial`,{limits:y.limits?.dial});break}case 3:{yield*r.DialResponse.codec().stream(f,f.uint32(),`${p}.dialResponse`,{limits:y.limits?.dialResponse});break}default:{f.skipType(m&7);break}}}})),c);function l(f){return te(f,r.codec())}r.encode=l;function u(f,h){return ee(f,r.codec(),h)}r.decode=u;function d(f,h){return re(f,r.codec(),h)}r.stream=d})(Me||(Me={}));var gN=4,yN=8,E0=class{components;protocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;started;log;topologyId;dialResults;findPeers;addressFilter;connectionThreshold;constructor(e,t){this.components=e,this.log=e.logger.forComponent("libp2p:auto-nat"),this.started=!1,this.protocol=`/${t.protocolPrefix??mE}/${gE}/${yE}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??20,this.connectionThreshold=t.connectionThreshold??80,this.maxMessageSize=t.maxMessageSize??8192,this.dialResults=ft({name:"libp2p_autonat_dial_results",metrics:e.metrics}),this.findPeers=ia(this.findRandomPeers.bind(this),6e4),this.addressFilter=Wt(1024)}[Symbol.toStringTag]="@libp2p/autonat";[ue]=["@libp2p/autonat"];get[rr](){return["@libp2p/identify"]}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,(e,t)=>{this.handleIncomingAutonatStream(e,t).catch(n=>{this.log.error("error handling incoming autonat stream - %e",n)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.topologyId=await this.components.registrar.register(this.protocol,{onConnect:(e,t)=>{this.verifyExternalAddresses(t).catch(n=>{this.log.error("could not verify addresses - %e",n)})}}),this.findPeers.start(),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.topologyId!=null&&await this.components.registrar.unhandle(this.topologyId),this.dialResults.clear(),this.findPeers.stop(),this.started=!1}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every(e=>e.expires>Date.now()?!0:e.verified)}async findRandomPeers(e){if(this.allAddressesAreVerified())return;let t=me([AbortSignal.timeout(1e4),e?.signal]);try{this.log("starting random walk to find peers to run AutoNAT");for await(let n of this.components.randomWalk.walk({signal:t})){if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable %s",n.id,n.multiaddrs.map(o=>o.toString()).join(", "));continue}try{this.log.trace("dial random peer %p",n.id),await this.components.connectionManager.openConnection(n.multiaddrs,{signal:t})}catch{}if(this.allAddressesAreVerified()){this.log("stopping random walk, all addresses are verified");return}if(!this.hasConnectionCapacity()){this.log("stopping random walk, too close to max connections");return}}}catch{}}async handleIncomingAutonatStream(e,t){let n=AbortSignal.timeout(this.timeout);try{let o=ke(e,{maxDataLength:this.maxMessageSize}).pb(Me),s=await o.read({signal:n}),i=await this.handleAutonatMessage(s,t,{signal:n});await o.write(i,{signal:n}),await e.close({signal:n})}catch(o){this.log.error("error handling incoming autonat stream - %e",o),e.abort(o)}}async handleAutonatMessage(e,t,n){let o=this.components.addressManager.getAddresses().map(d=>Y(d).host),s=e.dial;if(s==null)return this.log.error("dial was missing from message"),{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}};let i,a=s.peer;if(a?.id==null)return this.log.error("peerId missing from message"),{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}};try{let d=ve(a.id);i=Xe(d)}catch(d){return this.log.error("invalid PeerId - %e",d),{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}}}if(this.log("incoming request from %p",i),!t.remotePeer.equals(i))return this.log("target peer %p did not equal sending peer %p",i,t.remotePeer),{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}};let c=a.addrs.map(d=>V(d)).filter(d=>{try{let f=Y(d);return Ze(d)?!1:f.host!==Y(t.remoteAddr).host?(this.log.trace("not dialing %a - target host did not match remote host %a",d,t.remoteAddr),!1):o.includes(f.host)?!1:this.components.transportManager.dialTransportForMultiaddr(d)==null?(this.log.trace("not dialing %a - transport unsupported",d),!1):!0}catch{return!1}}).map(d=>(d.getComponents().find(f=>f.code===421)?.value==null&&(d=d.encapsulate(`/p2p/${i.toString()}`)),d));if(c.length===0)return this.log("refused to dial all multiaddrs for %p from message",i),{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}};this.log("dial multiaddrs %s for peer %p",c.map(d=>d.toString()).join(", "),i);let l="",u=c[0];for(let d of c){let f;u=d;try{if(f=await this.components.connectionManager.openConnection(d,n),!f.remoteAddr.equals(d))throw this.log.error("tried to dial %a but dialed %a",d,f.remoteAddr),new Error("Unexpected remote address");return this.log("successfully dialed %p via %a",i,d),{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.OK,addr:f.remoteAddr.decapsulateCode(421).bytes}}}catch(h){this.log.error("could not dial %p - %e",i,h),l=h.message}finally{f!=null&&await f.close()}}return{type:Me.MessageType.DIAL_RESPONSE,dialResponse:{status:Me.ResponseStatus.E_DIAL_ERROR,statusText:l,addr:u.bytes}}}getFirstUnverifiedMultiaddr(e,t){let n=this.components.addressManager.getAddressesWithMetadata().sort((o,s)=>o.type==="observed"&&s.type!=="observed"?1:s.type==="observed"&&o.type!=="observed"?-1:0).filter(o=>!(!(o.expires<Date.now())||Y(o.multiaddr).type==="ip6"&&(!t||!sf(o.multiaddr))||Ze(o.multiaddr)));for(let o of n){let s=o.multiaddr.toString(),i=this.dialResults.get(s);if(i!=null){if(i.networkSegments.includes(e)){this.log.trace("%a already has a network segment result from %s",i.multiaddr,e);continue}if(i.queue.size>10){this.log.trace("%a already has enough peers queued",i.multiaddr);continue}}if(i==null){let a=o.expires<Date.now();if(a&&this.addressFilter.remove?.(s),this.addressFilter.has(s))continue;this.addressFilter.add(s),this.log.trace("creating dial result %s %s",a?"to revalidate":"for",s),i={multiaddr:o.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:Vm(),queue:new Yt({concurrency:3,maxSize:50}),type:o.type,lastVerified:o.lastVerified},this.dialResults.set(s,i)}return i}}removeOutdatedMultiaddrResults(){let e=new Set(this.components.addressManager.getAddressesWithMetadata().filter(({expires:t})=>t<Date.now()).map(({multiaddr:t})=>t.toString()));for(let t of this.dialResults.keys())e.has(t)||(this.log.trace("remove results for %a",t),this.dialResults.delete(t))}async verifyExternalAddresses(e){if(!this.isStarted())return;this.removeOutdatedMultiaddrResults();let n=(await this.components.peerStore.get(e.remotePeer)).addresses.some(({multiaddr:i})=>Y(i).type==="ip6"),o=this.getNetworkSegment(e.remoteAddr),s=this.getFirstUnverifiedMultiaddr(o,n);if(s==null){this.log.trace("no unverified public addresses found for peer %p to verify, not requesting verification",e.remotePeer);return}if(!this.hasConnectionCapacity()){s.lastVerified!=null?(this.log("automatically re-verifying %a because we are too close to the connection limit",s.multiaddr),this.confirmAddress(s)):this.log("skipping verifying %a because we are too close to the connection limit",s.multiaddr);return}s.queue.add(async i=>{await this.askPeerToVerify(e,o,i)},{peerId:e.remotePeer,multiaddr:s.multiaddr}).catch(i=>{s?.result==null&&this.log.error("error from %p verifying address %a - %e",e.remotePeer,s?.multiaddr,i)})}async askPeerToVerify(e,t,n){let o=this.dialResults.get(n.multiaddr.toString());if(o==null){this.log("%a was verified while %p was queued",n.multiaddr,e.remotePeer);return}let s=AbortSignal.timeout(this.timeout);this.log.trace("asking %a to verify multiaddr %s",e.remoteAddr,n.multiaddr);let i=await e.newStream(this.protocol,{signal:s});try{let a=ke(i).pb(Me),[,c]=await Promise.all([a.write({type:Me.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toMultihash().bytes,addrs:[n.multiaddr.bytes]}}},{signal:s}),a.read({signal:s})]);if(c.type!==Me.MessageType.DIAL_RESPONSE||c.dialResponse==null){this.log("invalid autonat response from %p - %j",e.remotePeer,c);return}let l=c.dialResponse.status;if(this.log.trace("autonat response from %p for %a is %s",e.remotePeer,n.multiaddr,l),l!==Me.ResponseStatus.OK&&l!==Me.ResponseStatus.E_DIAL_ERROR)return;if(o=this.dialResults.get(n.multiaddr.toString()),o==null){this.log.trace("peer reported %a as %s but there is no result object",n.multiaddr,c.dialResponse.status);return}if(o.networkSegments.includes(t)){this.log.trace("%a results included network segment %s",n.multiaddr,t);return}if(o.result!=null){this.log.trace("already resolved result for %a, ignoring response from",n.multiaddr,e.remotePeer);return}if(o.verifyingPeers.has(e.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",e.remotePeer,n.multiaddr);return}if(o.verifyingPeers.add(e.remotePeer),o.networkSegments.push(t),l===Me.ResponseStatus.OK){if(o.success++,o.type!=="observed"){this.confirmAddress(o);return}}else l===Me.ResponseStatus.E_DIAL_ERROR&&o.failure++;this.log("%a success %d failure %d",o.multiaddr,o.success,o.failure),o.success===gN&&this.confirmAddress(o),o.failure===yN&&this.unconfirmAddress(o)}finally{try{await i.close({signal:s})}catch(a){i.abort(a)}}}hasConnectionCapacity(){let t=this.components.connectionManager.getConnections().length,n=this.components.connectionManager.getMaxConnections();return t/n*100<this.connectionThreshold}confirmAddress(e){this.log("%s address %a is externally dialable",e.type,e.multiaddr),this.components.addressManager.confirmObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!0,e.queue.abort()}unconfirmAddress(e){this.log("%s address %a is not externally dialable",e.type,e.multiaddr),this.components.addressManager.removeObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!1,e.queue.abort()}getNetworkSegment(e){let t=Y(e);switch(t.type){case"ip4":return t.host.split(".")[0].padStart(3,"0");case"ip6":return t.host.split(":")[0].padStart(4,"0");default:throw new C(`Remote address ${e} was not an IPv4 or Ipv6 address`)}}};function bE(r={}){return e=>new E0(e,r)}var bN="bootstrap",wN=50,xN=1e3,Ng=class extends se{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??xN,this.list=t.list.map(n=>V(n)).filter(n=>ta.matches(n)?n.getComponents().findLast(s=>s.code===421)?.value==null?(this.log.error("invalid bootstrap multiaddr without peer id"),!1):!0:(this.log.error("invalid multiaddr %a",n),!1)).map(n=>({id:Oe(n.getComponents().findLast(o=>o.code===421)?.value??""),multiaddrs:[n]})),this._init=t}[us]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[ue]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??bN]:{value:this._init.tagValue??wN,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function wE(r){return e=>new Ng(e,r)}var Og=1e3,xE=60*Og;var Zue=120*xE,EE=1,v0=5e3,vE=100;var bu=`${fs}-circuit-relay`,Jue=2*xE,ede=BigInt(1<<17),ui="/libp2p/circuit/relay/0.2.0/hop",Mg="/libp2p/circuit/relay/0.2.0/stop",tde=30*Og,rde=30*Og,Bg=300,SE=4096,AE=.001;var Ko;(function(r){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(t||(t={})),(function(a){a.codec=()=>rt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ne((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),$o.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),wu.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),Vo.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),at.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=$o.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.reservation=wu.codec().decode(a,a.uint32(),{limits:l.limits?.reservation});break}case 4:{u.limit=Vo.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 5:{u.status=at.codec().decode(a);break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*$o.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*wu.codec().stream(a,a.uint32(),`${l}.reservation`,{limits:u.limits?.reservation});break}case 4:{yield*Vo.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 5:{yield{field:`${l}.status`,value:at.codec().decode(a)};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return te(a,r.codec())}r.encode=o;function s(a,c){return ee(a,r.codec(),c)}r.decode=s;function i(a,c){return re(a,r.codec(),c)}r.stream=i})(Ko||(Ko={}));var bn;(function(r){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(t||(t={})),(function(a){a.codec=()=>rt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ne((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),$o.codec().encode(a.peer,c)),a.limit!=null&&(c.uint32(26),Vo.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(32),at.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=$o.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.limit=Vo.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 4:{u.status=at.codec().decode(a);break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*$o.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*Vo.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 4:{yield{field:`${l}.status`,value:at.codec().decode(a)};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return te(a,r.codec())}r.encode=o;function s(a,c){return ee(a,r.codec(),c)}r.decode=s;function i(a,c){return re(a,r.codec(),c)}r.stream=i})(bn||(bn={}));var $o;(function(r){let e;r.codec=()=>(e==null&&(e=ne((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.id!=null&&s.id.byteLength>0&&(i.uint32(10),i.bytes(s.id)),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(18),i.bytes(c);a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={id:de(0),addrs:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.id=s.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new fe('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={addrs:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{yield{field:`${a}.id`,value:s.bytes()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new fe('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:s.bytes()},l.addrs++;break}default:{s.skipType(d&7);break}}}})),e);function t(s){return te(s,r.codec())}r.encode=t;function n(s,i){return ee(s,r.codec(),i)}r.decode=n;function o(s,i){return re(s,r.codec(),i)}r.stream=o})($o||($o={}));var wu;(function(r){let e;r.codec=()=>(e==null&&(e=ne((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.expire!=null&&s.expire!==0n&&(i.uint32(8),i.uint64(s.expire)),s.addrs!=null&&s.addrs.length>0)for(let c of s.addrs)i.uint32(18),i.bytes(c);s.voucher!=null&&(i.uint32(26),Eu.codec().encode(s.voucher,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={expire:0n,addrs:[]},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.expire=s.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new fe('Decode error - repeated field "addrs" had too many elements');c.addrs.push(s.bytes());break}case 3:{c.voucher=Eu.codec().decode(s,s.uint32(),{limits:a.limits?.voucher});break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l={addrs:0},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{yield{field:`${a}.expire`,value:s.uint64()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new fe('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:s.bytes()},l.addrs++;break}case 3:{yield*Eu.codec().stream(s,s.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{s.skipType(d&7);break}}}})),e);function t(s){return te(s,r.codec())}r.encode=t;function n(s,i){return ee(s,r.codec(),i)}r.decode=n;function o(s,i){return re(s,r.codec(),i)}r.stream=o})(wu||(wu={}));var Vo;(function(r){let e;r.codec=()=>(e==null&&(e=ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.duration!=null&&(i.uint32(8),i.uint32(s.duration)),s.data!=null&&(i.uint32(16),i.uint64(s.data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.duration=s.uint32();break}case 2:{c.data=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.duration`,value:s.uint32()};break}case 2:{yield{field:`${a}.data`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return te(s,r.codec())}r.encode=t;function n(s,i){return ee(s,r.codec(),i)}r.decode=n;function o(s,i){return re(s,r.codec(),i)}r.stream=o})(Vo||(Vo={}));var at;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(at||(at={}));var Ug;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(Ug||(Ug={}));(function(r){r.codec=()=>rt(Ug)})(at||(at={}));var xu;(function(r){let e;r.codec=()=>(e==null&&(e=ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.relay!=null&&s.relay.byteLength>0&&(i.uint32(10),i.bytes(s.relay)),s.peer!=null&&s.peer.byteLength>0&&(i.uint32(18),i.bytes(s.peer)),s.expiration!=null&&s.expiration!==0n&&(i.uint32(24),i.uint64(s.expiration)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={relay:de(0),peer:de(0),expiration:0n},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.relay=s.bytes();break}case 2:{c.peer=s.bytes();break}case 3:{c.expiration=s.uint64();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.relay`,value:s.bytes()};break}case 2:{yield{field:`${a}.peer`,value:s.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:s.uint64()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return te(s,r.codec())}r.encode=t;function n(s,i){return ee(s,r.codec(),i)}r.decode=n;function o(s,i){return re(s,r.codec(),i)}r.stream=o})(xu||(xu={}));var Eu;(function(r){let e;r.codec=()=>(e==null&&(e=ne((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.publicKey!=null&&s.publicKey.byteLength>0&&(i.uint32(10),i.bytes(s.publicKey)),s.payloadType!=null&&s.payloadType.byteLength>0&&(i.uint32(18),i.bytes(s.payloadType)),s.payload!=null&&(i.uint32(26),xu.codec().encode(s.payload,i)),s.signature!=null&&s.signature.byteLength>0&&(i.uint32(42),i.bytes(s.signature)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={publicKey:de(0),payloadType:de(0),signature:de(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.publicKey=s.bytes();break}case 2:{c.payloadType=s.bytes();break}case 3:{c.payload=xu.codec().decode(s,s.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:s.bytes()};break}case 3:{yield*xu.codec().stream(s,s.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function t(s){return te(s,r.codec())}r.encode=t;function n(s,i){return ee(s,r.codec(),i)}r.decode=n;function o(s,i){return re(s,r.codec(),i)}r.stream=o})(Eu||(Eu={}));var vu=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},S0=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},A0=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function Fg(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var Su=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},C0=Ce(pe(ta.matchers[0],Ae(290))),I0=Ce(Ae(290));var T0=class extends se{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(ui,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(ui)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let s=CE(n),i=CE(o);return s>i?-1:i>s?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Yt({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p - %e",n.id,o)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,o)})}async dialPeer({peerId:e,signal:t}){let n=me([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function CE(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(B(e)).getTime()}var $g=class extends se{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??v0,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(I0.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(C0.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let s=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(s)}}else throw new ls(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>V(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function IE(r){return new $g(r)}var TE="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var _E=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=TE[t[r]&63];return e};var EN=60*1e3*10,vN=60*1e3*5,SN=30*1e3,_0=class extends se{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new Tt,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??vE,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??v0,this.started=!1,this.relayFilter=Wt(100),this.reserveQueue=new Yt({concurrency:t?.reservationConcurrency??EE,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(s=>s.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(s=>{this.log("could not remove relay %p - %e",n.detail,s)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(bu)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[bu]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=_E();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new ls("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new A0("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new ls("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let o=Date.now();try{let s=this.reservations.get(e);if(s!=null){let p=this.connectionManager.getConnections(e),y=!1;if(p.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),p.map(g=>g.id).includes(s.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),y=!0),y&&Fg(s.reservation.expire)>EN)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:s};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new vu("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(e,{signal:i});if(dt.matches(a.remoteAddr))throw new S0("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=Fg(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-vN,SN),Math.pow(2,31)-1),d=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async p=>{this.log.error("could not refresh reservation to relay %p - %e",e,p),await this.#t(e)}).catch(p=>{this.log.error("could not remove expired reservation to relay %p - %e",e,p)})},u),f;if(t==="discovered"){let p=this.pendingReservations.pop();if(p==null)throw new vu("Made reservation on relay but did not need any more discovered relays");f={timeout:d,reservation:c,type:t,connection:a.id,id:p}}else f={timeout:d,reservation:c,type:t,connection:a.id};this.reservations.set(e,f),await this.peerStore.merge(e,{tags:{[bu]:{value:1,ttl:l}}}),this.#r();let h={relay:e,details:f};return this.safeDispatchEvent("relay:created-reservation",{detail:h}),h}catch(s){throw t==="discovered"&&s.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-o,s),(s.name==="DialError"||s.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),s}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(ui,t),s=ke(n).pb(Ko);this.log.trace("send RESERVE to %p",e.remotePeer),await s.write({type:Ko.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await s.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===at.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of i.reservation.addrs){let u=V(l);u.getComponents().find(d=>d.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=V(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return i.reservation.addrs=[...c].map(l=>V(l).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[bu]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=Wt(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var Vg=class extends _o{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function Kg(r){return new Vg(r)}var AN=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(V)}catch{return!1}return!0},RE={maxInboundStopStreams:Bg,maxOutboundStopStreams:Bg,stopTimeout:3e4},R0=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??RE.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??RE.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new T0(e,{filter:t.discoveryFilter??O3(SE,AE)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,o)})}),this.reservationStore=new _0(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[ue]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[rr](){return this.discovery!=null?["@libp2p/identify"]:[]}[fo]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(Mg,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await Tr(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Zr(this.discovery,this.reservationStore),await this.components.registrar.unhandle(Mg),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),o=V(n[0]),s=V(n[n.length-1]),i=o.getComponents().find(h=>h.code===421)?.value,a=s.getComponents().find(h=>h.code===421)?.value;if(i==null||a==null){let h=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${h}`),new lo(`C${h}`)}let c=Oe(i),l=Oe(a),d=this.components.connectionManager.getConnections(c)[0];d==null?(await this.components.peerStore.merge(c,{multiaddrs:[o]}),t.onProgress?.(new X("circuit-relay:open-connection")),d=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new X("circuit-relay:reuse-connection"));let f;try{t.onProgress?.(new X("circuit-relay:open-hop-stream")),f=await d.newStream(ui,t);let h=ke(f).pb(Ko);t.onProgress?.(new X("circuit-relay:write-connect-message")),await h.write({type:Ko.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[V(s).bytes]}},t),t.onProgress?.(new X("circuit-relay:read-connect-response"));let p=await h.read(t);if(p.status!==at.OK)throw new oe(`failed to connect via relay with status ${p?.status?.toString()??"undefined"}`);let y=new Su(p.limit),g=Kg({stream:h.unwrap().unwrap(),remoteAddr:e,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:y.onData,onDataWrite:y.onData,log:f.log.newScope("circuit-relay:connection")}),m=await this.components.upgrader.upgradeOutbound(g,{...t,limits:y.getLimits()});return m.log("outbound relayed connection established to %p with limits %o, over connection %s",m.remotePeer,p.limit??"none",d.id),m}catch(h){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,h),f?.abort(h),h}}createListener(e){return IE({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>C0.exactMatch(t)||I0.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>dt.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(d){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",d)}let o=ke(e).pb(bn),s=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,s.type),s?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:bn.Type.STATUS,status:at.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(s.type!==bn.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:bn.Type.STATUS,status:at.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!AN(s)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:bn.Type.STATUS,status:at.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=Xe(ve(s.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:bn.Type.STATUS,status:at.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:bn.Type.STATUS,status:at.OK},{signal:n});let a=new Su(s.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.components.addressManager.getAddresses()[0],u=Kg({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,s.limit??"none",t.id)}finally{n?.clear()}}};function LE(r={}){return e=>new R0(e,r)}var zr;(function(r){let e;(function(a){a.UNUSED="UNUSED",a.CONNECT="CONNECT",a.SYNC="SYNC"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.UNUSED=0]="UNUSED",a[a.CONNECT=100]="CONNECT",a[a.SYNC=300]="SYNC"})(t||(t={})),(function(a){a.codec=()=>rt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ne((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.observedAddresses!=null&&a.observedAddresses.length>0)for(let u of a.observedAddresses)c.uint32(18),c.bytes(u);l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={observedAddresses:[]},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{if(l.limits?.observedAddresses!=null&&u.observedAddresses.length===l.limits.observedAddresses)throw new fe('Decode error - repeated field "observedAddresses" had too many elements');u.observedAddresses.push(a.bytes());break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={observedAddresses:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{if(u.limits?.observedAddresses!=null&&d.observedAddresses===u.limits.observedAddresses)throw new fe('Streaming decode error - repeated field "observedAddresses" had too many elements');yield{field:`${l}.observedAddresses[]`,index:d.observedAddresses,value:a.bytes()},d.observedAddresses++;break}default:{a.skipType(h&7);break}}}})),n);function o(a){return te(a,r.codec())}r.encode=o;function s(a,c){return ee(a,r.codec(),c)}r.decode=s;function i(a,c){return re(a,r.codec(),c)}r.stream=i})(zr||(zr={}));function qg(r,e){return dt.matches(r)||e.dialTransportForMultiaddr(r)==null?!1:x9.matches(r)?!0:A9.matches(r)?!Ze(r):!1}var PE=1024*4,DE=100,L0={timeout:5e3,retries:3,maxInboundStreams:1,maxOutboundStreams:1},P0=class{started;timeout;retries;maxInboundStreams;maxOutboundStreams;peerStore;registrar;connectionManager;addressManager;transportManager;topologyId;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:dcutr"),this.started=!1,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.timeout=t.timeout??L0.timeout,this.retries=t.retries??L0.retries,this.maxInboundStreams=t.maxInboundStreams??L0.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??L0.maxOutboundStreams,this.handleIncomingUpgrade=this.handleIncomingUpgrade.bind(this)}[Symbol.toStringTag]="@libp2p/dcutr";[rr]=["@libp2p/identify"];isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.registrar.register(Au,{notifyOnLimitedConnection:!0,onConnect:(e,t)=>{dt.exactMatch(t.remoteAddr)&&t.direction==="inbound"&&this.upgradeInbound(t).catch(n=>{this.log.error("error during outgoing DCUtR attempt - %e",n)})}}),await this.registrar.handle(Au,this.handleIncomingUpgrade,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){await this.registrar.unhandle(Au),this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async upgradeInbound(e){if(await this.attemptUnilateralConnectionUpgrade(e))return;let t;for(let n=0;n<this.retries;n++){let o={signal:AbortSignal.timeout(this.timeout)};try{t=await e.newStream([Au],{signal:o.signal,runOnLimitedConnection:!0});let s=ke(t,{maxDataLength:PE}).pb(zr);this.log("B sending connect to %p",e.remotePeer);let i=Date.now();await s.write({type:zr.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(d=>d.bytes)},o),this.log("B receiving connect from %p",e.remotePeer);let a=await s.read(o);if(a.type!==zr.Type.CONNECT)throw this.log("A sent wrong message type"),new oe("DCUtR message type was incorrect");let c=this.getDialableMultiaddrs(a.observedAddresses);if(c.length===0)throw this.log("A did not have any dialable multiaddrs"),new oe("DCUtR connect message had no multiaddrs");let l=Date.now()-i;this.log("A sending sync, rtt %dms",l),await s.write({type:zr.Type.SYNC,observedAddresses:[]},o),this.log("A waiting for half RTT"),await K9(l/2),this.log("B dialing",c);let u=await this.connectionManager.openConnection(c,{signal:o.signal,priority:DE,force:!0,initiator:!1});this.log("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,u.remoteAddr),await e.close(o);break}catch(s){if(this.log.error("error while attempting DCUtR on attempt %d of %d - %e",n+1,this.retries,s),t?.abort(s),n===this.retries)throw s}finally{t!=null&&await t.close(o)}}}async attemptUnilateralConnectionUpgrade(e){let n=(await this.peerStore.get(e.remotePeer)).addresses.map(o=>{let s=o.multiaddr;return s.getComponents().find(i=>i.code===421)?.value==null?s.encapsulate(`/p2p/${e.remotePeer}`):s}).filter(o=>qg(o,this.transportManager));if(n.length>0){let o=AbortSignal.timeout(this.timeout);try{this.log("attempting unilateral connection upgrade to %a",n);let s=await this.connectionManager.openConnection(n,{signal:o,force:!0});if(dt.exactMatch(s.remoteAddr))throw new Error("Could not open a new, non-limited, connection");return this.log("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,s.remoteAddr),await e.close({signal:o}),!0}catch(s){this.log.error("unilateral connection upgrade to %p on addresses %a failed - %e",e.remotePeer,n,s)}}else this.log("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}async handleIncomingUpgrade(e,t){let n={signal:AbortSignal.timeout(this.timeout)},o=ke(e,{maxDataLength:PE}).pb(zr);this.log("A receiving connect");let s=await o.read(n);if(s.type!==zr.Type.CONNECT)throw this.log("B sent wrong message type"),new oe("DCUtR message type was incorrect");if(s.observedAddresses.length===0)throw this.log("B sent no multiaddrs"),new oe("DCUtR connect message had no multiaddrs");let i=this.getDialableMultiaddrs(s.observedAddresses);if(i.length===0)throw this.log("B had no dialable multiaddrs in %o",s.observedAddresses.map(l=>V(l))),new oe("DCUtR connect message had no dialable multiaddrs");if(this.log("A sending connect"),await o.write({type:zr.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(l=>l.bytes)}),this.log("A receiving sync"),(await o.read(n)).type!==zr.Type.SYNC)throw new oe("DCUtR message type was incorrect");this.log("A dialing",i);let c=await this.connectionManager.openConnection(i,{signal:n.signal,priority:DE,force:!0});this.log("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,c.remoteAddr),await t.close(n),await e.close(n)}getDialableMultiaddrs(e){let t=[];for(let n of e)if(!(n==null||n.length===0))try{let o=V(n);if(!qg(o,this.transportManager))continue;t.push(o)}catch{}return t}};var Au="/libp2p/dcutr";function kE(r={}){return e=>new P0(e,r)}var jg={};$(jg,{base10:()=>PN});var Cfe=new Uint8Array(0);function NE(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function no(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function OE(r){return new TextEncoder().encode(r)}function ME(r){return new TextDecoder().decode(r)}function CN(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,g=0,m=0,b=p.length;m!==b&&p[m]===0;)m++,y++;for(var w=(b-m)*u+1>>>0,x=new Uint8Array(w);m!==b;){for(var v=p[m],A=0,S=w-1;(v!==0||A<g)&&S!==-1;S--,A++)v+=256*x[S]>>>0,x[S]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");g=A,m++}for(var I=w-g;I!==w&&x[I]===0;)I++;for(var k=c.repeat(y);I<w;++I)k+=r.charAt(x[I]);return k}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var g=0,m=0;p[y]===c;)g++,y++;for(var b=(p.length-y)*l+1>>>0,w=new Uint8Array(b);p[y];){var x=t[p.charCodeAt(y)];if(x===255)return;for(var v=0,A=b-1;(x!==0||v<m)&&A!==-1;A--,v++)x+=a*w[A]>>>0,w[A]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=v,y++}if(p[y]!==" "){for(var S=b-m;S!==b&&w[S]===0;)S++;for(var I=new Uint8Array(g+(b-S)),k=g;S!==b;)I[k++]=w[S++];return I}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var IN=CN,TN=IN,UE=TN;var Hg=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},zg=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return FE(this,e)}},Gg=class{decoders;constructor(e){this.decoders=e}or(e){return FE(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function FE(r,e){return new Gg({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Wg=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Hg(e,t,n),this.decoder=new zg(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ua({name:r,prefix:e,encode:t,decode:n}){return new Wg(r,e,t,n)}function qo({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=UE(t,r);return Ua({prefix:e,name:r,encode:n,decode:s=>no(o(s))})}function _N(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function RN(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function LN(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Ge({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=LN(n);return Ua({prefix:e,name:r,encode(s){return RN(s,n,t)},decode(s){return _N(s,o,t,r)}})}var PN=qo({prefix:"9",name:"base10",alphabet:"0123456789"});var Yg={};$(Yg,{base16:()=>DN,base16upper:()=>kN});var DN=Ge({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),kN=Ge({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Qg={};$(Qg,{base2:()=>NN});var NN=Ge({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Xg={};$(Xg,{base256emoji:()=>FN});var $E=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),ON=$E.reduce((r,e,t)=>(r[t]=e,r),[]),MN=$E.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function BN(r){return r.reduce((e,t)=>(e+=ON[t],e),"")}function UN(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=MN[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var FN=Ua({prefix:"\u{1F680}",name:"base256emoji",encode:BN,decode:UN});var Zg={};$(Zg,{base32:()=>Fa,base32hex:()=>qN,base32hexpad:()=>zN,base32hexpadupper:()=>GN,base32hexupper:()=>HN,base32pad:()=>VN,base32padupper:()=>KN,base32upper:()=>$N,base32z:()=>WN});var Fa=Ge({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$N=Ge({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),VN=Ge({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),KN=Ge({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),qN=Ge({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),HN=Ge({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),zN=Ge({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),GN=Ge({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),WN=Ge({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Jg={};$(Jg,{base36:()=>Cu,base36upper:()=>jN});var Cu=qo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),jN=qo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var e6={};$(e6,{base58btc:()=>wn,base58flickr:()=>YN});var wn=qo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),YN=qo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var t6={};$(t6,{base64:()=>QN,base64pad:()=>XN,base64url:()=>ZN,base64urlpad:()=>JN});var QN=Ge({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),XN=Ge({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ZN=Ge({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),JN=Ge({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var r6={};$(r6,{base8:()=>eO});var eO=Ge({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var n6={};$(n6,{identity:()=>tO});var tO=Ua({prefix:"\0",name:"identity",encode:r=>ME(r),decode:r=>OE(r)});var Vfe=new TextEncoder,Kfe=new TextDecoder;var s6={};$(s6,{identity:()=>AO});var oO=qE,VE=128,sO=127,iO=~sO,aO=Math.pow(2,31);function qE(r,e,t){e=e||[],t=t||0;for(var n=t;r>=aO;)e[t++]=r&255|VE,r/=128;for(;r&iO;)e[t++]=r&255|VE,r>>>=7;return e[t]=r|0,qE.bytes=t-n+1,e}var cO=o6,lO=128,KE=127;function o6(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw o6.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&KE)<<o:(i&KE)*Math.pow(2,o),o+=7}while(i>=lO);return o6.bytes=s-n,t}var uO=Math.pow(2,7),dO=Math.pow(2,14),fO=Math.pow(2,21),hO=Math.pow(2,28),pO=Math.pow(2,35),mO=Math.pow(2,42),gO=Math.pow(2,49),yO=Math.pow(2,56),bO=Math.pow(2,63),wO=function(r){return r<uO?1:r<dO?2:r<fO?3:r<hO?4:r<pO?5:r<mO?6:r<gO?7:r<yO?8:r<bO?9:10},xO={encode:oO,decode:cO,encodingLength:wO},EO=xO,Iu=EO;function Tu(r,e=0){return[Iu.decode(r,e),Iu.decode.bytes]}function $a(r,e,t=0){return Iu.encode(r,e,t),e}function Va(r){return Iu.encodingLength(r)}function qa(r,e){let t=e.byteLength,n=Va(r),o=n+Va(t),s=new Uint8Array(o+t);return $a(r,s,0),$a(t,s,n),s.set(e,o),new Ka(r,t,e,s)}function HE(r){let e=no(r),[t,n]=Tu(e),[o,s]=Tu(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ka(t,o,i,e)}function zE(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&NE(r.bytes,t.bytes)}}var Ka=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var GE=0,vO="identity",WE=no;function SO(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return qa(GE,WE(r))}var AO={code:GE,name:vO,encode:WE,digest:SO};var c6={};$(c6,{sha256:()=>IO,sha512:()=>TO});var CO=20;function a6({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new i6(r,e,t,n,o)}var i6=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??CO,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?jE(n,this.code,t?.truncate):n.then(o=>jE(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function jE(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return qa(e,r)}function QE(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var IO=a6({name:"sha2-256",code:18,encode:QE("SHA-256")}),TO=a6({name:"sha2-512",code:19,encode:QE("SHA-512")});function XE(r,e){let{bytes:t,version:n}=r;return n===0?RO(t,l6(r),e??wn.encoder):LO(t,l6(r),e??Fa.encoder)}var ZE=new WeakMap;function l6(r){let e=ZE.get(r);if(e==null){let t=new Map;return ZE.set(r,t),t}return e}var k0=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Ru)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==PO)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=qa(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&zE(e.multihash,n.multihash)}toString(e){return XE(this,e)}toJSON(){return{"/":XE(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??JE(n,o,s.bytes))}else if(t[DO]===!0){let{version:n,multihash:o,code:s}=t,i=HE(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Ru)throw new Error(`Version 0 CID must use dag-pb (code: ${Ru}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=JE(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Ru,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=no(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Ka(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,f]=Tu(e.subarray(t));return t+=f,d},o=n(),s=Ru;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=_O(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return l6(s).set(n,e),s}};function _O(r,e){switch(r[0]){case"Q":{let t=e??wn;return[wn.prefix,t.decode(`${wn.prefix}${r}`)]}case wn.prefix:{let t=e??wn;return[wn.prefix,t.decode(r)]}case Fa.prefix:{let t=e??Fa;return[Fa.prefix,t.decode(r)]}case Cu.prefix:{let t=e??Cu;return[Cu.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function RO(r,e,t){let{prefix:n}=t;if(n!==wn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function LO(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Ru=112,PO=18;function JE(r,e,t){let n=Va(r),o=n+Va(e),s=new Uint8Array(o+t.byteLength);return $a(r,s,0),$a(e,s,n),s.set(t,o),s}var DO=Symbol.for("@ipld/js-cid/CID");var u6={...n6,...Qg,...r6,...jg,...Yg,...Zg,...Jg,...e6,...t6,...Xg},uhe={...c6,...s6};function ev(r=0){return new Uint8Array(r)}function rv(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var tv=rv("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),d6=rv("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ev(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),kO={utf8:tv,"utf-8":tv,hex:u6.base16,latin1:d6,ascii:d6,binary:d6,...u6},nv=kO;function f6(r,e="utf8"){let t=nv[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function H(r){if(r!==void 0&&r!==H.REQUEST&&r!==H.RESPONSE)throw new Error("type must be REQUEST or RESPONSE");r===void 0||this.initialize(r),this.maxHeaderSize=H.maxHeaderSize}H.prototype.initialize=function(r,e){if(r!==H.REQUEST&&r!==H.RESPONSE)throw new Error("type must be REQUEST or RESPONSE");this.type=r,this.state=r+"_LINE",this.info={headers:[],upgrade:!1},this.trailers=[],this.line="",this.isChunked=!1,this.connection="",this.headerSize=0,this.body_bytes=null,this.isUserCall=!1,this.hadError=!1};H.encoding="ascii";H.maxHeaderSize=80*1024;H.REQUEST="REQUEST";H.RESPONSE="RESPONSE";var ov=H.kOnHeaders=1,h6=H.kOnHeadersComplete=2,N0=H.kOnBody=3,p6=H.kOnMessageComplete=4;H.prototype[ov]=H.prototype[h6]=H.prototype[N0]=H.prototype[p6]=function(){};var sv=!0;Object.defineProperty(H,"kOnExecute",{get:function(){return sv=!1,99}});var iv=H.methods=["DELETE","GET","HEAD","POST","PUT","CONNECT","OPTIONS","TRACE","COPY","LOCK","MKCOL","MOVE","PROPFIND","PROPPATCH","SEARCH","UNLOCK","BIND","REBIND","UNBIND","ACL","REPORT","MKACTIVITY","CHECKOUT","MERGE","M-SEARCH","NOTIFY","SUBSCRIBE","UNSUBSCRIBE","PATCH","PURGE","MKCALENDAR","LINK","UNLINK","SOURCE"],av=iv.indexOf("CONNECT");H.prototype.reinitialize=H;H.prototype.close=H.prototype.pause=H.prototype.resume=H.prototype.remove=H.prototype.free=function(){};H.prototype._compatMode0_11=!1;H.prototype.getAsyncId=function(){return 0};var NO={REQUEST_LINE:!0,RESPONSE_LINE:!0,HEADER:!0};H.prototype.execute=function(r,e,t){if(!(this instanceof H))throw new TypeError("not a HTTPParser");e=e||0,t=typeof t=="number"?t:r.length,this.chunk=r,this.offset=e;var n=this.end=e+t;try{for(;this.offset<n&&!this[this.state](););}catch(o){if(this.isUserCall)throw o;return this.hadError=!0,o}return this.chunk=null,t=this.offset-e,NO[this.state]&&(this.headerSize+=t,this.headerSize>(this.maxHeaderSize||H.maxHeaderSize))?new Error("max header size exceeded"):t};var OO={REQUEST_LINE:!0,RESPONSE_LINE:!0,BODY_RAW:!0};H.prototype.finish=function(){if(!this.hadError){if(!OO[this.state])return new Error("invalid state for EOF");this.state==="BODY_RAW"&&this.userCall()(this[p6]())}};H.prototype.consume=H.prototype.unconsume=H.prototype.getCurrentBuffer=function(){};H.prototype.userCall=function(){this.isUserCall=!0;var r=this;return function(e){return r.isUserCall=!1,e}};H.prototype.nextRequest=function(){this.userCall()(this[p6]()),this.reinitialize(this.type)};H.prototype.consumeLine=function(){for(var r=this.end,e=this.chunk,t=this.offset;t<r;t++)if(e[t]===10){var n=this.line+f6(e.subarray(this.offset,t),H.encoding);return n.charAt(n.length-1)==="\r"&&(n=n.substr(0,n.length-1)),this.line="",this.offset=t+1,n}this.line+=f6(e.subarray(this.offset,this.end),H.encoding),this.offset=this.end};var MO=/^([^: \t]+):[ \t]*((?:.*[^ \t])|)/,BO=/^[ \t]+(.*[^ \t])/;H.prototype.parseHeader=function(r,e){if(r.indexOf("\r")!==-1)throw O0("HPE_LF_EXPECTED");var t=MO.exec(r),n=t&&t[1];if(n)e.push(n),e.push(t[2]);else{var o=BO.exec(r);o&&e.length&&(e[e.length-1]&&(e[e.length-1]+=" "),e[e.length-1]+=o[1])}};var UO=/^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/;H.prototype.REQUEST_LINE=function(){var r=this.consumeLine();if(r){var e=UO.exec(r);if(e===null)throw O0("HPE_INVALID_CONSTANT");if(this.info.method=this._compatMode0_11?e[1]:iv.indexOf(e[1]),this.info.method===-1)throw new Error("invalid request method");this.info.url=e[2],this.info.versionMajor=+e[3],this.info.versionMinor=+e[4],this.body_bytes=0,this.state="HEADER"}};var FO=/^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/;H.prototype.RESPONSE_LINE=function(){var r=this.consumeLine();if(r){var e=FO.exec(r);if(e===null)throw O0("HPE_INVALID_CONSTANT");this.info.versionMajor=+e[1],this.info.versionMinor=+e[2];var t=this.info.statusCode=+e[3];this.info.statusMessage=e[4],((t/100|0)===1||t===204||t===304)&&(this.body_bytes=0),this.state="HEADER"}};H.prototype.shouldKeepAlive=function(){if(this.info.versionMajor>0&&this.info.versionMinor>0){if(this.connection.indexOf("close")!==-1)return!1}else if(this.connection.indexOf("keep-alive")===-1)return!1;return!!(this.body_bytes!==null||this.isChunked)};H.prototype.HEADER=function(){var r=this.consumeLine();if(r!==void 0){var e=this.info;if(r)this.parseHeader(r,e.headers);else{for(var t=e.headers,n=!1,o,s=!1,i=0;i<t.length;i+=2)switch(t[i].toLowerCase()){case"transfer-encoding":this.isChunked=t[i+1].toLowerCase()==="chunked";break;case"content-length":if(o=+t[i+1],n){if(o!==this.body_bytes)throw O0("HPE_UNEXPECTED_CONTENT_LENGTH")}else n=!0,this.body_bytes=o;break;case"connection":this.connection+=t[i+1].toLowerCase();break;case"upgrade":s=!0;break}this.isChunked&&n&&(n=!1,this.body_bytes=null),s&&this.connection.indexOf("upgrade")!=-1?e.upgrade=this.type===H.REQUEST||e.statusCode===101:e.upgrade=e.method===av,this.isChunked&&e.upgrade&&(this.isChunked=!1),e.shouldKeepAlive=this.shouldKeepAlive();var a;if(sv?a=this.userCall()(this[h6](e)):a=this.userCall()(this[h6](e.versionMajor,e.versionMinor,e.headers,e.method,e.url,e.statusCode,e.statusMessage,e.upgrade,e.shouldKeepAlive)),a===2)return this.nextRequest(),!0;if(this.isChunked&&!a)this.state="BODY_CHUNKHEAD";else{if(a||this.body_bytes===0)return this.nextRequest(),e.upgrade;this.body_bytes===null?this.state="BODY_RAW":this.state="BODY_SIZED"}}}};H.prototype.BODY_CHUNKHEAD=function(){var r=this.consumeLine();r!==void 0&&(this.body_bytes=parseInt(r,16),this.body_bytes?this.state="BODY_CHUNK":this.state="BODY_CHUNKTRAILERS")};H.prototype.BODY_CHUNK=function(){var r=Math.min(this.end-this.offset,this.body_bytes);this.userCall()(this[N0](this.chunk.slice(this.offset,this.offset+r),0,r)),this.offset+=r,this.body_bytes-=r,this.body_bytes||(this.state="BODY_CHUNKEMPTYLINE")};H.prototype.BODY_CHUNKEMPTYLINE=function(){var r=this.consumeLine();if(r!==void 0){if(r!=="")throw new Error("Expected empty line");this.state="BODY_CHUNKHEAD"}};H.prototype.BODY_CHUNKTRAILERS=function(){var r=this.consumeLine();r!==void 0&&(r?this.parseHeader(r,this.trailers):(this.trailers.length&&this.userCall()(this[ov](this.trailers,"")),this.nextRequest()))};H.prototype.BODY_RAW=function(){this.userCall()(this[N0](this.chunk.slice(this.offset,this.end),0,this.end-this.offset)),this.offset=this.end};H.prototype.BODY_SIZED=function(){var r=Math.min(this.end-this.offset,this.body_bytes);this.userCall()(this[N0](this.chunk.slice(this.offset,this.offset+r),0,r)),this.offset+=r,this.body_bytes-=r,this.body_bytes||this.nextRequest()};["Headers","HeadersComplete","Body","MessageComplete"].forEach(function(r){var e=H["kOn"+r];Object.defineProperty(H.prototype,"on"+r,{get:function(){return this[e]},set:function(t){return this._compatMode0_11=!0,av="CONNECT",this[e]=t}})});function O0(r){var e=new Error("Parse Error");return e.code=r,e}var $O=[6,53,56,54,55];function cv(r){return dv("sni",r)?.value}function lv(r){let e=dv("tcp",r)?.value;return e==null?"":`:${e}`}function dv(r,e){return e.find(t=>t.name===r)}function uv(r){return r.some(({code:e})=>e===448)}function Gr(r,e){let t=fv[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var fv={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Gr(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Gr(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Gr(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Gr(t,e)}`},http:(r,e)=>{let t=uv(e),n=cv(e),o=lv(e);if(t&&n!=null)return`https://${n}${o}`;let s=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Gr(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Gr(t,e),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Gr(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Gr(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Gr(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=uv(e),n=cv(e),o=lv(e);if(t&&n!=null)return`wss://${n}${o}`;let s=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Gr(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Gr(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function M0(r,e){let n=V(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=fv[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return e?.assumeHttp!==!1&&$O.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var hv="[a-fA-F\\d:]",Ho=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${hv})|(?<=${hv})(?=\\s|$))`:"",Wr="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",Je="[a-fA-F\\d]{1,4}",B0=`
|
|
32
32
|
(?:
|
|
33
33
|
(?:${Je}:){7}(?:${Je}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
34
34
|
(?:${Je}:){6}(?:${Wr}|:${Je}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
|