helia 4.2.2 → 4.2.3

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 CHANGED
@@ -19,7 +19,7 @@ if (cid) {
19
19
  `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
20
20
  ${e.join(`
21
21
  `)}`:`${t} :`}};im=go;W.Constructed=im;go.NAME="CONSTRUCTED";var Dl=class extends Lt{fromBER(e,t,n){return t}toBER(e){return Gr}};Dl.override="EndOfContentValueBlock";var am,Tl=class extends Et{constructor(e={}){super(e,Dl),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};am=Tl;W.EndOfContent=am;Tl.NAME=Da;var cm,yo=class extends Et{constructor(e={}){super(e,Lt),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}`}};cm=yo;W.Null=cm;yo.NAME="NULL";var kl=class extends Fn(Lt){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=we.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=we.BufferSourceConverter.toUint8Array(e);return Un(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,n0.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};kl.NAME="BooleanValueBlock";var lm,Cl=class extends Et{constructor(e={}){super(e,kl),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};lm=Cl;W.Boolean=lm;Cl.NAME="BOOLEAN";var Nl=class extends Fn(un){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=un.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Da){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==rm)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}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}}};Nl.NAME="OctetStringValueBlock";var um,Bn=class r extends Et{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},Nl),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){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 s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=iu(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?go.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${we.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return we.BufferSourceConverter.concat(e)}};um=Bn;W.OctetString=um;Bn.NAME=rm;var Ll=class extends Fn(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){if(!n)return t;let o=-1;if(this.isConstructed){if(o=un.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Da){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==nm)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let s=we.BufferSourceConverter.toUint8Array(e);if(!Un(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=iu(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.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)return Gr;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}}};Ll.NAME="BitStringValueBlock";var dm,ii=class extends Et{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},Ll),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return go.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};dm=ii;W.BitString=dm;ii.NAME=nm;var fm;function tS(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,d=c<i?i:c,u=0;for(let h=d;h>=0;h--,u++){switch(!0){case u<a.length:l=s[i-u]+a[c-u]+t[0];break;default:l=s[i-u]+t[0]}switch(t[0]=l/10,!0){case u>=s.length:s=xl(new Uint8Array([l%10]),s);break;default:s[i-u]=l%10}}return t[0]>0&&(s=xl(t,s)),s}function tm(r){if(r>=Aa.length)for(let e=Aa.length;e<=r;e++){let t=new Uint8Array([0]),n=Aa[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=xl(t,n)),Aa.push(n)}return Aa[r]}function rS(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,d=0;for(let u=c;u>=0;u--,d++)switch(l=s[i-d]-a[c-d]-t,!0){case l<0:t=1,s[i-d]=l+10;break;default:t=0,s[i-d]=l}if(t>0)for(let u=i-c+1;u>=0;u--,d++)if(l=s[i-d]-t,l<0)t=1,s[i-d]=l+10;else{t=0,s[i-d]=l;break}return s.slice()}var Ta=class extends Fn(Lt){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}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=n0.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Z8(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?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++){if((o&1)===1)switch(n){case e:t=rS(tm(n),t),i="-";break;default:t=tS(t,tm(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=em.charAt(t[c]));return a===!1&&(i+=em.charAt(0)),i}};fm=Ta;Ta.NAME="IntegerValueBlock";Object.defineProperty(fm.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var hm,at=class r extends Et{constructor(e={}){super(e,Ta),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return vl(),BigInt(this.valueBlock.toString())}static fromBigInt(e){vl();let t=BigInt(e),n=new Ia,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(we.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${we.Convert.ToHex(a)}`)+t,d=we.BufferSourceConverter.toUint8Array(we.Convert.FromHex(l.toString(16)));d[0]|=128,n.write(d)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};hm=at;W.Integer=hm;at.NAME="INTEGER";var pm,Pl=class extends at{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};pm=Pl;W.Enumerated=pm;Pl.NAME="ENUMERATED";var ka=class extends Fn(Lt){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=we.BufferSourceConverter.toUint8Array(e);if(!Un(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));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?(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=ls(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){vl();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=mo(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Gr;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=we.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}}};ka.NAME="sidBlock";var Ol=class extends Lt{constructor({value:e=ai,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new ka;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,Gr;t.push(o)}return o0(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 ka;if(o>Number.MAX_SAFE_INTEGER){vl();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}};Ol.NAME="ObjectIdentifierValueBlock";var mm,qr=class extends Et{constructor(e={}){super(e,Ol),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};mm=qr;W.ObjectIdentifier=mm;qr.NAME="OBJECT IDENTIFIER";var Ca=class extends Fn(On){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=we.BufferSourceConverter.toUint8Array(e);if(!Un(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));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?(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=ls(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=mo(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Gr;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=we.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Ca.NAME="relativeSidBlock";var Bl=class extends Lt{constructor({value:e=ai,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Ca;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,Gr;n.push(s)}return o0(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 Ca;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}};Bl.NAME="RelativeObjectIdentifierValueBlock";var gm,Ml=class extends Et{constructor(e={}){super(e,Bl),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};gm=Ml;W.RelativeObjectIdentifier=gm;Ml.NAME="RelativeObjectIdentifier";var ym,mt=class extends go{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};ym=mt;W.Sequence=ym;mt.NAME="SEQUENCE";var wm,Ul=class extends go{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};wm=Ul;W.Set=wm;Ul.NAME="SET";var Fl=class extends Fn(Lt){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ai}toJSON(){return{...super.toJSON(),value:this.value}}};Fl.NAME="StringValueBlock";var Vl=class extends Fl{};Vl.NAME="SimpleStringValueBlock";var Ut=class extends _l{constructor({...e}={}){super(e,Vl)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,we.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}};Ut.NAME="SIMPLE STRING";var Kl=class extends Ut{fromBuffer(e){this.valueBlock.valueHexView=we.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=we.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=we.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(we.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Kl.NAME="Utf8StringValueBlock";var Em,Mn=class extends Kl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Em=Mn;W.Utf8String=Em;Mn.NAME="UTF8String";var $l=class extends Ut{fromBuffer(e){this.valueBlock.value=we.Convert.ToUtf16String(e),this.valueBlock.valueHexView=we.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(we.Convert.FromUtf16String(e))}};$l.NAME="BmpStringValueBlock";var bm,Hl=class extends $l{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};bm=Hl;W.BmpString=bm;Hl.NAME="BMPString";var ql=class extends Ut{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=mo(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}};ql.NAME="UniversalStringValueBlock";var xm,Gl=class extends ql{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};xm=Gl;W.UniversalString=xm;Gl.NAME="UniversalString";var vm,Wl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};vm=Wl;W.NumericString=vm;Wl.NAME="NumericString";var Rm,zl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Rm=zl;W.PrintableString=Rm;zl.NAME="PrintableString";var Sm,Yl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Sm=Yl;W.TeletexString=Sm;Yl.NAME="TeletexString";var _m,Xl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};_m=Xl;W.VideotexString=_m;Xl.NAME="VideotexString";var Am,Ql=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Am=Ql;W.IA5String=Am;Ql.NAME="IA5String";var Im,jl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Im=jl;W.GraphicString=Im;jl.NAME="GraphicString";var Dm,Na=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Dm=Na;W.VisibleString=Dm;Na.NAME="VisibleString";var Tm,Zl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Tm=Zl;W.GeneralString=Tm;Zl.NAME="GeneralString";var km,Jl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};km=Jl;W.CharacterString=km;Jl.NAME="CharacterString";var Cm,La=class extends Na{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,we.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]=zt(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=zt(this.month,2),t[2]=zt(this.day,2),t[3]=zt(this.hour,2),t[4]=zt(this.minute,2),t[5]=zt(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}}};Cm=La;W.UTCTime=Cm;La.NAME="UTCTime";var Nm,eu=class extends La{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(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}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 u=new Number(e[e.length-1]);if(isNaN(u.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 u=1,h=n.indexOf("+"),f="";if(h===-1&&(h=n.indexOf("-"),u=-1),h!==-1){if(f=n.substring(h+1),n=n.substring(0,h),f.length!==2&&f.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(f.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=u*p,f.length===4){if(p=parseInt(f.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=u*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let u=new Number(`0${n.substring(l)}`);if(isNaN(u.valueOf()))throw new Error("Wrong input string for conversion");s=u.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 u=60*s;this.minute=Math.floor(u),u=60*(u-this.minute),this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=60*s;this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=1e3*s;this.millisecond=Math.floor(u)}break;default:throw new Error("Wrong input string for conversion")}let d=i.exec(o);if(d===null)throw new Error("Wrong input string for conversion");for(let u=1;u<d.length;u++)switch(u){case 1:this.year=parseInt(d[u],10);break;case 2:this.month=parseInt(d[u],10);break;case 3:this.day=parseInt(d[u],10);break;case 4:this.hour=parseInt(d[u],10)+a;break;case 5:this.minute=parseInt(d[u],10)+c;break;case 6:this.second=parseInt(d[u],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let u=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=u.getUTCFullYear(),this.month=u.getUTCMonth(),this.day=u.getUTCDay(),this.hour=u.getUTCHours(),this.minute=u.getUTCMinutes(),this.second=u.getUTCSeconds(),this.millisecond=u.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(zt(this.year,4)),t.push(zt(this.month,2)),t.push(zt(this.day,2)),t.push(zt(this.hour,2)),t.push(zt(this.minute,2)),t.push(zt(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(zt(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Nm=eu;W.GeneralizedTime=Nm;eu.NAME="GeneralizedTime";var Lm,tu=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Lm=tu;W.DATE=Lm;tu.NAME="DATE";var Pm,ru=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Pm=ru;W.TimeOfDay=Pm;ru.NAME="TimeOfDay";var Om,nu=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Om=nu;W.DateTime=Om;nu.NAME="DateTime";var Bm,ou=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Bm=ou;W.Duration=Bm;ou.NAME="Duration";var Mm,su=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Mm=su;W.TIME=Mm;su.NAME="TIME";function oS(r){let{result:e}=ci(r),t=e.valueBlock.value;return{n:O(dn(t[1].toBigInt()),"base64url"),e:O(dn(t[2].toBigInt()),"base64url"),d:O(dn(t[3].toBigInt()),"base64url"),p:O(dn(t[4].toBigInt()),"base64url"),q:O(dn(t[5].toBigInt()),"base64url"),dp:O(dn(t[6].toBigInt()),"base64url"),dq:O(dn(t[7].toBigInt()),"base64url"),qi:O(dn(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function sS(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new g("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new mt({value:[new at({value:0}),at.fromBigInt(fn(M(r.n,"base64url"))),at.fromBigInt(fn(M(r.e,"base64url"))),at.fromBigInt(fn(M(r.d,"base64url"))),at.fromBigInt(fn(M(r.p,"base64url"))),at.fromBigInt(fn(M(r.q,"base64url"))),at.fromBigInt(fn(M(r.dp,"base64url"))),at.fromBigInt(fn(M(r.dq,"base64url"))),at.fromBigInt(fn(M(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function iS(r){let{result:e}=ci(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:O(dn(t[0].toBigInt()),"base64url"),e:O(dn(t[1].toBigInt()),"base64url")}}function aS(r){if(r.n==null||r.e==null)throw new g("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new mt({value:[new mt({value:[new qr({value:"1.2.840.113549.1.1.1"}),new yo]}),new ii({valueHex:new mt({value:[at.fromBigInt(fn(M(r.n,"base64url"))),at.fromBigInt(fn(M(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function dn(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function fn(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var cS=16,i0=32,a0=1e4;async function lS(r,e){let t=qe.get(),o=new mt({value:[new at({value:0}),new mt({value:[new qr({value:"1.2.840.113549.1.1.1"}),new yo]}),new Bn({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=pt(cS),a=await t0(uo,e,i,{c:a0,dkLen:i0}),c=pt(16),l=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),d=await t.subtle.encrypt({name:"AES-CBC",iv:c},l,s),u=new mt({value:[new Bn({valueHex:i}),new at({value:a0}),new at({value:i0}),new mt({value:[new qr({value:"1.2.840.113549.2.11"}),new yo]})]}),h=new mt({value:[new qr({value:"1.2.840.113549.1.5.13"}),new mt({value:[new mt({value:[new qr({value:"1.2.840.113549.1.5.12"}),u]}),new mt({value:[new qr({value:"2.16.840.1.101.3.4.1.42"}),new Bn({valueHex:c})]})]})]}),p=new mt({value:[h,new Bn({valueHex:d})]}).toBER(),m=new Uint8Array(p,0,p.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...O(m,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
22
- `)}async function c0(r,e){let t=qe.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=M(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=ci(o),{iv:i,salt:a,iterations:c,keySize:l,cipherText:d}=uS(s),u=await t0(uo,e,a,{c,dkLen:l}),h=await t.subtle.importKey("raw",u,"AES-CBC",!1,["decrypt"]),f=Pa(await t.subtle.decrypt({name:"AES-CBC",iv:i},h,d)),{result:p}=ci(f);n=Um(p)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=M(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=ci(o);n=Um(s)}else throw new g("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return l0(n)}function uS(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new g("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");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 g("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Pa(s.valueBlock.value[0].getValue()),a=a0,c=i0;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 g("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let l=e.valueBlock.value[1].valueBlock.value[1],d=l.valueBlock.value[0].toString();if(d!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(d!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(d!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(d!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(d!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new g("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let u=Pa(l.valueBlock.value[1].getValue());return{cipherText:Pa(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:u}}function Um(r){return Pa(r.valueBlock.value[2].getValue())}function Pa(r){return new Uint8Array(r,0,r.byteLength)}async function Fm(r){let e=await qe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await $m(e);return{privateKey:t[0],publicKey:t[1]}}async function u0(r){let t=[await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await dS(r)],n=await $m({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Vm(r,e){let t=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await qe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Km(r,e,t){let n=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return qe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function $m(r){if(r.privateKey==null||r.publicKey==null)throw new g("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([qe.get().subtle.exportKey("jwk",r.privateKey),qe.get().subtle.exportKey("jwk",r.publicKey)])}async function dS(r){return qe.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function au(r){if(r.kty!=="RSA")throw new g("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new g("invalid key modulus","ERR_INVALID_KEY_MODULUS");return M(r.n,"base64url").length*8}var ds=8192,us=class{_key;constructor(e){this._key=e}verify(e,t){return Km(this._key,t,e)}marshal(){return wo.jwkToPkix(this._key)}get bytes(){return $r.encode({Type:Ke.RSA,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}},Eo=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return pt(16)}sign(e){return Vm(this._key,e)}get public(){if(this._publicKey==null)throw new g("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new us(this._publicKey)}marshal(){return wo.jwkToPkcs1(this._key)}get bytes(){return Hr.encode({Type:Ke.RSA,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return O(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return wo.exportToPem(this,e);if(t==="libp2p-key")return ri(this.bytes,e);throw new g(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function l0(r){let e=wo.pkcs1ToJwk(r);if(au(e)>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await u0(e);return new Eo(t.privateKey,t.publicKey)}function hS(r){let e=wo.pkixToJwk(r);if(au(e)>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new us(e)}async function pS(r){if(au(r)>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await u0(r);return new Eo(e.privateKey,e.publicKey)}async function mS(r){if(r>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Fm(r);return new Eo(e.privateKey,e.publicKey)}var g0={};pe(g0,{Secp256k1PrivateKey:()=>ps,Secp256k1PublicKey:()=>hs,generateKeyPair:()=>DS,unmarshalSecp256k1PrivateKey:()=>AS,unmarshalSecp256k1PublicKey:()=>IS});var gS=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),bo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xo=new Uint32Array(64),f0=class extends ao{constructor(){super(64,32,8,!1),this.A=bo[0]|0,this.B=bo[1]|0,this.C=bo[2]|0,this.D=bo[3]|0,this.E=bo[4]|0,this.F=bo[5]|0,this.G=bo[6]|0,this.H=bo[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)xo[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let h=xo[u-15],f=xo[u-2],p=Ur(h,7)^Ur(h,18)^h>>>3,m=Ur(f,17)^Ur(f,19)^f>>>10;xo[u]=m+xo[u-7]+p+xo[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){let h=Ur(a,6)^Ur(a,11)^Ur(a,25),f=d+h+il(a,c,l)+gS[u]+xo[u]|0,m=(Ur(n,2)^Ur(n,13)^Ur(n,22))+al(n,o,s)|0;d=l,l=c,c=a,a=i+f|0,i=s,s=o,o=n,n=f+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,l,d)}roundClean(){xo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var vo=Zs(()=>new f0);function yS(r){let e=va(r);Rr(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:wS,hexToBytes:ES}=ul,fs={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=fs;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:wS(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=fs,t=typeof r=="string"?ES(r):r;Js(t);let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:s}=fs._parseInt(t.subarray(2)),{d:i,l:a}=fs._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{let d=l.toString(16);return d.length&1?`0${d}`:d},n=e(t(r.s)),o=e(t(r.r)),s=n.length/2,i=o.length/2,a=t(s),c=t(i);return`30${t(i+s+4)}02${c}${o}02${a}${n}`}},Vn=BigInt(0),_r=BigInt(1),mU=BigInt(2),Hm=BigInt(3),gU=BigInt(4);function bS(r){let e=yS(r),{Fp:t}=e,n=e.toBytes||((p,m,y)=>{let w=m.toAffine();return kn(Uint8Array.from([4]),t.toBytes(w.x),t.toBytes(w.y))}),o=e.fromBytes||(p=>{let m=p.subarray(1),y=t.fromBytes(m.subarray(0,t.BYTES)),w=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:y,y:w}});function s(p){let{a:m,b:y}=e,w=t.sqr(p),b=t.mul(w,p);return t.add(t.add(b,t.mul(p,m)),y)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(p){return typeof p=="bigint"&&Vn<p&&p<e.n}function a(p){if(!i(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:w,n:b}=e;if(m&&typeof p!="bigint"){if(fo(p)&&(p=In(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let E;try{E=typeof p=="bigint"?p:Dn(Fe("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return w&&(E=De(E,b)),a(E),E}let l=new Map;function d(p){if(!(p instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(m,y,w){if(this.px=m,this.py=y,this.pz=w,m==null||!t.isValid(m))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(w==null||!t.isValid(w))throw new Error("z required")}static fromAffine(m){let{x:y,y:w}=m||{};if(!m||!t.isValid(y)||!t.isValid(w))throw new Error("invalid affine point");if(m instanceof u)throw new Error("projective point not allowed");let b=E=>t.eql(E,t.ZERO);return b(y)&&b(w)?u.ZERO:new u(y,w,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=t.invertBatch(m.map(w=>w.pz));return m.map((w,b)=>w.toAffine(y[b])).map(u.fromAffine)}static fromHex(m){let y=u.fromAffine(o(Fe("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return u.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not FE");let w=t.sqr(y),b=s(m);if(!t.eql(w,b))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){d(m);let{px:y,py:w,pz:b}=this,{px:E,py:x,pz:v}=m,I=t.eql(t.mul(y,v),t.mul(E,b)),S=t.eql(t.mul(w,v),t.mul(x,b));return I&&S}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,w=t.mul(y,Hm),{px:b,py:E,pz:x}=this,v=t.ZERO,I=t.ZERO,S=t.ZERO,R=t.mul(b,b),T=t.mul(E,E),P=t.mul(x,x),N=t.mul(b,E);return N=t.add(N,N),S=t.mul(b,x),S=t.add(S,S),v=t.mul(m,S),I=t.mul(w,P),I=t.add(v,I),v=t.sub(T,I),I=t.add(T,I),I=t.mul(v,I),v=t.mul(N,v),S=t.mul(w,S),P=t.mul(m,P),N=t.sub(R,P),N=t.mul(m,N),N=t.add(N,S),S=t.add(R,R),R=t.add(S,R),R=t.add(R,P),R=t.mul(R,N),I=t.add(I,R),P=t.mul(E,x),P=t.add(P,P),R=t.mul(P,N),v=t.sub(v,R),S=t.mul(P,T),S=t.add(S,S),S=t.add(S,S),new u(v,I,S)}add(m){d(m);let{px:y,py:w,pz:b}=this,{px:E,py:x,pz:v}=m,I=t.ZERO,S=t.ZERO,R=t.ZERO,T=e.a,P=t.mul(e.b,Hm),N=t.mul(y,E),B=t.mul(w,x),k=t.mul(b,v),X=t.add(y,w),D=t.add(E,x);X=t.mul(X,D),D=t.add(N,B),X=t.sub(X,D),D=t.add(y,b);let L=t.add(E,v);return D=t.mul(D,L),L=t.add(N,k),D=t.sub(D,L),L=t.add(w,b),I=t.add(x,v),L=t.mul(L,I),I=t.add(B,k),L=t.sub(L,I),R=t.mul(T,D),I=t.mul(P,k),R=t.add(I,R),I=t.sub(B,R),R=t.add(B,R),S=t.mul(I,R),B=t.add(N,N),B=t.add(B,N),k=t.mul(T,k),D=t.mul(P,D),B=t.add(B,k),k=t.sub(N,k),k=t.mul(T,k),D=t.add(D,k),N=t.mul(B,D),S=t.add(S,N),N=t.mul(L,D),I=t.mul(X,I),I=t.sub(I,N),N=t.mul(X,B),R=t.mul(L,R),R=t.add(R,N),new u(I,S,R)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return f.wNAFCached(this,l,m,y=>{let w=t.invertBatch(y.map(b=>b.pz));return y.map((b,E)=>b.toAffine(w[E])).map(u.fromAffine)})}multiplyUnsafe(m){let y=u.ZERO;if(m===Vn)return y;if(a(m),m===_r)return this;let{endo:w}=e;if(!w)return f.unsafeLadder(this,m);let{k1neg:b,k1:E,k2neg:x,k2:v}=w.splitScalar(m),I=y,S=y,R=this;for(;E>Vn||v>Vn;)E&_r&&(I=I.add(R)),v&_r&&(S=S.add(R)),R=R.double(),E>>=_r,v>>=_r;return b&&(I=I.negate()),x&&(S=S.negate()),S=new u(t.mul(S.px,w.beta),S.py,S.pz),I.add(S)}multiply(m){a(m);let y=m,w,b,{endo:E}=e;if(E){let{k1neg:x,k1:v,k2neg:I,k2:S}=E.splitScalar(y),{p:R,f:T}=this.wNAF(v),{p:P,f:N}=this.wNAF(S);R=f.constTimeNegate(x,R),P=f.constTimeNegate(I,P),P=new u(t.mul(P.px,E.beta),P.py,P.pz),w=R.add(P),b=T.add(N)}else{let{p:x,f:v}=this.wNAF(y);w=x,b=v}return u.normalizeZ([w,b])[0]}multiplyAndAddUnsafe(m,y,w){let b=u.BASE,E=(v,I)=>I===Vn||I===_r||!v.equals(b)?v.multiplyUnsafe(I):v.multiply(I),x=E(this,y).add(E(m,w));return x.is0()?void 0:x}toAffine(m){let{px:y,py:w,pz:b}=this,E=this.is0();m==null&&(m=E?t.ONE:t.inv(b));let x=t.mul(y,m),v=t.mul(w,m),I=t.mul(b,m);if(E)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x,y:v}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===_r)return!0;if(y)return y(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===_r?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return In(this.toRawBytes(m))}}u.BASE=new u(e.Gx,e.Gy,t.ONE),u.ZERO=new u(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,f=hl(u,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function xS(r){let e=va(r);return Rr(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function qm(r){let e=xS(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(D){return Vn<D&&D<t.ORDER}function a(D){return De(D,n)}function c(D){return dl(D,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:d,weierstrassEquation:u,isWithinCurveOrder:h}=bS({...e,toBytes(D,L,$){let C=L.toAffine(),A=t.toBytes(C.x),U=kn;return $?U(Uint8Array.from([L.hasEvenY()?2:3]),A):U(Uint8Array.from([4]),A,t.toBytes(C.y))},fromBytes(D){let L=D.length,$=D[0],C=D.subarray(1);if(L===o&&($===2||$===3)){let A=Dn(C);if(!i(A))throw new Error("Point is not on curve");let U=u(A),V;try{V=t.sqrt(U)}catch(ie){let de=ie instanceof Error?": "+ie.message:"";throw new Error("Point is not on curve"+de)}let q=(V&_r)===_r;return($&1)===1!==q&&(V=t.neg(V)),{x:A,y:V}}else if(L===s&&$===4){let A=t.fromBytes(C.subarray(0,t.BYTES)),U=t.fromBytes(C.subarray(t.BYTES,2*t.BYTES));return{x:A,y:U}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),f=D=>In(ho(D,e.nByteLength));function p(D){let L=n>>_r;return D>L}function m(D){return p(D)?a(-D):D}let y=(D,L,$)=>Dn(D.slice(L,$));class w{constructor(L,$,C){this.r=L,this.s=$,this.recovery=C,this.assertValidity()}static fromCompact(L){let $=e.nByteLength;return L=Fe("compactSignature",L,$*2),new w(y(L,0,$),y(L,$,2*$))}static fromDER(L){let{r:$,s:C}=fs.toSig(Fe("DER",L));return new w($,C)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(L){return new w(this.r,this.s,L)}recoverPublicKey(L){let{r:$,s:C,recovery:A}=this,U=S(Fe("msgHash",L));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let V=A===2||A===3?$+e.n:$;if(V>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let q=A&1?"03":"02",se=l.fromHex(q+f(V)),ie=c(V),de=a(-U*ie),ae=a(C*ie),ue=l.BASE.multiplyAndAddUnsafe(se,de,ae);if(!ue)throw new Error("point at infinify");return ue.assertValidity(),ue}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return is(this.toDERHex())}toDERHex(){return fs.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return is(this.toCompactHex())}toCompactHex(){return f(this.r)+f(this.s)}}let b={isValidPrivateKey(D){try{return d(D),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let D=Gh(e.n);return A8(e.randomBytes(D),e.n)},precompute(D=8,L=l.BASE){return L._setWindowSize(D),L.multiply(BigInt(3)),L}};function E(D,L=!0){return l.fromPrivateKey(D).toRawBytes(L)}function x(D){let L=fo(D),$=typeof D=="string",C=(L||$)&&D.length;return L?C===o||C===s:$?C===2*o||C===2*s:D instanceof l}function v(D,L,$=!0){if(x(D))throw new Error("first arg must be private key");if(!x(L))throw new Error("second arg must be public key");return l.fromHex(L).multiply(d(D)).toRawBytes($)}let I=e.bits2int||function(D){let L=Dn(D),$=D.length*8-e.nBitLength;return $>0?L>>BigInt($):L},S=e.bits2int_modN||function(D){return a(I(D))},R=xa(e.nBitLength);function T(D){if(typeof D!="bigint")throw new Error("bigint expected");if(!(Vn<=D&&D<R))throw new Error(`bigint expected < 2^${e.nBitLength}`);return ho(D,e.nByteLength)}function P(D,L,$=N){if(["recovered","canonical"].some(Le=>Le in $))throw new Error("sign() legacy options not supported");let{hash:C,randomBytes:A}=e,{lowS:U,prehash:V,extraEntropy:q}=$;U==null&&(U=!0),D=Fe("msgHash",D),V&&(D=Fe("prehashed msgHash",C(D)));let se=S(D),ie=d(L),de=[T(ie),T(se)];if(q!=null&&q!==!1){let Le=q===!0?A(t.BYTES):q;de.push(Fe("extraEntropy",Le))}let ae=kn(...de),ue=se;function Me(Le){let yt=I(Le);if(!h(yt))return;let wt=c(yt),lt=l.BASE.multiply(yt).toAffine(),Tt=a(lt.x);if(Tt===Vn)return;let xn=a(wt*a(ue+Tt*ie));if(xn===Vn)return;let Go=(lt.x===Tt?0:2)|Number(lt.y&_r),fa=xn;return U&&p(xn)&&(fa=m(xn),Go^=1),new w(Tt,fa,Go)}return{seed:ae,k2sig:Me}}let N={lowS:e.lowS,prehash:!1},B={lowS:e.lowS,prehash:!1};function k(D,L,$=N){let{seed:C,k2sig:A}=P(D,L,$),U=e;return Vh(U.hash.outputLen,U.nByteLength,U.hmac)(C,A)}l.BASE._setWindowSize(8);function X(D,L,$,C=B){let A=D;if(L=Fe("msgHash",L),$=Fe("publicKey",$),"strict"in C)throw new Error("options.strict was renamed to lowS");let{lowS:U,prehash:V}=C,q,se;try{if(typeof A=="string"||fo(A))try{q=w.fromDER(A)}catch(lt){if(!(lt instanceof fs.Err))throw lt;q=w.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:lt,s:Tt}=A;q=new w(lt,Tt)}else throw new Error("PARSE");se=l.fromHex($)}catch(lt){if(lt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(U&&q.hasHighS())return!1;V&&(L=e.hash(L));let{r:ie,s:de}=q,ae=S(L),ue=c(de),Me=a(ae*ue),Le=a(ie*ue),yt=l.BASE.multiplyAndAddUnsafe(se,Me,Le)?.toAffine();return yt?a(yt.x)===ie:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:v,sign:k,verify:X,ProjectivePoint:l,Signature:w,utils:b}}function vS(r){return{hash:r,hmac:(e,...t)=>po(r,e,sl(...t)),randomBytes:ss}}function Gm(r,e){let t=n=>qm({...r,...vS(n)});return Object.freeze({...t(e),create:t})}var Ym=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Wm=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),RS=BigInt(1),h0=BigInt(2),zm=(r,e)=>(r+e/h0)/e;function SS(r){let e=Ym,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,u=Ve(d,t,e)*d%e,h=Ve(u,t,e)*d%e,f=Ve(h,h0,e)*l%e,p=Ve(f,o,e)*f%e,m=Ve(p,s,e)*p%e,y=Ve(m,a,e)*m%e,w=Ve(y,c,e)*y%e,b=Ve(w,a,e)*m%e,E=Ve(b,t,e)*d%e,x=Ve(E,i,e)*p%e,v=Ve(x,n,e)*l%e,I=Ve(v,h0,e);if(!p0.eql(p0.sqr(I),r))throw new Error("Cannot find square root");return I}var p0=fl(Ym,void 0,void 0,{sqrt:SS}),Wr=Gm({a:BigInt(0),b:BigInt(7),Fp:p0,n:Wm,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Wm,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-RS*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=zm(s*r,e),c=zm(-n*r,e),l=De(r-a*t-c*o,e),d=De(-a*n-c*s,e),u=l>i,h=d>i;if(u&&(l=e-l),h&&(d=e-d),l>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:h,k2:d}}}},vo),_U=BigInt(0);var AU=Wr.ProjectivePoint;function Xm(){return Wr.utils.randomPrivateKey()}function Qm(r,e){let t=Ne.digest(e instanceof Uint8Array?e:e.subarray());if(vr(t))return t.then(({digest:n})=>Wr.sign(n,r).toDERRawBytes()).catch(n=>{throw new g(String(n),"ERR_INVALID_INPUT")});try{return Wr.sign(t.digest,r).toDERRawBytes()}catch(n){throw new g(String(n),"ERR_INVALID_INPUT")}}function jm(r,e,t){let n=Ne.digest(t instanceof Uint8Array?t:t.subarray());if(vr(n))return n.then(({digest:o})=>Wr.verify(e,o,r)).catch(o=>{throw new g(String(o),"ERR_INVALID_INPUT")});try{return Wr.verify(e,n.digest,r)}catch(o){throw new g(String(o),"ERR_INVALID_INPUT")}}function Zm(r){return Wr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Jm(r){try{Wr.getPublicKey(r,!0)}catch(e){throw new g(String(e),"ERR_INVALID_PRIVATE_KEY")}}function m0(r){try{Wr.ProjectivePoint.fromHex(r)}catch(e){throw new g(String(e),"ERR_INVALID_PUBLIC_KEY")}}function e6(r){try{return Wr.getPublicKey(r,!0)}catch(e){throw new g(String(e),"ERR_INVALID_PRIVATE_KEY")}}var hs=class{_key;constructor(e){m0(e),this._key=e}verify(e,t){return jm(this._key,t,e)}marshal(){return Zm(this._key)}get bytes(){return $r.encode({Type:Ke.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}async hash(){let e=Ne.digest(this.bytes),t;return vr(e)?{bytes:t}=await e:t=e.bytes,t}},ps=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??e6(e),Jm(this._key),m0(this._publicKey)}sign(e){return Qm(this._key,e)}get public(){return new hs(this._publicKey)}marshal(){return this._key}get bytes(){return Hr.encode({Type:Ke.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return O(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return ri(this.bytes,e);throw new g(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function AS(r){return new ps(r)}function IS(r){return new hs(r)}async function DS(){let r=Xm();return new ps(r)}var Kn={rsa:d0,ed25519:Jh,secp256k1:g0};function y0(r){let e=Object.keys(Kn).join(" / ");return new g(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function w0(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return Kn[r];throw y0(r)}async function Oa(r,e){return w0(r).generateKeyPair(e??2048)}async function TS(r,e,t){if(r.toLowerCase()!=="ed25519")throw new g("Seed key derivation is unimplemented for RSA or secp256k1","ERR_UNSUPPORTED_KEY_DERIVATION_TYPE");return Zh(e)}function zr(r){let e=$r.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Ke.RSA:return Kn.rsa.unmarshalRsaPublicKey(t);case Ke.Ed25519:return Kn.ed25519.unmarshalEd25519PublicKey(t);case Ke.Secp256k1:return Kn.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw y0(e.Type??"unknown")}}function E0(r,e){return e=(e??"rsa").toLowerCase(),w0(e),r.bytes}async function Ar(r){let e=Hr.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Ke.RSA:return Kn.rsa.unmarshalRsaPrivateKey(t);case Ke.Ed25519:return Kn.ed25519.unmarshalEd25519PrivateKey(t);case Ke.Secp256k1:return Kn.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw y0(e.Type??"RSA")}}function b0(r,e){return e=(e??"rsa").toLowerCase(),w0(e),r.bytes}async function li(r,e){try{let t=await G8(r,e);return await Ar(t)}catch{}if(!r.includes("BEGIN"))throw new g("Encrypted key was not a libp2p-key or a PEM file","ERR_INVALID_IMPORT_FORMAT");return c0(r,e)}var Ba=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),Ro=new Uint32Array(80),x0=class extends ao{constructor(){super(64,20,8,!1),this.A=Ba[0]|0,this.B=Ba[1]|0,this.C=Ba[2]|0,this.D=Ba[3]|0,this.E=Ba[4]|0}get(){let{A:e,B:t,C:n,D:o,E:s}=this;return[e,t,n,o,s]}set(e,t,n,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0}process(e,t){for(let c=0;c<16;c++,t+=4)Ro[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Ro[c]=ol(Ro[c-3]^Ro[c-8]^Ro[c-14]^Ro[c-16],1);let{A:n,B:o,C:s,D:i,E:a}=this;for(let c=0;c<80;c++){let l,d;c<20?(l=il(o,s,i),d=1518500249):c<40?(l=o^s^i,d=1859775393):c<60?(l=al(o,s,i),d=2400959708):(l=o^s^i,d=3395469782);let u=ol(n,5)+l+a+d+Ro[c]|0;a=i,i=s,s=ol(o,30),o=n,n=u}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,this.set(n,o,s,i,a)}roundClean(){Ro.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}},t6=Zs(()=>new x0);var r6={sha1:t6,"sha2-256":vo,"sha2-512":uo};function Ma(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(r6).join(" / ");throw new g(`Hash '${o}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let s=r6[o],i=Q8(s,r,e,{c:t,dkLen:n});return st.encode(i).substring(1)}var v0=class extends it{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Fa(r){let{name:e,metrics:t}=r,n;return t!=null?n=new v0({name:e,metrics:t}):n=new it,n}var $n=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=st.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=st.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=st.encode(e.multihash.bytes);this.blocks.set(n,t)}};function kS(r){let e=new Uint8Array(r.reduce((n,o)=>n+Se(o),0)),t=0;for(let n of r)e=$e(n,e,t),t+=Se(n);return e}var i6=kS;function R0(r){return i6([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var uu=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t=new $n,n=new Set;for(let[o,s]of this.wants.entries())try{let i=await this.blockstore.get(s.cid,e);s.wantType===rt.WantHave?i.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",s.cid),n.add(o),t.addBlock(s.cid,{data:i,prefix:R0(s.cid)})):(this.log("sending have for %c",s.cid),t.addBlockPresence(s.cid,{cid:s.cid.bytes,type:xr.HaveBlock})):(this.log("sending block for %c",s.cid),n.add(o),t.addBlock(s.cid,{data:i,prefix:R0(s.cid)}))}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i;if(this.log("do not have block for %c",s.cid),!s.sendDontHave||s.sentDontHave===!0)continue;s.sentDontHave=!0,t.addBlockPresence(s.cid,{cid:s.cid.bytes,type:xr.DontHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((o,s)=>o+s.data.byteLength,0));for(let o of n)this.wants.delete(o)}}};var du=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=Fa({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new uu({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let o of t.wantlist.entries){let s=le.decode(o.cid),i=O(s.multihash.bytes,"base64");o.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,s),n.wants.delete(i)):(o.wantType===rt.WantHave?this.log("peer %p wanted block presence for %c",e,s):this.log("peer %p wanted block for %c",e,s),n.wants.set(i,{cid:s,priority:o.priority,wantType:o.wantType??rt.WantBlock,sendDontHave:o.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=O(e.multihash.bytes,"base64"),o=[];for(let s of this.ledgerMap.values())s.wants.has(n)&&o.push(s);await Promise.all(o.map(async s=>s.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var sr=Qe(d6(),1);sr.default.formatters.b=r=>r==null?"undefined":Ye.baseEncode(r);sr.default.formatters.t=r=>r==null?"undefined":ut.baseEncode(r);sr.default.formatters.m=r=>r==null?"undefined":st.baseEncode(r);sr.default.formatters.p=r=>r==null?"undefined":r.toString();sr.default.formatters.c=r=>r==null?"undefined":r.toString();sr.default.formatters.k=r=>r==null?"undefined":r.toString();sr.default.formatters.a=r=>r==null?"undefined":r.toString();function HS(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function So(){return{forComponent(r){return ir(r)}}}function ir(r){let e=HS(`${r}:trace`);return sr.default.enabled(`${r}:trace`)&&sr.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,sr.default)(`${r}:trace`)),Object.assign((0,sr.default)(r),{error:(0,sr.default)(`${r}:error`),trace:e})}var _0=Qe(h6(),1);var _o=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},A0=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},p6=r=>globalThis.DOMException===void 0?new A0(r):new DOMException(r),m6=r=>{let e=r.reason===void 0?p6("This operation was aborted."):r.reason;return e instanceof Error?e:p6(e)};function Yr(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((l,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&d(m6(h)),h.addEventListener("abort",()=>{d(m6(h))})}if(t===Number.POSITIVE_INFINITY){r.then(l,d);return}let u=new _o;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(h){d(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?d(o):(u.message=o??`Promise timed out after ${t} milliseconds`,d(u))},t),(async()=>{try{l(await r)}catch(h){d(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function I0(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Ka=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=I0(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var Ir=class extends _0.default{#e;#t;#r=0;#o;#a;#l=0;#s;#u;#n;#m;#i=0;#d;#c;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ka,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#o=e.intervalCap,this.#a=e.interval,this.#n=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#c=e.autoStart===!1}get#E(){return this.#t||this.#r<this.#o}get#b(){return this.#i<this.#d}#x(){this.#i--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#u=void 0}get#R(){let e=Date.now();if(this.#s===void 0){let t=this.#l-e;if(t<0)this.#r=this.#e?this.#i:0;else return this.#u===void 0&&(this.#u=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#n.size===0)return this.#s&&clearInterval(this.#s),this.#s=void 0,this.emit("empty"),this.#i===0&&this.emit("idle"),!1;if(!this.#c){let e=!this.#R;if(this.#E&&this.#b){let t=this.#n.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#s!==void 0||(this.#s=setInterval(()=>{this.#w()},this.#a),this.#l=Date.now()+this.#a)}#w(){this.#r===0&&this.#i===0&&this.#s&&(clearInterval(this.#s),this.#s=void 0),this.#r=this.#e?this.#i:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#d}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#d=e,this.#h()}async#S(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#i++,this.#r++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=Yr(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#S(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof _o&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#x()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#c?(this.#c=!1,this.#h(),this):this}pause(){this.#c=!0}clear(){this.#n=new this.#m}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#i===0&&this.#n.size===0||await this.#p("idle")}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#i}get isPaused(){return this.#c}};function mu(r){let e=[ar.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var D0=60;function gu(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:ar[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:ar[e.type],TTL:e.TTL??e.ttl??D0,data:e.data instanceof Uint8Array?O(e.data):e.data}))}}var WS=4;function T0(r,e={}){let t=new Ir({concurrency:e.queryConcurrency??WS});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),mu(o.types).forEach(a=>{s.append("type",ar[a])}),o.onProgress?.(new me("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=gu(await a.json());return o.onProgress?.(new me("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function g6(){return[T0("https://cloudflare-dns.com/dns-query"),T0("https://dns.google/resolve")]}var w6=Qe(k0(),1);var C0=class{lru;constructor(e){this.lru=(0,w6.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return gu({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:ar[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??D0)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function E6(r){return new C0(r)}var zS=1e3,yu=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=E6(e.cacheSize??zS),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=g6())}async query(e,t={}){let n=mu(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new me("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let d of l.Answer)this.cache.add(e,d);return l}catch(l){a.push(l),t.onProgress?.(new me("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var ar;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(ar||(ar={}));function wu(r={}){return new yu(r)}var YS=["string","number","bigint","symbol"],XS=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function b6(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(YS.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(QS(r))return"Buffer";let t=jS(r);return t||"Object"}function QS(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function jS(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(XS.includes(e))return e}var _=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};_.uint=new _(0,"uint",!0);_.negint=new _(1,"negint",!0);_.bytes=new _(2,"bytes",!0);_.string=new _(3,"string",!0);_.array=new _(4,"array",!1);_.map=new _(5,"map",!1);_.tag=new _(6,"tag",!1);_.float=new _(7,"float",!0);_.false=new _(7,"false",!0);_.true=new _(7,"true",!0);_.null=new _(7,"null",!0);_.undefined=new _(7,"undefined",!0);_.break=new _(7,"break",!0);var F=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var hi=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ZS=new TextDecoder,JS=new TextEncoder;function Eu(r){return hi&&globalThis.Buffer.isBuffer(r)}function $a(r){return r instanceof Uint8Array?Eu(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var S6=hi?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):v6(r,e,t):(r,e,t)=>t-e>64?ZS.decode(r.subarray(e,t)):v6(r,e,t),bu=hi?r=>r.length>64?globalThis.Buffer.from(r):x6(r):r=>r.length>64?JS.encode(r):x6(r),hn=r=>Uint8Array.from(r),pi=hi?(r,e,t)=>Eu(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),_6=hi?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),$a(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},A6=hi?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function I6(r,e){if(Eu(r)&&Eu(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function x6(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),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 e}function v6(r,e,t){let n=[];for(;e<t;){let o=r[e],s=null,i=o>239?4:o>223?3:o>191?2:1;if(e+i<=t){let a,c,l,d;switch(i){case 1:o<128&&(s=o);break;case 2:a=r[e+1],(a&192)===128&&(d=(o&31)<<6|a&63,d>127&&(s=d));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(d=(o&15)<<12|(a&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(d=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,d>65535&&d<1114112&&(s=d))}}s===null?(s=65533,i=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),e+=i}return N0(n)}var R6=4096;function N0(r){let e=r.length;if(e<=R6)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=R6));return t}var e_=256,Ha=class{constructor(e=e_){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=A6(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=pi(n,0,this.cursor)}else t=_6(this.chunks,this.cursor);return e&&this.reset(),t}};var Q="CBOR decode error:",mi="CBOR encode error:",qa=[];qa[23]=1;qa[24]=2;qa[25]=3;qa[26]=5;qa[27]=9;function Hn(r,e,t){if(r.length-e<t)throw new Error(`${Q} not enough data for type`)}var gt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function cr(r,e,t){Hn(r,e,1);let n=r[e];if(t.strict===!0&&n<gt[0])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);return n}function lr(r,e,t){Hn(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<gt[1])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);return n}function ur(r,e,t){Hn(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<gt[2])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);return n}function dr(r,e,t){Hn(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],s=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&s<gt[3])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${Q} integers outside of the safe integer range are not supported`)}function D6(r,e,t,n){return new F(_.uint,cr(r,e+1,n),2)}function T6(r,e,t,n){return new F(_.uint,lr(r,e+1,n),3)}function k6(r,e,t,n){return new F(_.uint,ur(r,e+1,n),5)}function C6(r,e,t,n){return new F(_.uint,dr(r,e+1,n),9)}function Dr(r,e){return bt(r,0,e.value)}function bt(r,e,t){if(t<gt[0]){let n=Number(t);r.push([e|n])}else if(t<gt[1]){let n=Number(t);r.push([e|24,n])}else if(t<gt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<gt[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<gt[4]){let o=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=s&255,s=s>>8,o[7]=s&255,s=s>>8,o[6]=s&255,s=s>>8,o[5]=s&255,o[4]=i&255,i=i>>8,o[3]=i&255,i=i>>8,o[2]=i&255,i=i>>8,o[1]=i&255,r.push(o)}else throw new Error(`${Q} encountered BigInt larger than allowable range`)}}Dr.encodedSize=function(e){return bt.encodedSize(e.value)};bt.encodedSize=function(e){return e<gt[0]?1:e<gt[1]?2:e<gt[2]?3:e<gt[3]?5:9};Dr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function N6(r,e,t,n){return new F(_.negint,-1-cr(r,e+1,n),2)}function L6(r,e,t,n){return new F(_.negint,-1-lr(r,e+1,n),3)}function P6(r,e,t,n){return new F(_.negint,-1-ur(r,e+1,n),5)}var L0=BigInt(-1),O6=BigInt(1);function B6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o!="bigint"){let s=-1-o;if(s>=Number.MIN_SAFE_INTEGER)return new F(_.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${Q} integers outside of the safe integer range are not supported`);return new F(_.negint,L0-BigInt(o),9)}function xu(r,e){let t=e.value,n=typeof t=="bigint"?t*L0-O6:t*-1-1;bt(r,e.type.majorEncoded,n)}xu.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*L0-O6:t*-1-1;return n<gt[0]?1:n<gt[1]?2:n<gt[2]?3:n<gt[3]?5:9};xu.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Ga(r,e,t,n){Hn(r,e,t+n);let o=pi(r,e+t,e+t+n);return new F(_.bytes,o,t+n)}function M6(r,e,t,n){return Ga(r,e,1,t)}function U6(r,e,t,n){return Ga(r,e,2,cr(r,e+1,n))}function F6(r,e,t,n){return Ga(r,e,3,lr(r,e+1,n))}function V6(r,e,t,n){return Ga(r,e,5,ur(r,e+1,n))}function K6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer bytes lengths not supported`);return Ga(r,e,9,o)}function vu(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===_.string?bu(r.value):r.value),r.encodedBytes}function gi(r,e){let t=vu(e);bt(r,e.type.majorEncoded,t.length),r.push(t)}gi.encodedSize=function(e){let t=vu(e);return bt.encodedSize(t.length)+t.length};gi.compareTokens=function(e,t){return r_(vu(e),vu(t))};function r_(r,e){return r.length<e.length?-1:r.length>e.length?1:I6(r,e)}function Wa(r,e,t,n,o){let s=t+n;Hn(r,e,s);let i=new F(_.string,S6(r,e+t,e+s),s);return o.retainStringBytes===!0&&(i.byteValue=pi(r,e+t,e+s)),i}function $6(r,e,t,n){return Wa(r,e,1,t,n)}function H6(r,e,t,n){return Wa(r,e,2,cr(r,e+1,n),n)}function q6(r,e,t,n){return Wa(r,e,3,lr(r,e+1,n),n)}function G6(r,e,t,n){return Wa(r,e,5,ur(r,e+1,n),n)}function W6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer string lengths not supported`);return Wa(r,e,9,o,n)}var z6=gi;function yi(r,e,t,n){return new F(_.array,n,t)}function Y6(r,e,t,n){return yi(r,e,1,t)}function X6(r,e,t,n){return yi(r,e,2,cr(r,e+1,n))}function Q6(r,e,t,n){return yi(r,e,3,lr(r,e+1,n))}function j6(r,e,t,n){return yi(r,e,5,ur(r,e+1,n))}function Z6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer array lengths not supported`);return yi(r,e,9,o)}function J6(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Q} indefinite length items not allowed`);return yi(r,e,1,1/0)}function Ru(r,e){bt(r,_.array.majorEncoded,e.value)}Ru.compareTokens=Dr.compareTokens;Ru.encodedSize=function(e){return bt.encodedSize(e.value)};function wi(r,e,t,n){return new F(_.map,n,t)}function e5(r,e,t,n){return wi(r,e,1,t)}function t5(r,e,t,n){return wi(r,e,2,cr(r,e+1,n))}function r5(r,e,t,n){return wi(r,e,3,lr(r,e+1,n))}function n5(r,e,t,n){return wi(r,e,5,ur(r,e+1,n))}function o5(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer map lengths not supported`);return wi(r,e,9,o)}function s5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Q} indefinite length items not allowed`);return wi(r,e,1,1/0)}function Su(r,e){bt(r,_.map.majorEncoded,e.value)}Su.compareTokens=Dr.compareTokens;Su.encodedSize=function(e){return bt.encodedSize(e.value)};function i5(r,e,t,n){return new F(_.tag,t,1)}function a5(r,e,t,n){return new F(_.tag,cr(r,e+1,n),2)}function c5(r,e,t,n){return new F(_.tag,lr(r,e+1,n),3)}function l5(r,e,t,n){return new F(_.tag,ur(r,e+1,n),5)}function u5(r,e,t,n){return new F(_.tag,dr(r,e+1,n),9)}function _u(r,e){bt(r,_.tag.majorEncoded,e.value)}_u.compareTokens=Dr.compareTokens;_u.encodedSize=function(e){return bt.encodedSize(e.value)};var c_=20,l_=21,u_=22,d_=23;function d5(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Q} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new F(_.null,null,1):new F(_.undefined,void 0,1)}function f5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Q} indefinite length items not allowed`);return new F(_.break,void 0,1)}function P0(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Q} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Q} Infinity values are not supported`)}return new F(_.float,r,e)}function h5(r,e,t,n){return P0(O0(r,e+1),3,n)}function p5(r,e,t,n){return P0(B0(r,e+1),5,n)}function m5(r,e,t,n){return P0(E5(r,e+1),9,n)}function Au(r,e,t){let n=e.value;if(n===!1)r.push([_.float.majorEncoded|c_]);else if(n===!0)r.push([_.float.majorEncoded|l_]);else if(n===null)r.push([_.float.majorEncoded|u_]);else if(n===void 0)r.push([_.float.majorEncoded|d_]);else{let o,s=!1;(!t||t.float64!==!0)&&(y5(n),o=O0(Xr,1),n===o||Number.isNaN(n)?(Xr[0]=249,r.push(Xr.slice(0,3)),s=!0):(w5(n),o=B0(Xr,1),n===o&&(Xr[0]=250,r.push(Xr.slice(0,5)),s=!0))),s||(f_(n),o=E5(Xr,1),Xr[0]=251,r.push(Xr.slice(0,9)))}}Au.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){y5(n);let o=O0(Xr,1);if(n===o||Number.isNaN(n))return 3;if(w5(n),o=B0(Xr,1),n===o)return 5}return 9};var g5=new ArrayBuffer(9),Tr=new DataView(g5,1),Xr=new Uint8Array(g5,0);function y5(r){if(r===1/0)Tr.setUint16(0,31744,!1);else if(r===-1/0)Tr.setUint16(0,64512,!1);else if(Number.isNaN(r))Tr.setUint16(0,32256,!1);else{Tr.setFloat32(0,r);let e=Tr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Tr.setUint16(0,31744,!1);else if(t===0)Tr.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Tr.setUint16(0,0):o<-14?Tr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Tr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function O0(r,e){if(r.length-e<2)throw new Error(`${Q} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,s;return n===0?s=o*2**-24:n!==31?s=(o+1024)*2**(n-25):s=o===0?1/0:NaN,t&32768?-s:s}function w5(r){Tr.setFloat32(0,r,!1)}function B0(r,e){if(r.length-e<4)throw new Error(`${Q} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function f_(r){Tr.setFloat64(0,r,!1)}function E5(r,e){if(r.length-e<8)throw new Error(`${Q} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Au.compareTokens=Dr.compareTokens;function _e(r,e,t){throw new Error(`${Q} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Iu(r){return()=>{throw new Error(`${Q} ${r}`)}}var K=[];for(let r=0;r<=23;r++)K[r]=_e;K[24]=D6;K[25]=T6;K[26]=k6;K[27]=C6;K[28]=_e;K[29]=_e;K[30]=_e;K[31]=_e;for(let r=32;r<=55;r++)K[r]=_e;K[56]=N6;K[57]=L6;K[58]=P6;K[59]=B6;K[60]=_e;K[61]=_e;K[62]=_e;K[63]=_e;for(let r=64;r<=87;r++)K[r]=M6;K[88]=U6;K[89]=F6;K[90]=V6;K[91]=K6;K[92]=_e;K[93]=_e;K[94]=_e;K[95]=Iu("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)K[r]=$6;K[120]=H6;K[121]=q6;K[122]=G6;K[123]=W6;K[124]=_e;K[125]=_e;K[126]=_e;K[127]=Iu("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)K[r]=Y6;K[152]=X6;K[153]=Q6;K[154]=j6;K[155]=Z6;K[156]=_e;K[157]=_e;K[158]=_e;K[159]=J6;for(let r=160;r<=183;r++)K[r]=e5;K[184]=t5;K[185]=r5;K[186]=n5;K[187]=o5;K[188]=_e;K[189]=_e;K[190]=_e;K[191]=s5;for(let r=192;r<=215;r++)K[r]=i5;K[216]=a5;K[217]=c5;K[218]=l5;K[219]=u5;K[220]=_e;K[221]=_e;K[222]=_e;K[223]=_e;for(let r=224;r<=243;r++)K[r]=Iu("simple values are not supported");K[244]=_e;K[245]=_e;K[246]=_e;K[247]=d5;K[248]=Iu("simple values are not supported");K[249]=h5;K[250]=p5;K[251]=m5;K[252]=_e;K[253]=_e;K[254]=_e;K[255]=f5;var Qr=[];for(let r=0;r<24;r++)Qr[r]=new F(_.uint,r,1);for(let r=-1;r>=-24;r--)Qr[31-r]=new F(_.negint,r,1);Qr[64]=new F(_.bytes,new Uint8Array(0),1);Qr[96]=new F(_.string,"",1);Qr[128]=new F(_.array,0,1);Qr[160]=new F(_.map,0,1);Qr[244]=new F(_.false,!1,1);Qr[245]=new F(_.true,!0,1);Qr[246]=new F(_.null,null,1);function b5(r){switch(r.type){case _.false:return hn([244]);case _.true:return hn([245]);case _.null:return hn([246]);case _.bytes:return r.value.length?void 0:hn([64]);case _.string:return r.value===""?hn([96]):void 0;case _.array:return r.value===0?hn([128]):void 0;case _.map:return r.value===0?hn([160]):void 0;case _.uint:return r.value<24?hn([Number(r.value)]):void 0;case _.negint:if(r.value>=-24)return hn([31-Number(r.value)])}}var p_={float64:!1,mapSorter:y_,quickEncodeToken:b5};function m_(){let r=[];return r[_.uint.major]=Dr,r[_.negint.major]=xu,r[_.bytes.major]=gi,r[_.string.major]=z6,r[_.array.major]=Ru,r[_.map.major]=Su,r[_.tag.major]=_u,r[_.float.major]=Au,r}var x5=m_(),M0=new Ha,Tu=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${mi} object contains circular references`);return new r(t,e)}},Ao={null:new F(_.null,null),undefined:new F(_.undefined,void 0),true:new F(_.true,!0),false:new F(_.false,!1),emptyArray:new F(_.array,0),emptyMap:new F(_.map,0)},Io={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new F(_.float,r):r>=0?new F(_.uint,r):new F(_.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new F(_.uint,r):new F(_.negint,r)},Uint8Array(r,e,t,n){return new F(_.bytes,r)},string(r,e,t,n){return new F(_.string,r)},boolean(r,e,t,n){return r?Ao.true:Ao.false},null(r,e,t,n){return Ao.null},undefined(r,e,t,n){return Ao.undefined},ArrayBuffer(r,e,t,n){return new F(_.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new F(_.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Ao.emptyArray,new F(_.break)]:Ao.emptyArray;n=Tu.createCheck(n,r);let o=[],s=0;for(let i of r)o[s++]=Du(i,t,n);return t.addBreakTokens?[new F(_.array,r.length),o,new F(_.break)]:[new F(_.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",s=o?r.keys():Object.keys(r),i=o?r.size:s.length;if(!i)return t.addBreakTokens===!0?[Ao.emptyMap,new F(_.break)]:Ao.emptyMap;n=Tu.createCheck(n,r);let a=[],c=0;for(let l of s)a[c++]=[Du(l,t,n),Du(o?r.get(l):r[l],t,n)];return g_(a,t),t.addBreakTokens?[new F(_.map,i),a,new F(_.break)]:[new F(_.map,i),a]}};Io.Map=Io.Object;Io.Buffer=Io.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Io[`${r}Array`]=Io.DataView;function Du(r,e={},t){let n=b6(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Io[n];if(typeof o=="function"){let i=o(r,n,e,t);if(i!=null)return i}let s=Io[n];if(!s)throw new Error(`${mi} unsupported type: ${n}`);return s(r,n,e,t)}function g_(r,e){e.mapSorter&&r.sort(e.mapSorter)}function y_(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,s=x5[o].compareTokens(t,n);return s===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),s}function v5(r,e,t,n){if(Array.isArray(e))for(let o of e)v5(r,o,t,n);else t[e.type.major](r,e,n)}function R5(r,e,t){let n=Du(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let s=e[n.type.major];if(s.encodedSize){let i=s.encodedSize(n,t),a=new Ha(i);if(s(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return $a(a.chunks[0])}}return M0.reset(),v5(M0,n,e,t),M0.toBytes(!0)}function Ei(r,e){return e=Object.assign({},p_,e),R5(r,x5,e)}var w_={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},ku=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Qr[e];if(t===void 0){let n=K[e];if(!n)throw new Error(`${Q} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},za=Symbol.for("DONE"),Cu=Symbol.for("BREAK");function E_(r,e,t){let n=[];for(let o=0;o<r.value;o++){let s=bi(e,t);if(s===Cu){if(r.value===1/0)break;throw new Error(`${Q} got unexpected break to lengthed array`)}if(s===za)throw new Error(`${Q} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=s}return n}function b_(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},s=n?new Map:void 0;for(let i=0;i<r.value;i++){let a=bi(e,t);if(a===Cu){if(r.value===1/0)break;throw new Error(`${Q} got unexpected break to lengthed map`)}if(a===za)throw new Error(`${Q} found map but not enough entries (got ${i} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${Q} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&s.has(a)||!n&&a in o))throw new Error(`${Q} found repeat map key "${a}"`);let c=bi(e,t);if(c===za)throw new Error(`${Q} found map but not enough entries (got ${i} [no value], expected ${r.value})`);n?s.set(a,c):o[a]=c}return n?s:o}function bi(r,e){if(r.done())return za;let t=r.next();if(t.type===_.break)return Cu;if(t.type.terminal)return t.value;if(t.type===_.array)return E_(t,r,e);if(t.type===_.map)return b_(t,r,e);if(t.type===_.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=bi(r,e);return e.tags[t.value](n)}throw new Error(`${Q} tag not supported (${t.value})`)}throw new Error("unsupported")}function U0(r,e){if(!(r instanceof Uint8Array))throw new Error(`${Q} data to decode must be a Uint8Array`);e=Object.assign({},w_,e);let t=e.tokenizer||new ku(r,e),n=bi(t,e);if(n===za)throw new Error(`${Q} did not find any content to decode`);if(n===Cu)throw new Error(`${Q} got unexpected break`);return[n,r.subarray(t.pos())]}function kr(r,e){let[t,n]=U0(r,e);if(n.length>0)throw new Error(`${Q} too many terminals, data makes no sense`);return t}var qn="/",S5=new TextEncoder().encode(qn),Lu=S5[0],Pe=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=M(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Lu)throw new Error("Invalid key")}toString(e="utf8"){return O(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(qn))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=S5),this._buf[0]!==Lu){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Lu,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Lu;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(qn).slice(1)}type(){return x_(this.baseNamespace())}name(){return v_(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(qn)||(e+=qn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(qn):new r(e.slice(0,-1).join(qn))}child(e){return this.toString()===qn?e:e.toString()===qn?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...R_(e.map(t=>t.namespaces()))])}};function x_(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function v_(r){let e=r.split(":");return e[e.length-1]}function R_(r){return[].concat(...r)}var D5="/pin/",_5="/pinned-block/",F0=so,A5=1;function I5(r){return r.version===0&&(r=r.toV1()),new Pe(`${D5}${r.toString(F0)}`)}var Pu=class{datastore;blockstore;dagWalkers;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.dagWalkers=n}async*add(e,t={}){let n=I5(e);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let s=new tr({concurrency:A5});for await(let a of this.#e(e,s,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>Z(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Ei(i),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=this.dagWalkers[e.code];if(o==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let s=await this.blockstore.get(e,n);yield e;for await(let i of o.walk(s))yield*await t.add(async()=>this.#e(i,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new Pe(`${_5}${F0.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=kr(await this.datastore.get(o,n))}catch(a){if(a.code!=="ERR_NOT_FOUND")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Ei(s),n),n.onProgress?.(new me("helia:pin:add",e))}}async*rm(e,t={}){let n=I5(e),o=await this.datastore.get(n,t),s=kr(o);await this.datastore.delete(n,t);let i=new tr({concurrency:A5});for await(let a of this.#e(e,i,{...t,depth:s.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>Z(l,e.bytes)),!0),{...t,depth:s.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:D5+(e.cid!=null?`${e.cid.toString(so)}`:"")},e)){let o=le.parse(t.toString().substring(5),so),s=kr(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new Pe(`${_5}${F0.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}};var S_=5,Ou=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??S_}async start(){await cn(...this.routers)}async stop(){await ln(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new g("No content routers available","ERR_NO_ROUTERS_AVAILABLE");let n=new wr({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of Mt(n.toGenerator(),...xi(this.routers,"findProviders").map(s=>s.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let s=await this.findPeer(o.id,t);return s.multiaddrs.length===0?null:s}catch(s){return this.log.error("could not load multiaddrs for peer %p",o.id,s),null}},{peerId:o.id,signal:t.signal}).catch(s=>{this.log.error("could not load multiaddrs for peer %p",o.id,s)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new g("No content routers available","ERR_NO_ROUTERS_AVAILABLE");await Promise.all(xi(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async put(e,t,n){await Promise.all(xi(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(xi(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new g("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");let n=this,o=Mt(...xi(this.routers,"findPeer").map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s;throw new g("Could not find peer in routing","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new g("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");for await(let n of Mt(...xi(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function xi(r,e){return r.filter(t=>t[e]!=null)}var Do={},vi=r=>{r.addEventListener("message",e=>{vi.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{vi.dispatchEvent("message",r,e)})};vi.addEventListener=(r,e)=>{Do[r]==null&&(Do[r]=[]),Do[r].push(e)};vi.removeEventListener=(r,e)=>{Do[r]!=null&&(Do[r]=Do[r].filter(t=>t===e))};vi.dispatchEvent=function(r,e,t){Do[r]!=null&&Do[r].forEach(n=>n(e,t))};var V0=vi;var K0="lock:worker:request-read",$0="lock:worker:release-read",H0="lock:master:grant-read",q0="lock:worker:request-write",G0="lock:worker:release-write",W0="lock:master:grant-write";var T5=(r=21)=>Math.random().toString().substring(2);var k5=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=d=>{if(d==null||d.data==null)return;let u={type:d.data.type,name:d.data.name,identifier:d.data.identifier};u.type===n&&u.identifier===a.identifier&&(s.removeEventListener("message",l),c())};s.addEventListener("message",l)})}}}))},C5=(r,e,t,n)=>async()=>{let o=T5();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},__={singleProcess:!1},N5=r=>{if(r=Object.assign({},__,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return V0.addEventListener("message",k5(t,"requestReadLock",K0,$0,H0)),V0.addEventListener("message",k5(t,"requestWriteLock",q0,G0,W0)),t}return{isWorker:!0,readLock:t=>C5(t,K0,H0,$0),writeLock:t=>C5(t,q0,W0,G0)}};var ys={},To;async function z0(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>Yr((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var A_=(r,e)=>{if(To.isWorker===!0)return{readLock:To.readLock(r,e),writeLock:To.writeLock(r,e)};let t=new Ir({concurrency:1}),n;return{async readLock(){if(n!=null)return z0(n,e);n=new Ir({concurrency:e.concurrency,autoStart:!1});let o=n,s=z0(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,z0(t,e)}}},I_={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Ya(r){let e=Object.assign({},I_,r);return To==null&&(To=N5(e),To.isWorker!==!0&&(To.addEventListener("requestReadLock",t=>{ys[t.data.name]!=null&&ys[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),To.addEventListener("requestWriteLock",async t=>{ys[t.data.name]!=null&&ys[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),ys[e.name]==null&&(ys[e.name]=A_(e.name,e)),ys[e.name]}var Bu=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Ya({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await cn(this.child),this.started=!0}async stop(){await ln(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let s of e){if(await o.pins.isPinned(s))throw new Error("CID was pinned");yield s}}(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var P5=42;function D_(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=le.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new F(_.tag,P5),new F(_.bytes,t)]}function T_(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function k_(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var L5={float64:!0,typeEncoders:{Object:D_,undefined:T_,number:k_}},GK={...L5,typeEncoders:{...L5.typeEncoders}};function C_(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return le.decode(r.subarray(1))}var Y0={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Y0.tags[P5]=C_;var WK={...Y0,tags:Y0.tags.slice()};var O5=113;var B5=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===_.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===_.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[_.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s);e.push(o)}[_.negint.major](e,t){this[_.uint.major](e,t)}[_.bytes.major](e,t){throw new Error(`${mi} unsupported type: Uint8Array`)}[_.string.major](e,t){this.prefix(e);let n=bu(JSON.stringify(t.value));e.push(n.length>32?$a(n):n)}[_.array.major](e,t){this.prefix(e),this.inRecursive.push({type:_.array,elements:0}),e.push([91])}[_.map.major](e,t){this.prefix(e),this.inRecursive.push({type:_.map,elements:0}),e.push([123])}[_.tag.major](e,t){}[_.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(i.type===_.array)e.push([93]);else if(i.type===_.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${mi} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],s=!1;for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i),!s&&(o[i]===46||o[i]===101||o[i]===69)&&(s=!0);s||(o.push(46),o.push(48)),e.push(o)}};var ws=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${Q} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${Q} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new F(_.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${Q} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${Q} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let s=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(s);return n?new F(_.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new F(i>=0?_.uint:_.negint,i,this._pos-e):new F(i>=0?_.uint:_.negint,BigInt(s),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${Q} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let s=this._pos,i=0;s<this.data.length&&i<65536;s++,i++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,s));return this._pos=s+1,new F(_.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${Q} unexpected end of unicode escape sequence at position ${this._pos}`);let s=0;for(let i=0;i<4;i++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${Q} unexpected unicode escape character at position ${this._pos}`);s=s*16+a,this._pos++}return s},o=()=>{let s=this.ch(),i=null,a=s>239?4:s>223?3:s>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${Q} unexpected unicode sequence at position ${this._pos}`);let c,l,d,u;switch(a){case 1:s<128&&(i=s);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(u=(s&31)<<6|c&63,u>127&&(i=u));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(u=(s&15)<<12|(c&63)<<6|l&63,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],d=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(d&192)===128&&(u=(s&15)<<18|(c&63)<<12|(l&63)<<6|d&63,u>65535&&u<1114112&&(i=u))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let s=this.ch(),i;switch(s){case 92:if(this._pos++,this.done())throw new Error(`${Q} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${Q} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new F(_.string,N0(t),this._pos-e);default:if(s<32)throw new Error(`${Q} invalid control character at position ${this._pos}`);s<128?(t.push(s),this._pos++):o()}}throw new Error(`${Q} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new F(_.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new F(_.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new F(_.null,null,4);case 102:return this.expect([102,97,108,115,101]),new F(_.false,!1,5);case 116:return this.expect([116,114,117,101]),new F(_.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${Q} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new F(_.break,void 0,1);if(this.ch()!==44)throw new Error(`${Q} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new F(_.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new F(_.break,void 0,1);if(this.ch()!==44)throw new Error(`${Q} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new F(_.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${Q} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${Q} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Mu(r,e){return e=Object.assign({tokenizer:new ws(r,e)},e),kr(r,e)}var P_={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};P_.tags[42]=le.parse;var U5=297;var l$=new TextDecoder;var u$=new TextEncoder;var B_=new TextDecoder;function X0(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Uu(r,e){let t;[t,e]=X0(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function F5(r,e){let t;return[t,e]=X0(r,e),[t&7,t>>3,e]}function M_(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=F5(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Uu(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Uu(r,n),e.Name=B_.decode(i)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=X0(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function V5(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=F5(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=Uu(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Uu(r,t),n.push(M_(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let i={};return s&&(i.Data=s),i.Links=n||[],i}var f$=new TextEncoder,h$=2**32,p$=2**31;var y$=new TextEncoder;function K5(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var $5=112;function H5(r){let e=K5(r),t=V5(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=le.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}var F_={codec:$5,*walk(r){yield*H5(r).Links.map(t=>t.Hash)}},V_={codec:Xc,*walk(){}},q5=42,K_={codec:O5,*walk(r){let e=[],t=[];t[q5]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let o=le.decode(n.subarray(1));return e.push(o),o},kr(r,{tags:t}),yield*e}},Q0=class extends ws{tokenBuffer;constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===_.map){let t=this._next();if(t.type===_.string&&t.value==="/"){let n=this._next();if(n.type===_.string){if(this._next().type!==_.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new F(_.tag,42,0)}if(n.type===_.map){let o=this._next();if(o.type===_.string&&o.value==="bytes"){let s=this._next();if(s.type===_.string){for(let a=0;a<2;a++)if(this._next().type!==_.break)throw new Error("Invalid encoded Bytes form");let i=st.decode(`m${s.value}`);return new F(_.bytes,i,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},$_={codec:U5,*walk(r){let e=[],t=[];t[q5]=n=>{let o=le.parse(n);return e.push(o),o},Mu(r,{tags:t,tokenizer:new Q0(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}},H_={codec:W4,*walk(){}};function G5(r=[]){let e={};return[F_,V_,K_,$_,H_,...r].forEach(t=>{e[t.codec]=t}),e}var j0=new Pe("/version"),W5=1;async function z5(r){if(!await r.has(j0)){await r.put(j0,M(`${W5}`));return}let e=await r.get(j0),t=O(e);if(parseInt(t,10)!==W5)throw new Error("Unknown datastore version, a datastore migration may be required")}function Y5(r=[]){let e={};return[Ne,Eh,Wt,...r].forEach(t=>{e[t.code]=t}),e}var Gn=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:o}of e)await this.put(n,o,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var Ri={};pe(Ri,{abortedError:()=>Y_,closeFailedError:()=>G_,deleteFailedError:()=>Q5,getFailedError:()=>W_,hasFailedError:()=>z_,notFoundError:()=>Xa,openFailedError:()=>q_,putFailedError:()=>X5});var Wn=Qe(Yo(),1);function q_(r){return r=r??new Error("Open failed"),(0,Wn.default)(r,"ERR_OPEN_FAILED")}function G_(r){return r=r??new Error("Close failed"),(0,Wn.default)(r,"ERR_CLOSE_FAILED")}function X5(r){return r=r??new Error("Put failed"),(0,Wn.default)(r,"ERR_PUT_FAILED")}function W_(r){return r=r??new Error("Get failed"),(0,Wn.default)(r,"ERR_GET_FAILED")}function Q5(r){return r=r??new Error("Delete failed"),(0,Wn.default)(r,"ERR_DELETE_FAILED")}function z_(r){return r=r??new Error("Has failed"),(0,Wn.default)(r,"ERR_HAS_FAILED")}function Xa(r){return r=r??new Error("Not Found"),(0,Wn.default)(r,"ERR_NOT_FOUND")}function Y_(r){return r=r??new Error("Aborted"),(0,Wn.default)(r,"ERR_ABORTED")}var Qa=class extends Gn{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(ut.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(ut.encode(e.multihash.bytes));if(t==null)throw Xa();return t}has(e){return this.data.has(ut.encode(e.multihash.bytes))}async delete(e){this.data.delete(ut.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:le.createV1(Xc,Mr(ut.decode(e))),block:t}}};function X_(r){return r[Symbol.asyncIterator]!=null}function Q_(r,e){let t=0;if(X_(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Vs(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var jr=Q_;var eH=ir("blockstore:core:tiered");var j5={...Ri};var Fu=0,Vu=class extends Gn{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===Fu||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===Fu)return e.multihash.digest;if(this.child==null)throw j5.notFoundError();return this.child.get(e)}has(e){return e.multihash.code===Fu?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==Fu&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function j_(r){return r[Symbol.asyncIterator]!=null}function Z5(r){return r?.then!=null}function Z_(r,e){let t=0;if(j_(r))return async function*(){for await(let c of r){let l=e(c,t++);Z5(l)&&await l,yield c}}();let n=Vs(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();if(typeof e(o,t++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=e(c,t++);Z5(l)&&await l,yield c}}();let a=e;return function*(){yield o;for(let c of n)a(c,t++),yield c}()}var ja=Z_;var Ku=class{child;hashers;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Vu(e.blockstore),this.hashers=e.hashers??{}}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new me("blocks:put:duplicate",e)),e):(n.onProgress?.(new me("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new me("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=jr(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new me("blocks:put-many:duplicate",s)),!i}),o=ja(n,async({cid:s,block:i})=>{t.onProgress?.(new me("blocks:put-many:providers:notify",s)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(s,i,t)))});t.onProgress?.(new me("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){t.onProgress?.(new me("blocks:get:providers:get",e));let n=await J5(e,this.components.blockBrokers,this.hashers[e.multihash.code],{...t,log:this.log});return t.onProgress?.(new me("blocks:get:blockstore:put",e)),await this.child.put(e,n,t),t.onProgress?.(new me("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n,t))),n}return t.onProgress?.(new me("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new me("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(ja(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){t.onProgress?.(new me("blocks:get-many:providers:get",n));let o=await J5(n,this.components.blockBrokers,this.hashers[n.multihash.code],{...t,log:this.log});t.onProgress?.(new me("blocks:get-many:blockstore:put",n)),await this.child.put(n,o,t),t.onProgress?.(new me("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,o,t)))}}))}async delete(e,t={}){t.onProgress?.(new me("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new me("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of e)yield n}(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new me("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},$u=class extends Ku{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await cn(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await ln(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new Z0({blockstore:this.child,blockBrokers:n,hashers:this.hashers,logger:this.logger},{root:e})}},Z0=class extends Ku{closeController;constructor(e,t){super(e),this.closeController=new AbortController,H(1/0,this.closeController.signal),this.log=e.logger.forComponent(`helia:session-storage${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=Ae([this.closeController.signal,n.signal]);H(1/0,o);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Ae([this.closeController.signal,e.signal]);H(1/0,t);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function J_(r){return typeof r.retrieve=="function"}var eA=(r,e)=>{if(e==null)throw new g(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`,"ERR_UNKNOWN_HASH_ALG");return async t=>{let n=await e.digest(t);if(!Z(n.digest,r.multihash.digest))throw new g("Hash of downloaded block did not match multihash from passed CID","ERR_HASH_MISMATCH")}};async function J5(r,e,t,n){let o=eA(r,t),s=new AbortController,i=Ae([s.signal,n.signal]);H(1/0,s.signal,i);let a=[];for(let c of e)J_(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,d=await c.retrieve(r,{...n,signal:i,validateFn:async u=>{await o(u),l=!0}});return l||await o(d),d}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{s.abort(),i.clear()}}var eg=1,tg=5;var J0=Qe(s6(),1);var tA=Math.LN2*Math.LN2,Hu=class r{static create(e,t=.005){let n=rA(e,t);return new r(n)}seeds;bits;buffer;constructor(e={}){e.seeds!=null?this.seeds=e.seeds:this.seeds=nA(e.hashes??8),this.bits=e.bits??1024,this.buffer=Ie(Math.ceil(this.bits/8))}add(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.seeds.length;t++){let o=J0.default.x86.hash32(e,this.seeds[t])%this.bits;this.setbit(o)}}has(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.seeds.length;t++){let o=J0.default.x86.hash32(e,this.seeds[t])%this.bits;if(!this.getbit(o))return!1}return!0}clear(){this.buffer.fill(0)}setbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;let o=this.buffer[t];o|=1<<n,this.buffer[t]=o}getbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;return(this.buffer[t]&1<<n)!==0}};function rA(r,e=.005){let t=Math.round(-1*r*Math.log(e)/tA),n=Math.round(t/r*Math.LN2);return{bits:t,hashes:n}}function nA(r){let e,t,n=[];for(let o=0;o<r;o++)for(e=new ce(pt(4)),n[o]=e.getUint32(0,!0),t=0;t<o;t++)if(n[o]===n[t]){o--;break}return n}var Es=class extends ye{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),H(1/0,this),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Hu.create(this.maxProviders)}async retrieve(e,t={}){let n=st.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let s=J();if(this.requests.set(n,s.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",e)}let i=!1,a=new tr({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{i=!0,s.resolve(l.detail.result)}),a.addEventListener("idle",()=>{i||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c",e,l),s.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,d)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(e,l,t),{provider:l}))).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,l)});try{return await s.promise}finally{this.removeEventListener("provider",c),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=J(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let i of this.findNewProviders(e,n)){if(s===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",s,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),s++,s===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",s);break}}if(this.log("found %d/%d new session peers",s,this.maxProviders),s<t)throw new g(`Found ${s} of ${t} ${this.name} providers for ${e}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",e,i.errors??i),o.reject(i)}),o.promise}};var qu=class{blockstore;datastore;pins;logger;routing;dagWalkers;hashers;dns;metrics;log;constructor(e){this.logger=e.logger??So(),this.log=this.logger.forComponent("helia"),this.hashers=Y5(e.hashers),this.dagWalkers=G5(e.dagWalkers),this.dns=e.dns??wu(),this.metrics=e.metrics;let t={blockstore:e.blockstore,datastore:e.datastore,hashers:this.hashers,dagWalkers:this.dagWalkers,logger:this.logger,blockBrokers:[],dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new Ou(t,{routers:(e.routers??[]).flatMap(o=>{let s=[o];return o[on]!=null&&s.push(o[on]),o[sn]!=null&&s.push(o[sn]),s}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new $u(t);this.pins=new Pu(e.datastore,n,this.dagWalkers),this.blockstore=new Bu(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await z5(this.datastore),await cn(this.blockstore,this.datastore,this.routing)}async stop(){await ln(this.blockstore,this.datastore,this.routing)}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await $t(o.deleteMany(async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new me("helia:gc:deleted",s))}catch(i){n.log.error("Error during gc",i),e.onProgress?.(new me("helia:gc:error",i))}}()))}finally{t()}this.log("gc finished")}};var e2=class extends Es{wantList;network;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let o=await this.wantList.wantSessionBlock(e,t,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has&&o.block!=null)return o.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield n.id}toEvictionKey(e){return e.toBytes()}equals(e,t){return e.equals(t)}};function rg(r,e){return new e2(r,e)}var Gu=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var t2=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Wu(r){let{name:e,metrics:t}=r,n;return t!=null?n=new t2({name:e,metrics:t}):n=new Map,n}function oA(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Bt(r);e.push(t),r=r.slice(Se(t))}return e}var ng=oA;var zu=class extends ye{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),H(1/0,this),this.peers=Fa({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=Wu({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=O(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??rt.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,o)),o.wantType===rt.WantHave&&t.wantType===rt.WantBlock&&(o.wantType=rt.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===rt.WantBlock?(await er(this,"block",t?.signal,{filter:a=>Z(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await er(this,"presence",t?.signal,{filter:i=>Z(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=J(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new $n;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o);for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer",s)}})).catch(e=>{this.log.error("error sending messages",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=O(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new $n;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:rt.WantHave,priority:1}),await this.network.sendMessage(t,o),(await er(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Z(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:rt.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new $n;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:rt.WantBlock,priority:1}),await this.network.sendMessage(t,o),(await er(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Z(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=O(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=ng(o.prefix),i=s[0],a=s[1],c=s[2],l=c===Ne.code?Ne:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let d=l.digest(o.data);d.then!=null&&(d=await d);let u=le.create(i===0?0:1,a,d);this.log("received block from %p for %c",e,u),this.safeDispatchEvent("block",{detail:{sender:e,cid:u,block:o.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:u,has:!0,block:o.data}});let h=O(u.multihash.bytes,"base64"),f=this.wants.get(h);f!=null&&(f.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=le.decode(o);this.log("received %s from %p for %c",s,e,i),this.safeDispatchEvent("presence",{detail:{sender:e,cid:i,has:s===xr.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new $n(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:rt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Yu=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.stats=new Gu(e),this.network=new rl(e,t),this.peerWantLists=new du({...e,network:this.network},t),this.wantList=new zu({...e,network:this.network},t)}createSession(e={}){return rg({wantList:this.wantList,network:this.network,logger:this.logger},e)}async want(e,t={}){let n=new AbortController,o=Ae([n.signal,t.signal]);H(1/0,n.signal,o),this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,s)});try{return(await this.wantList.wantBlock(e,{...t,signal:o})).block}finally{n.abort(),o.clear()}}async notify(e,t,n={}){await Promise.all([this.peerWantLists.receivedBlock(e,n),this.wantList.receivedBlock(e,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var og=(r,e={})=>new Yu(r,e);var r2=class{bitswap;started;constructor(e,t={}){let{hashers:n}=e;this.bitswap=og(e,{hashLoader:{getHasher:async o=>{let s;if(typeof o=="string"?s=Object.values(n).find(i=>i.name===o):s=n[o],s!=null)return s;throw new Error(`Could not load hasher for code/name "${o}"`)}},...t}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t,n){await this.bitswap.notify(e,t,n)}async retrieve(e,t={}){return this.bitswap.want(e,t)}createSession(e){let t=this.bitswap.createSession(e);return{announce:async(n,o,s)=>{await this.bitswap.notify(n,o,s)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function n2(r={}){return e=>new r2(e,r)}var Xu=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let d=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let h=Number.parseInt(u,e);if(!Number.isNaN(h))return h});if(d===void 0)break;if(s*=e,s+=d,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var sg=45,sA=15,Si=new Xu;function o2(r){if(!(r.length>sA))return Si.new(r).parseWith(()=>Si.readIPv4Addr())}function s2(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>sg))return Si.new(r).parseWith(()=>Si.readIPv6Addr())}function Qu(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>sg))return Si.new(r).parseWith(()=>Si.readIPAddr())}function _i(r){return!!o2(r)}function Ai(r){return!!s2(r)}function ju(r){return!!Qu(r)}var ag=Qe(ig(),1),iA=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],aA=iA.map(r=>new ag.Netmask(r));function cA(r){for(let e of aA)if(e.contains(r))return!0;return!1}function lA(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Yt(r){return _i(r)?cA(r):Ai(r)?lA(r):void 0}var Vq=parseInt("0xFFFF",16),Kq=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var ug=_i,pA=Ai,i2=function(r){let e=0;if(r=r.toString().trim(),ug(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(pA(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ug(t[n]),i;s&&(i=i2(t[n]),t[n]=O(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,O(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},dg=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Ii={},a2={},gA=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];gA.forEach(r=>{let e=yA(...r);a2[e.code]=e,Ii[e.name]=e});function yA(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function ee(r){if(typeof r=="number"){if(a2[r]!=null)return a2[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Ii[r]!=null)return Ii[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var vG=ee("ip4"),RG=ee("ip6"),SG=ee("ipcidr");function l2(r,e){switch(ee(r).code){case 4:case 41:return EA(e);case 42:return pg(e);case 6:case 273:case 33:case 132:return gg(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return pg(e);case 421:return RA(e);case 444:return mg(e);case 445:return mg(e);case 466:return vA(e);default:return O(e,"base16")}}function u2(r,e){switch(ee(r).code){case 4:return fg(e);case 41:return fg(e);case 42:return hg(e);case 6:case 273:case 33:case 132:return d2(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return hg(e);case 421:return bA(e);case 444:return SA(e);case 445:return _A(e);case 466:return xA(e);default:return M(e,"base16")}}var c2=Object.values(br).map(r=>r.decoder),wA=function(){let r=c2[0].or(c2[1]);return c2.slice(2).forEach(e=>r=r.or(e)),r}();function fg(r){if(!ju(r))throw new Error("invalid ip address");return i2(r)}function EA(r){let e=dg(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!ju(e))throw new Error("invalid ip address");return e}function d2(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function gg(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function hg(r){let e=M(r),t=Uint8Array.from($e(e.length));return ve([t,e],t.length+e.length)}function pg(r){let e=Bt(r);if(r=r.slice(Se(e)),r.length!==e)throw new Error("inconsistent lengths");return O(r)}function bA(r){let e;r[0]==="Q"||r[0]==="1"?e=Mr(Ye.decode(`z${r}`)).bytes:e=le.parse(r).multihash.bytes;let t=Uint8Array.from($e(e.length));return ve([t,e],t.length+e.length)}function xA(r){let e=wA.decode(r),t=Uint8Array.from($e(e.length));return ve([t,e],t.length+e.length)}function vA(r){let e=Bt(r),t=r.slice(Se(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+O(t,"base64url")}function RA(r){let e=Bt(r),t=r.slice(Se(e));if(t.length!==e)throw new Error("inconsistent lengths");return O(t,"base58btc")}function SA(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=ut.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=d2(n);return ve([t,o],t.length+o.length)}function _A(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ut.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=d2(n);return ve([t,o],t.length+o.length)}function mg(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=O(e,"base32"),o=gg(t);return`${n}:${o}`}function yg(r){r=f2(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=ee(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Eg("invalid address: "+r);if(a.path===!0){n=f2(o.slice(s).join("/")),e.push([a.code,u2(a.code,n)]),t.push([a.code,n]);break}let c=u2(a.code,o[s]);e.push([a.code,c]),t.push([a.code,l2(a.code,c)])}return{string:wg(t),bytes:p2(e),tuples:e,stringTuples:t,path:n}}function h2(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=Bt(r,o),i=Se(s),a=ee(s),c=AA(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Eg("Invalid address Uint8Array: "+O(r,"base16"));e.push([s,l]);let d=l2(s,l);if(t.push([s,d]),a.path===!0){n=d;break}}return{bytes:Uint8Array.from(r),string:wg(t),tuples:e,stringTuples:t,path:n}}function wg(r){let e=[];return r.map(t=>{let n=ee(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),f2(e.join("/"))}function p2(r){return ve(r.map(e=>{let t=ee(e[0]),n=Uint8Array.from($e(t.code));return e.length>1&&e[1]!=null&&(n=ve([n,e[1]])),n}))}function AA(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=Bt(e instanceof Uint8Array?e:Uint8Array.from(e));return t+Se(t)}}function f2(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Eg(r){return new Error("Error parsing address: "+r)}var IA=Symbol.for("nodejs.util.inspect.custom"),m2=Symbol.for("@multiformats/js-multiaddr/multiaddr"),DA=[ee("dns").code,ee("dns4").code,ee("dns6").code,ee("dnsaddr").code],Zu=class r{bytes;#e;#t;#r;#o;[m2]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=h2(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=yg(e)}else if(ko(e))t=h2(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#o=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=ee("tcp"),a=ee("udp"),c=ee("ip4"),l=ee("ip6"),d=ee("dns6"),u=ee("ip6zone");for(let[f,p]of this.stringTuples())f===u.code&&(s=`%${p??""}`),DA.includes(f)&&(t=i.name,o=443,n=`${p??""}${s}`,e=f===d.code?6:4),(f===i.code||f===a.code)&&(t=ee(f).name,o=parseInt(p??"")),(f===c.code||f===l.code)&&(t=ee(f).name,n=`${p??""}${s}`,e=f===l.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},ee(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>ee(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(p2(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===Ii.p2p.code&&e.push([n,o]),n===Ii["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?O(Ye.decode(`z${n}`),"base58btc"):O(le.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#o}equals(e){return Z(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=Di.get(t.name);if(n==null)throw new g(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>j(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[IA](){return`Multiaddr(${this.#e})`}};var Di=new Map;function ko(r){return!!r?.[m2]}function j(r){return new Zu(r)}var TA=r=>r.toString().split("/").slice(1),Ja=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),Te=r=>({match:e=>Ja(t=>t===r).match(e),pattern:r}),t1=()=>({match:r=>Ja(e=>typeof e=="string").match(r),pattern:"{string}"}),r1=()=>({match:r=>Ja(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),xt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Ye.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Ju=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{lh.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),vt=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),fr=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Oe=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function nt(...r){function e(o){let s=TA(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var y2=Oe(Te("dns4"),t1()),w2=Oe(Te("dns6"),t1()),E2=Oe(Te("dnsaddr"),t1()),bg=Oe(Te("dns"),t1()),JG=nt(y2),eW=nt(w2),tW=nt(E2),n1=nt(fr(bg,E2,y2,w2)),xg=Oe(Te("ip4"),Ja(_i)),vg=Oe(Te("ip6"),Ja(Ai)),Rg=fr(xg,vg),pn=fr(Rg,bg,y2,w2,E2),Sg=nt(pn),rW=nt(xg),nW=nt(vg),_g=nt(Rg),o1=Oe(pn,Te("tcp"),r1()),ec=Oe(pn,Te("udp"),r1()),kA=fr(o1,ec),oW=nt(o1),sW=nt(ec),b2=Oe(ec,Te("quic")),s1=Oe(ec,Te("quic-v1")),CA=fr(b2,s1),iW=nt(b2),aW=nt(s1),g2=fr(pn,o1,ec,b2,s1),Ag=fr(Oe(g2,Te("ws"),vt(xt()))),cW=nt(Ag),Ig=fr(Oe(g2,Te("wss"),vt(xt())),Oe(g2,Te("tls"),Te("ws"),vt(xt()))),lW=nt(Ig),Dg=Oe(kA,Te("webrtc-direct"),Ju(),vt(Ju()),vt(xt())),Tg=nt(Dg),kg=Oe(s1,Te("webtransport"),vt(Ju()),vt(Ju()),vt(xt())),i1=nt(kg),e1=fr(Ag,Ig,Oe(o1,vt(xt())),Oe(CA,vt(xt())),Oe(pn,vt(xt())),Dg,kg,xt()),uW=nt(e1),NA=Oe(e1,Te("p2p-circuit"),xt()),bs=nt(NA),LA=fr(Oe(e1,Te("p2p-circuit"),Te("webrtc"),xt()),Oe(e1,Te("webrtc"),vt(xt())),Te("webrtc")),Cg=nt(LA),PA=fr(Oe(pn,Te("tcp"),r1(),Te("http"),vt(xt())),Oe(pn,Te("http"),vt(xt()))),Ng=nt(PA),OA=fr(Oe(pn,Te("tcp"),fr(Oe(Te("443"),Te("http")),Oe(r1(),Te("https"))),vt(xt())),Oe(pn,Te("tls"),Te("http"),vt(xt())),Oe(pn,Te("https"),vt(xt()))),Lg=nt(OA);var BA=[ee("tcp").code,ee("dns").code,ee("dnsaddr").code,ee("dns4").code,ee("dns6").code];function Pg(r){let e;try{e=ee("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function Og(r){return r.some(([e,t])=>e===ee("tls").code)}function hr(r,e,t){let n=Bg[ee(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${ee(r).name}`);let o=n(e,t);return r===ee("ip6").code?`[${o}]`:o}var Bg={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${hr(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${hr(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=Og(e),n=Pg(e);if(t&&n!==null)return`https://${n}`;let o=t?"https://":"http://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let i=hr(s[0],s[1]??"",e);return i=i.replace("tcp://",""),`${o}${i}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return hr(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return hr(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=hr(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=Og(e),n=Pg(e);if(t&&n!==null)return`wss://${n}`;let o=t?"wss://":"ws://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let i=hr(s[0],s[1]??"",e);return i=i.replace("tcp://",""),`${o}${i}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=hr(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function a1(r,e){let n=j(r).stringTuples(),o=n.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let s=ee(o[0]),i=Bg[s.name];if(i==null)throw new Error(`No interpreter found for ${s.name}`);let a=i(o[1]??"",n);return e?.assumeHttp!==!1&&BA.includes(o[0])&&(a=a.replace(/^.*:\/\//,""),o[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var c1=class{url;#e=0;#t=0;#r=0;#o=0;#a=new Map;log;constructor(e,t){this.url=e instanceof URL?e:new URL(e),this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#l(e){let t=e.multihash.bytes;return st.encode(t)}async getRawBlock(e,t){let n=new URL(this.url.toString());if(n.pathname=`/ipfs/${e.toString()}`,n.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let o=this.#l(e),s=new AbortController,i=()=>{s.abort()};t?.addEventListener("abort",i);try{let a=this.#a.get(o);return a==null&&(this.#e++,a=fetch(n.toString(),{signal:s.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async c=>{if(this.log("GET %s %d",n,c.status),!c.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);return this.#o++,new Uint8Array(await c.arrayBuffer())}),this.#a.set(o,a)),await a}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",i),this.#a.delete(o)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#o/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#o,pendingResponses:this.#a.size}}};function MA(r,e,t){return r.filter(n=>Lg.matches(n)||e&&Ng.matches(n)?t||n1.matches(n)?!0:Yt(n.toOptions().host)===!1:!1)}async function*l1(r,e,t,n,o,s){for await(let i of e.findProviders(r,s)){let a=MA(i.multiaddrs,n,o);if(a.length===0)continue;let c=a1(a[0]);yield new c1(c,t)}}var x2=class extends Es{routing;allowInsecure;allowLocal;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??u1,this.allowLocal=t.allowLocal??d1}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let o=await t.getRawBlock(e,n.signal);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*l1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}};function Mg(r,e){return new x2(r,e)}var f1=class{allowInsecure;allowLocal;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??u1,this.allowLocal=t.allowLocal??d1}async retrieve(e,t={}){let n=[];for await(let o of l1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)){this.log("getting block for %c from %s",e,o.url);try{let s=await o.getRawBlock(e,t.signal);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s",e,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s",e,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return Mg({logger:this.logger,routing:this.routing},e)}};var u1=!1,d1=!1;function v2(r={}){return e=>new f1(e,r)}async function*h1(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 KA=Qe(Yo(),1);var $A=Qe(p1(),1);var Ug="ERR_IPNS_EXPIRED_RECORD",m1="ERR_UNRECOGNIZED_VALIDITY";var zn="ERR_SIGNATURE_VERIFICATION";var S2="ERR_UNDEFINED_PARAMETER",Fg="ERR_INVALID_RECORD_DATA",Vg="ERR_INVALID_VALUE",Kg="ERR_INVALID_EMBEDDED_KEY";var $g="ERR_RECORD_TOO_LARGE";var Xt;(function(r){let e;(function(o){o.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(o){o[o.EOL=0]="EOL"})(t||(t={})),function(o){o.codec=()=>He(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=ne((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.value!=null&&(s.uint32(10),s.bytes(o.value)),o.signatureV1!=null&&(s.uint32(18),s.bytes(o.signatureV1)),o.validityType!=null&&(s.uint32(24),r.ValidityType.codec().encode(o.validityType,s)),o.validity!=null&&(s.uint32(34),s.bytes(o.validity)),o.sequence!=null&&(s.uint32(40),s.uint64(o.sequence)),o.ttl!=null&&(s.uint32(48),s.uint64(o.ttl)),o.pubKey!=null&&(s.uint32(58),s.bytes(o.pubKey)),o.signatureV2!=null&&(s.uint32(66),s.bytes(o.signatureV2)),o.data!=null&&(s.uint32(74),s.bytes(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.value=o.bytes();break;case 2:i.signatureV1=o.bytes();break;case 3:i.validityType=r.ValidityType.codec().decode(o);break;case 4:i.validity=o.bytes();break;case 5:i.sequence=o.uint64();break;case 6:i.ttl=o.uint64();break;case 7:i.pubKey=o.bytes();break;case 8:i.signatureV2=o.bytes();break;case 9:i.data=o.bytes();break;default:o.skipType(c&7);break}}return i})),n),r.encode=o=>re(o,r.codec()),r.decode=o=>te(o,r.codec())})(Xt||(Xt={}));var pr=Qe(Yo(),1);var qg=ir("ipns:utils"),Gg=M("/ipns/"),UA=114,Wg=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw qg.error(n),(0,pr.default)(n,S2)}let t;if(e.pubKey!=null){try{t=zr(e.pubKey)}catch(o){throw qg.error(o),o}if(!(await dt(e.pubKey)).equals(r))throw(0,pr.default)(new Error("Embedded public key did not match PeerID"),Kg)}else r.publicKey!=null&&(t=zr(r.publicKey));if(t!=null)return t;throw(0,pr.default)(new Error("no public key is available"),S2)};var zg=r=>{let e=M("ipns-signature:");return ve([e,r])},tc=r=>"signatureV1"in r?Xt.encode({value:M(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:M(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):Xt.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data});function mn(r){let e=Xt.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw(0,pr.default)(new Error("missing data or signatureV2"),zn);let t=Xg(e.data),n=FA(t.Value),o=O(t.Validity);if(e.value!=null&&e.signatureV1!=null)return VA(e),{value:n,validityType:Xt.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:Xt.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}var _2=r=>ve([Gg,r.toBytes()]),Yg=r=>Je(r.slice(Gg.length));var Xg=r=>{let e=kr(r);if(e.ValidityType===0)e.ValidityType=Xt.ValidityType.EOL;else throw(0,pr.default)(new Error("Unknown validity type"),m1);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e},FA=r=>{if(r!=null){if(Ms(r))return`/ipns/${r.toCID().toString(so)}`;if(r instanceof Uint8Array){let n=O(r);n.startsWith("/")&&(r=n)}let e=r.toString().trim();if(e.startsWith("/")&&e.length>1)return e;let t=le.asCID(r);if(t!=null)return t.code===UA?`/ipns/${t.toString(so)}`:`/ipfs/${t.toV1().toString()}`;try{return r instanceof Uint8Array?`/ipfs/${le.decode(r).toV1().toString()}`:`/ipfs/${le.parse(e).toV1().toString()}`}catch{}}throw(0,pr.default)(new Error("Value must be a valid content path starting with /"),Vg)},VA=r=>{if(r.data==null)throw(0,pr.default)(new Error("Record data is missing"),Fg);let e=Xg(r.data);if(!Z(e.Value,r.value??new Uint8Array(0)))throw(0,pr.default)(new Error('Field "value" did not match between protobuf and CBOR'),zn);if(!Z(e.Validity,r.validity??new Uint8Array(0)))throw(0,pr.default)(new Error('Field "validity" did not match between protobuf and CBOR'),zn);if(e.ValidityType!==r.validityType)throw(0,pr.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),zn);if(e.Sequence!==r.sequence)throw(0,pr.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),zn);if(e.TTL!==r.ttl)throw(0,pr.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),zn)};var nz=ir("ipns"),oz=Wt.code,sz=60*60*1e9,HA="/ipns/",iz=HA.length;var rc=Qe(Yo(),1),Qg=Qe(p1(),1);var g1=ir("ipns:validator"),qA=1024*10,GA=async(r,e)=>{let t=mn(e),n;try{let o=zg(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw g1.error("record signature verification failed"),(0,rc.default)(new Error("record signature verification failed"),zn);if(t.validityType===Xt.ValidityType.EOL){if(Qg.default.fromString(t.validity).toDate().getTime()<Date.now())throw g1.error("record has expired"),(0,rc.default)(new Error("record has expired"),Ug)}else if(t.validityType!=null)throw g1.error("unrecognized validity type"),(0,rc.default)(new Error("unrecognized validity type"),m1);g1("ipns record for %s is valid",t.value)};async function y1(r,e){if(e.byteLength>qA)throw(0,rc.default)(new Error("record too large"),$g);let t=Yg(r),n=mn(e),o=await Wg(t,n);await GA(o,e)}async function*nc(r){let e=/\r?\n/,t=new TextDecoder("utf8"),n="";for await(let o of r){typeof o=="string"&&(o=new TextEncoder().encode(o)),n+=t.decode(o,{stream:!0});let s=n.split(e);n=s.pop()??"";for(let i=0;i<s.length;i++)yield JSON.parse(s[i])}n+=t.decode(),n!==""&&(yield JSON.parse(n))}function WA(r){return r[Symbol.asyncIterator]!=null}function zA(r){if(WA(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var xs=zA;var A2=M("/ipns/");function jg(r){return Z(r.subarray(0,A2.byteLength),A2)}var Zg=r=>Je(r.slice(A2.length)),w1=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*Gt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async put(e,t,n){if(!jg(e))return;let o=Zg(e),s=mn(t);await this.client.putIPNS(o,s,n)}async get(e,t){if(!jg(e))throw new g("Not found","ERR_NOT_FOUND");let n=Zg(e);try{let o=await this.client.getIPNS(n,t);return tc(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new g("Not found","ERR_NOT_FOUND"):o}}},E1=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await xs(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new g("Not found","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){}};var Qt=ir("delegated-routing-v1-http-api-client"),Jg={concurrentRequests:4,timeout:3e4},b1=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal),this.httpQueue=new Ir({concurrency:t.concurrentRequests??Jg.concurrentRequests}),this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??Jg.timeout,this.contentRouting=new w1(this),this.peerRouting=new E1(this)}get[on](){return this.contentRouting}get[sn](){return this.peerRouting}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.shutDownController.abort(),this.started=!1}async*getProviders(e,t={}){Qt("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ae([this.shutDownController.signal,n,t.signal]);H(1/0,n,o);let s=J(),i=J();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=`${this.clientUrl}routing/v1/providers/${e.toString()}`,l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new g("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new g("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new g("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let h of u.Providers){let f=this.#e(h);f!=null&&(yield f)}}else for await(let u of nc(h1(l.body))){let h=this.#e(u);h!=null&&(yield h)}}catch(a){Qt.error("getProviders errored:",a)}finally{o.clear(),i.resolve(),Qt("getProviders finished: %c",e)}}async*getPeers(e,t={}){Qt("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ae([this.shutDownController.signal,n,t.signal]);H(1/0,n,o);let s=J(),i=J();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`,l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new g("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new g("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new g("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let h of u.Peers){let f=this.#e(h);f!=null&&(yield f)}}else for await(let u of nc(h1(l.body))){let h=this.#e(u);h!=null&&(yield h)}}catch(a){Qt.error("getPeers errored:",a)}finally{o.clear(),i.resolve(),Qt("getPeers finished: %c",e)}}async getIPNS(e,t={}){Qt("getIPNS starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ae([this.shutDownController.signal,n,t.signal]);H(1/0,n,o);let s=J(),i=J();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await s.promise;let l=await fetch(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(Qt("getIPNS GET %s %d",a,l.status),l.status===404)throw new g("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new g("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new g("GET ipns response had no body","ERR_BAD_RESPONSE");let d=await l.arrayBuffer(),u=new Uint8Array(d,0,d.byteLength);return t.validate!==!1&&await y1(_2(e),u),mn(u)}catch(c){throw Qt.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),i.resolve(),Qt("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){Qt("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=Ae([this.shutDownController.signal,o,n.signal]);H(1/0,o,s);let i=J(),a=J();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await i.promise;let l=tc(t),u=await fetch(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:s});if(Qt("putIPNS PUT %s %d",c,u.status),u.status!==200)throw new g("PUT ipns response had status other than 200","ERR_BAD_RESPONSE")}catch(l){throw Qt.error("putIPNS PUT %s error:",c,l.stack),l}finally{s.clear(),a.resolve(),Qt("putIPNS finished: %c",e)}}#e(e){let t=[],n=e.Addrs?.map(j)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:ge(e.ID),Addrs:n,Protocols:t}}};function e7(r,e={}){return new b1(new URL(r),e)}var t7="[a-fA-F\\d:]",Co=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${t7})|(?<=${t7})(?=\\s|$))`:"",Zr="(?: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}",ct="[a-fA-F\\d]{1,4}",x1=`
22
+ `)}async function c0(r,e){let t=qe.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=M(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=ci(o),{iv:i,salt:a,iterations:c,keySize:l,cipherText:d}=uS(s),u=await t0(uo,e,a,{c,dkLen:l}),h=await t.subtle.importKey("raw",u,"AES-CBC",!1,["decrypt"]),f=Pa(await t.subtle.decrypt({name:"AES-CBC",iv:i},h,d)),{result:p}=ci(f);n=Um(p)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=M(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=ci(o);n=Um(s)}else throw new g("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return l0(n)}function uS(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new g("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");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 g("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Pa(s.valueBlock.value[0].getValue()),a=a0,c=i0;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 g("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let l=e.valueBlock.value[1].valueBlock.value[1],d=l.valueBlock.value[0].toString();if(d!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(d!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(d!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(d!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(d!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new g("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let u=Pa(l.valueBlock.value[1].getValue());return{cipherText:Pa(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:u}}function Um(r){return Pa(r.valueBlock.value[2].getValue())}function Pa(r){return new Uint8Array(r,0,r.byteLength)}async function Fm(r){let e=await qe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await $m(e);return{privateKey:t[0],publicKey:t[1]}}async function u0(r){let t=[await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await dS(r)],n=await $m({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Vm(r,e){let t=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await qe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Km(r,e,t){let n=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return qe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function $m(r){if(r.privateKey==null||r.publicKey==null)throw new g("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([qe.get().subtle.exportKey("jwk",r.privateKey),qe.get().subtle.exportKey("jwk",r.publicKey)])}async function dS(r){return qe.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function au(r){if(r.kty!=="RSA")throw new g("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new g("invalid key modulus","ERR_INVALID_KEY_MODULUS");return M(r.n,"base64url").length*8}var ds=8192,us=class{_key;constructor(e){this._key=e}verify(e,t){return Km(this._key,t,e)}marshal(){return wo.jwkToPkix(this._key)}get bytes(){return $r.encode({Type:Ke.RSA,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}},Eo=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return pt(16)}sign(e){return Vm(this._key,e)}get public(){if(this._publicKey==null)throw new g("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new us(this._publicKey)}marshal(){return wo.jwkToPkcs1(this._key)}get bytes(){return Hr.encode({Type:Ke.RSA,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return O(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return wo.exportToPem(this,e);if(t==="libp2p-key")return ri(this.bytes,e);throw new g(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function l0(r){let e=wo.pkcs1ToJwk(r);if(au(e)>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await u0(e);return new Eo(t.privateKey,t.publicKey)}function hS(r){let e=wo.pkixToJwk(r);if(au(e)>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new us(e)}async function pS(r){if(au(r)>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await u0(r);return new Eo(e.privateKey,e.publicKey)}async function mS(r){if(r>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Fm(r);return new Eo(e.privateKey,e.publicKey)}var g0={};pe(g0,{Secp256k1PrivateKey:()=>ps,Secp256k1PublicKey:()=>hs,generateKeyPair:()=>DS,unmarshalSecp256k1PrivateKey:()=>AS,unmarshalSecp256k1PublicKey:()=>IS});var gS=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),bo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xo=new Uint32Array(64),f0=class extends ao{constructor(){super(64,32,8,!1),this.A=bo[0]|0,this.B=bo[1]|0,this.C=bo[2]|0,this.D=bo[3]|0,this.E=bo[4]|0,this.F=bo[5]|0,this.G=bo[6]|0,this.H=bo[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)xo[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let h=xo[u-15],f=xo[u-2],p=Ur(h,7)^Ur(h,18)^h>>>3,m=Ur(f,17)^Ur(f,19)^f>>>10;xo[u]=m+xo[u-7]+p+xo[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){let h=Ur(a,6)^Ur(a,11)^Ur(a,25),f=d+h+il(a,c,l)+gS[u]+xo[u]|0,m=(Ur(n,2)^Ur(n,13)^Ur(n,22))+al(n,o,s)|0;d=l,l=c,c=a,a=i+f|0,i=s,s=o,o=n,n=f+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,l,d)}roundClean(){xo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var vo=Zs(()=>new f0);function yS(r){let e=va(r);Rr(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:wS,hexToBytes:ES}=ul,fs={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=fs;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:wS(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=fs,t=typeof r=="string"?ES(r):r;Js(t);let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:s}=fs._parseInt(t.subarray(2)),{d:i,l:a}=fs._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{let d=l.toString(16);return d.length&1?`0${d}`:d},n=e(t(r.s)),o=e(t(r.r)),s=n.length/2,i=o.length/2,a=t(s),c=t(i);return`30${t(i+s+4)}02${c}${o}02${a}${n}`}},Vn=BigInt(0),_r=BigInt(1),mU=BigInt(2),Hm=BigInt(3),gU=BigInt(4);function bS(r){let e=yS(r),{Fp:t}=e,n=e.toBytes||((p,m,y)=>{let w=m.toAffine();return kn(Uint8Array.from([4]),t.toBytes(w.x),t.toBytes(w.y))}),o=e.fromBytes||(p=>{let m=p.subarray(1),y=t.fromBytes(m.subarray(0,t.BYTES)),w=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:y,y:w}});function s(p){let{a:m,b:y}=e,w=t.sqr(p),b=t.mul(w,p);return t.add(t.add(b,t.mul(p,m)),y)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(p){return typeof p=="bigint"&&Vn<p&&p<e.n}function a(p){if(!i(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:w,n:b}=e;if(m&&typeof p!="bigint"){if(fo(p)&&(p=In(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let E;try{E=typeof p=="bigint"?p:Dn(Fe("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return w&&(E=De(E,b)),a(E),E}let l=new Map;function d(p){if(!(p instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(m,y,w){if(this.px=m,this.py=y,this.pz=w,m==null||!t.isValid(m))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(w==null||!t.isValid(w))throw new Error("z required")}static fromAffine(m){let{x:y,y:w}=m||{};if(!m||!t.isValid(y)||!t.isValid(w))throw new Error("invalid affine point");if(m instanceof u)throw new Error("projective point not allowed");let b=E=>t.eql(E,t.ZERO);return b(y)&&b(w)?u.ZERO:new u(y,w,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=t.invertBatch(m.map(w=>w.pz));return m.map((w,b)=>w.toAffine(y[b])).map(u.fromAffine)}static fromHex(m){let y=u.fromAffine(o(Fe("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return u.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not FE");let w=t.sqr(y),b=s(m);if(!t.eql(w,b))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){d(m);let{px:y,py:w,pz:b}=this,{px:E,py:x,pz:v}=m,I=t.eql(t.mul(y,v),t.mul(E,b)),S=t.eql(t.mul(w,v),t.mul(x,b));return I&&S}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,w=t.mul(y,Hm),{px:b,py:E,pz:x}=this,v=t.ZERO,I=t.ZERO,S=t.ZERO,R=t.mul(b,b),T=t.mul(E,E),P=t.mul(x,x),N=t.mul(b,E);return N=t.add(N,N),S=t.mul(b,x),S=t.add(S,S),v=t.mul(m,S),I=t.mul(w,P),I=t.add(v,I),v=t.sub(T,I),I=t.add(T,I),I=t.mul(v,I),v=t.mul(N,v),S=t.mul(w,S),P=t.mul(m,P),N=t.sub(R,P),N=t.mul(m,N),N=t.add(N,S),S=t.add(R,R),R=t.add(S,R),R=t.add(R,P),R=t.mul(R,N),I=t.add(I,R),P=t.mul(E,x),P=t.add(P,P),R=t.mul(P,N),v=t.sub(v,R),S=t.mul(P,T),S=t.add(S,S),S=t.add(S,S),new u(v,I,S)}add(m){d(m);let{px:y,py:w,pz:b}=this,{px:E,py:x,pz:v}=m,I=t.ZERO,S=t.ZERO,R=t.ZERO,T=e.a,P=t.mul(e.b,Hm),N=t.mul(y,E),B=t.mul(w,x),k=t.mul(b,v),X=t.add(y,w),D=t.add(E,x);X=t.mul(X,D),D=t.add(N,B),X=t.sub(X,D),D=t.add(y,b);let L=t.add(E,v);return D=t.mul(D,L),L=t.add(N,k),D=t.sub(D,L),L=t.add(w,b),I=t.add(x,v),L=t.mul(L,I),I=t.add(B,k),L=t.sub(L,I),R=t.mul(T,D),I=t.mul(P,k),R=t.add(I,R),I=t.sub(B,R),R=t.add(B,R),S=t.mul(I,R),B=t.add(N,N),B=t.add(B,N),k=t.mul(T,k),D=t.mul(P,D),B=t.add(B,k),k=t.sub(N,k),k=t.mul(T,k),D=t.add(D,k),N=t.mul(B,D),S=t.add(S,N),N=t.mul(L,D),I=t.mul(X,I),I=t.sub(I,N),N=t.mul(X,B),R=t.mul(L,R),R=t.add(R,N),new u(I,S,R)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return f.wNAFCached(this,l,m,y=>{let w=t.invertBatch(y.map(b=>b.pz));return y.map((b,E)=>b.toAffine(w[E])).map(u.fromAffine)})}multiplyUnsafe(m){let y=u.ZERO;if(m===Vn)return y;if(a(m),m===_r)return this;let{endo:w}=e;if(!w)return f.unsafeLadder(this,m);let{k1neg:b,k1:E,k2neg:x,k2:v}=w.splitScalar(m),I=y,S=y,R=this;for(;E>Vn||v>Vn;)E&_r&&(I=I.add(R)),v&_r&&(S=S.add(R)),R=R.double(),E>>=_r,v>>=_r;return b&&(I=I.negate()),x&&(S=S.negate()),S=new u(t.mul(S.px,w.beta),S.py,S.pz),I.add(S)}multiply(m){a(m);let y=m,w,b,{endo:E}=e;if(E){let{k1neg:x,k1:v,k2neg:I,k2:S}=E.splitScalar(y),{p:R,f:T}=this.wNAF(v),{p:P,f:N}=this.wNAF(S);R=f.constTimeNegate(x,R),P=f.constTimeNegate(I,P),P=new u(t.mul(P.px,E.beta),P.py,P.pz),w=R.add(P),b=T.add(N)}else{let{p:x,f:v}=this.wNAF(y);w=x,b=v}return u.normalizeZ([w,b])[0]}multiplyAndAddUnsafe(m,y,w){let b=u.BASE,E=(v,I)=>I===Vn||I===_r||!v.equals(b)?v.multiplyUnsafe(I):v.multiply(I),x=E(this,y).add(E(m,w));return x.is0()?void 0:x}toAffine(m){let{px:y,py:w,pz:b}=this,E=this.is0();m==null&&(m=E?t.ONE:t.inv(b));let x=t.mul(y,m),v=t.mul(w,m),I=t.mul(b,m);if(E)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x,y:v}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===_r)return!0;if(y)return y(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===_r?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return In(this.toRawBytes(m))}}u.BASE=new u(e.Gx,e.Gy,t.ONE),u.ZERO=new u(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,f=hl(u,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function xS(r){let e=va(r);return Rr(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function qm(r){let e=xS(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(D){return Vn<D&&D<t.ORDER}function a(D){return De(D,n)}function c(D){return dl(D,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:d,weierstrassEquation:u,isWithinCurveOrder:h}=bS({...e,toBytes(D,L,$){let C=L.toAffine(),A=t.toBytes(C.x),U=kn;return $?U(Uint8Array.from([L.hasEvenY()?2:3]),A):U(Uint8Array.from([4]),A,t.toBytes(C.y))},fromBytes(D){let L=D.length,$=D[0],C=D.subarray(1);if(L===o&&($===2||$===3)){let A=Dn(C);if(!i(A))throw new Error("Point is not on curve");let U=u(A),V;try{V=t.sqrt(U)}catch(ie){let de=ie instanceof Error?": "+ie.message:"";throw new Error("Point is not on curve"+de)}let q=(V&_r)===_r;return($&1)===1!==q&&(V=t.neg(V)),{x:A,y:V}}else if(L===s&&$===4){let A=t.fromBytes(C.subarray(0,t.BYTES)),U=t.fromBytes(C.subarray(t.BYTES,2*t.BYTES));return{x:A,y:U}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),f=D=>In(ho(D,e.nByteLength));function p(D){let L=n>>_r;return D>L}function m(D){return p(D)?a(-D):D}let y=(D,L,$)=>Dn(D.slice(L,$));class w{constructor(L,$,C){this.r=L,this.s=$,this.recovery=C,this.assertValidity()}static fromCompact(L){let $=e.nByteLength;return L=Fe("compactSignature",L,$*2),new w(y(L,0,$),y(L,$,2*$))}static fromDER(L){let{r:$,s:C}=fs.toSig(Fe("DER",L));return new w($,C)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(L){return new w(this.r,this.s,L)}recoverPublicKey(L){let{r:$,s:C,recovery:A}=this,U=S(Fe("msgHash",L));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let V=A===2||A===3?$+e.n:$;if(V>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let q=A&1?"03":"02",se=l.fromHex(q+f(V)),ie=c(V),de=a(-U*ie),ae=a(C*ie),ue=l.BASE.multiplyAndAddUnsafe(se,de,ae);if(!ue)throw new Error("point at infinify");return ue.assertValidity(),ue}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return is(this.toDERHex())}toDERHex(){return fs.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return is(this.toCompactHex())}toCompactHex(){return f(this.r)+f(this.s)}}let b={isValidPrivateKey(D){try{return d(D),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let D=Gh(e.n);return A8(e.randomBytes(D),e.n)},precompute(D=8,L=l.BASE){return L._setWindowSize(D),L.multiply(BigInt(3)),L}};function E(D,L=!0){return l.fromPrivateKey(D).toRawBytes(L)}function x(D){let L=fo(D),$=typeof D=="string",C=(L||$)&&D.length;return L?C===o||C===s:$?C===2*o||C===2*s:D instanceof l}function v(D,L,$=!0){if(x(D))throw new Error("first arg must be private key");if(!x(L))throw new Error("second arg must be public key");return l.fromHex(L).multiply(d(D)).toRawBytes($)}let I=e.bits2int||function(D){let L=Dn(D),$=D.length*8-e.nBitLength;return $>0?L>>BigInt($):L},S=e.bits2int_modN||function(D){return a(I(D))},R=xa(e.nBitLength);function T(D){if(typeof D!="bigint")throw new Error("bigint expected");if(!(Vn<=D&&D<R))throw new Error(`bigint expected < 2^${e.nBitLength}`);return ho(D,e.nByteLength)}function P(D,L,$=N){if(["recovered","canonical"].some(Le=>Le in $))throw new Error("sign() legacy options not supported");let{hash:C,randomBytes:A}=e,{lowS:U,prehash:V,extraEntropy:q}=$;U==null&&(U=!0),D=Fe("msgHash",D),V&&(D=Fe("prehashed msgHash",C(D)));let se=S(D),ie=d(L),de=[T(ie),T(se)];if(q!=null&&q!==!1){let Le=q===!0?A(t.BYTES):q;de.push(Fe("extraEntropy",Le))}let ae=kn(...de),ue=se;function Me(Le){let yt=I(Le);if(!h(yt))return;let wt=c(yt),lt=l.BASE.multiply(yt).toAffine(),Tt=a(lt.x);if(Tt===Vn)return;let xn=a(wt*a(ue+Tt*ie));if(xn===Vn)return;let Go=(lt.x===Tt?0:2)|Number(lt.y&_r),fa=xn;return U&&p(xn)&&(fa=m(xn),Go^=1),new w(Tt,fa,Go)}return{seed:ae,k2sig:Me}}let N={lowS:e.lowS,prehash:!1},B={lowS:e.lowS,prehash:!1};function k(D,L,$=N){let{seed:C,k2sig:A}=P(D,L,$),U=e;return Vh(U.hash.outputLen,U.nByteLength,U.hmac)(C,A)}l.BASE._setWindowSize(8);function X(D,L,$,C=B){let A=D;if(L=Fe("msgHash",L),$=Fe("publicKey",$),"strict"in C)throw new Error("options.strict was renamed to lowS");let{lowS:U,prehash:V}=C,q,se;try{if(typeof A=="string"||fo(A))try{q=w.fromDER(A)}catch(lt){if(!(lt instanceof fs.Err))throw lt;q=w.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:lt,s:Tt}=A;q=new w(lt,Tt)}else throw new Error("PARSE");se=l.fromHex($)}catch(lt){if(lt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(U&&q.hasHighS())return!1;V&&(L=e.hash(L));let{r:ie,s:de}=q,ae=S(L),ue=c(de),Me=a(ae*ue),Le=a(ie*ue),yt=l.BASE.multiplyAndAddUnsafe(se,Me,Le)?.toAffine();return yt?a(yt.x)===ie:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:v,sign:k,verify:X,ProjectivePoint:l,Signature:w,utils:b}}function vS(r){return{hash:r,hmac:(e,...t)=>po(r,e,sl(...t)),randomBytes:ss}}function Gm(r,e){let t=n=>qm({...r,...vS(n)});return Object.freeze({...t(e),create:t})}var Ym=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Wm=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),RS=BigInt(1),h0=BigInt(2),zm=(r,e)=>(r+e/h0)/e;function SS(r){let e=Ym,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,u=Ve(d,t,e)*d%e,h=Ve(u,t,e)*d%e,f=Ve(h,h0,e)*l%e,p=Ve(f,o,e)*f%e,m=Ve(p,s,e)*p%e,y=Ve(m,a,e)*m%e,w=Ve(y,c,e)*y%e,b=Ve(w,a,e)*m%e,E=Ve(b,t,e)*d%e,x=Ve(E,i,e)*p%e,v=Ve(x,n,e)*l%e,I=Ve(v,h0,e);if(!p0.eql(p0.sqr(I),r))throw new Error("Cannot find square root");return I}var p0=fl(Ym,void 0,void 0,{sqrt:SS}),Wr=Gm({a:BigInt(0),b:BigInt(7),Fp:p0,n:Wm,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Wm,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-RS*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=zm(s*r,e),c=zm(-n*r,e),l=De(r-a*t-c*o,e),d=De(-a*n-c*s,e),u=l>i,h=d>i;if(u&&(l=e-l),h&&(d=e-d),l>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:h,k2:d}}}},vo),_U=BigInt(0);var AU=Wr.ProjectivePoint;function Xm(){return Wr.utils.randomPrivateKey()}function Qm(r,e){let t=Ne.digest(e instanceof Uint8Array?e:e.subarray());if(vr(t))return t.then(({digest:n})=>Wr.sign(n,r).toDERRawBytes()).catch(n=>{throw new g(String(n),"ERR_INVALID_INPUT")});try{return Wr.sign(t.digest,r).toDERRawBytes()}catch(n){throw new g(String(n),"ERR_INVALID_INPUT")}}function jm(r,e,t){let n=Ne.digest(t instanceof Uint8Array?t:t.subarray());if(vr(n))return n.then(({digest:o})=>Wr.verify(e,o,r)).catch(o=>{throw new g(String(o),"ERR_INVALID_INPUT")});try{return Wr.verify(e,n.digest,r)}catch(o){throw new g(String(o),"ERR_INVALID_INPUT")}}function Zm(r){return Wr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Jm(r){try{Wr.getPublicKey(r,!0)}catch(e){throw new g(String(e),"ERR_INVALID_PRIVATE_KEY")}}function m0(r){try{Wr.ProjectivePoint.fromHex(r)}catch(e){throw new g(String(e),"ERR_INVALID_PUBLIC_KEY")}}function e6(r){try{return Wr.getPublicKey(r,!0)}catch(e){throw new g(String(e),"ERR_INVALID_PRIVATE_KEY")}}var hs=class{_key;constructor(e){m0(e),this._key=e}verify(e,t){return jm(this._key,t,e)}marshal(){return Zm(this._key)}get bytes(){return $r.encode({Type:Ke.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}async hash(){let e=Ne.digest(this.bytes),t;return vr(e)?{bytes:t}=await e:t=e.bytes,t}},ps=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??e6(e),Jm(this._key),m0(this._publicKey)}sign(e){return Qm(this._key,e)}get public(){return new hs(this._publicKey)}marshal(){return this._key}get bytes(){return Hr.encode({Type:Ke.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return O(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return ri(this.bytes,e);throw new g(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function AS(r){return new ps(r)}function IS(r){return new hs(r)}async function DS(){let r=Xm();return new ps(r)}var Kn={rsa:d0,ed25519:Jh,secp256k1:g0};function y0(r){let e=Object.keys(Kn).join(" / ");return new g(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function w0(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return Kn[r];throw y0(r)}async function Oa(r,e){return w0(r).generateKeyPair(e??2048)}async function TS(r,e,t){if(r.toLowerCase()!=="ed25519")throw new g("Seed key derivation is unimplemented for RSA or secp256k1","ERR_UNSUPPORTED_KEY_DERIVATION_TYPE");return Zh(e)}function zr(r){let e=$r.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Ke.RSA:return Kn.rsa.unmarshalRsaPublicKey(t);case Ke.Ed25519:return Kn.ed25519.unmarshalEd25519PublicKey(t);case Ke.Secp256k1:return Kn.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw y0(e.Type??"unknown")}}function E0(r,e){return e=(e??"rsa").toLowerCase(),w0(e),r.bytes}async function Ar(r){let e=Hr.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Ke.RSA:return Kn.rsa.unmarshalRsaPrivateKey(t);case Ke.Ed25519:return Kn.ed25519.unmarshalEd25519PrivateKey(t);case Ke.Secp256k1:return Kn.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw y0(e.Type??"RSA")}}function b0(r,e){return e=(e??"rsa").toLowerCase(),w0(e),r.bytes}async function li(r,e){try{let t=await G8(r,e);return await Ar(t)}catch{}if(!r.includes("BEGIN"))throw new g("Encrypted key was not a libp2p-key or a PEM file","ERR_INVALID_IMPORT_FORMAT");return c0(r,e)}var Ba=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),Ro=new Uint32Array(80),x0=class extends ao{constructor(){super(64,20,8,!1),this.A=Ba[0]|0,this.B=Ba[1]|0,this.C=Ba[2]|0,this.D=Ba[3]|0,this.E=Ba[4]|0}get(){let{A:e,B:t,C:n,D:o,E:s}=this;return[e,t,n,o,s]}set(e,t,n,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0}process(e,t){for(let c=0;c<16;c++,t+=4)Ro[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Ro[c]=ol(Ro[c-3]^Ro[c-8]^Ro[c-14]^Ro[c-16],1);let{A:n,B:o,C:s,D:i,E:a}=this;for(let c=0;c<80;c++){let l,d;c<20?(l=il(o,s,i),d=1518500249):c<40?(l=o^s^i,d=1859775393):c<60?(l=al(o,s,i),d=2400959708):(l=o^s^i,d=3395469782);let u=ol(n,5)+l+a+d+Ro[c]|0;a=i,i=s,s=ol(o,30),o=n,n=u}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,this.set(n,o,s,i,a)}roundClean(){Ro.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}},t6=Zs(()=>new x0);var r6={sha1:t6,"sha2-256":vo,"sha2-512":uo};function Ma(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(r6).join(" / ");throw new g(`Hash '${o}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let s=r6[o],i=Q8(s,r,e,{c:t,dkLen:n});return st.encode(i).substring(1)}var v0=class extends it{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Fa(r){let{name:e,metrics:t}=r,n;return t!=null?n=new v0({name:e,metrics:t}):n=new it,n}var $n=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=st.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=st.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=st.encode(e.multihash.bytes);this.blocks.set(n,t)}};function kS(r){let e=new Uint8Array(r.reduce((n,o)=>n+Se(o),0)),t=0;for(let n of r)e=$e(n,e,t),t+=Se(n);return e}var i6=kS;function R0(r){return i6([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var uu=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t=new $n,n=new Set;for(let[o,s]of this.wants.entries())try{let i=await this.blockstore.get(s.cid,e);s.wantType===rt.WantHave?i.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",s.cid),n.add(o),t.addBlock(s.cid,{data:i,prefix:R0(s.cid)})):(this.log("sending have for %c",s.cid),t.addBlockPresence(s.cid,{cid:s.cid.bytes,type:xr.HaveBlock})):(this.log("sending block for %c",s.cid),n.add(o),t.addBlock(s.cid,{data:i,prefix:R0(s.cid)}))}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i;if(this.log("do not have block for %c",s.cid),!s.sendDontHave||s.sentDontHave===!0)continue;s.sentDontHave=!0,t.addBlockPresence(s.cid,{cid:s.cid.bytes,type:xr.DontHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((o,s)=>o+s.data.byteLength,0));for(let o of n)this.wants.delete(o)}}};var du=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=Fa({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new uu({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let o of t.wantlist.entries){let s=le.decode(o.cid),i=O(s.multihash.bytes,"base64");o.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,s),n.wants.delete(i)):(o.wantType===rt.WantHave?this.log("peer %p wanted block presence for %c",e,s):this.log("peer %p wanted block for %c",e,s),n.wants.set(i,{cid:s,priority:o.priority,wantType:o.wantType??rt.WantBlock,sendDontHave:o.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=O(e.multihash.bytes,"base64"),o=[];for(let s of this.ledgerMap.values())s.wants.has(n)&&o.push(s);await Promise.all(o.map(async s=>s.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var sr=Qe(d6(),1);sr.default.formatters.b=r=>r==null?"undefined":Ye.baseEncode(r);sr.default.formatters.t=r=>r==null?"undefined":ut.baseEncode(r);sr.default.formatters.m=r=>r==null?"undefined":st.baseEncode(r);sr.default.formatters.p=r=>r==null?"undefined":r.toString();sr.default.formatters.c=r=>r==null?"undefined":r.toString();sr.default.formatters.k=r=>r==null?"undefined":r.toString();sr.default.formatters.a=r=>r==null?"undefined":r.toString();function HS(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function So(){return{forComponent(r){return ir(r)}}}function ir(r){let e=HS(`${r}:trace`);return sr.default.enabled(`${r}:trace`)&&sr.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,sr.default)(`${r}:trace`)),Object.assign((0,sr.default)(r),{error:(0,sr.default)(`${r}:error`),trace:e})}var _0=Qe(h6(),1);var _o=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},A0=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},p6=r=>globalThis.DOMException===void 0?new A0(r):new DOMException(r),m6=r=>{let e=r.reason===void 0?p6("This operation was aborted."):r.reason;return e instanceof Error?e:p6(e)};function Yr(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((l,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&d(m6(h)),h.addEventListener("abort",()=>{d(m6(h))})}if(t===Number.POSITIVE_INFINITY){r.then(l,d);return}let u=new _o;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(h){d(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?d(o):(u.message=o??`Promise timed out after ${t} milliseconds`,d(u))},t),(async()=>{try{l(await r)}catch(h){d(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function I0(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Ka=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=I0(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var Ir=class extends _0.default{#e;#t;#r=0;#o;#a;#l=0;#s;#u;#n;#m;#i=0;#d;#c;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ka,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#o=e.intervalCap,this.#a=e.interval,this.#n=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#c=e.autoStart===!1}get#E(){return this.#t||this.#r<this.#o}get#b(){return this.#i<this.#d}#x(){this.#i--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#u=void 0}get#R(){let e=Date.now();if(this.#s===void 0){let t=this.#l-e;if(t<0)this.#r=this.#e?this.#i:0;else return this.#u===void 0&&(this.#u=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#n.size===0)return this.#s&&clearInterval(this.#s),this.#s=void 0,this.emit("empty"),this.#i===0&&this.emit("idle"),!1;if(!this.#c){let e=!this.#R;if(this.#E&&this.#b){let t=this.#n.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#s!==void 0||(this.#s=setInterval(()=>{this.#w()},this.#a),this.#l=Date.now()+this.#a)}#w(){this.#r===0&&this.#i===0&&this.#s&&(clearInterval(this.#s),this.#s=void 0),this.#r=this.#e?this.#i:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#d}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#d=e,this.#h()}async#S(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#i++,this.#r++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=Yr(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#S(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof _o&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#x()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#c?(this.#c=!1,this.#h(),this):this}pause(){this.#c=!0}clear(){this.#n=new this.#m}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#i===0&&this.#n.size===0||await this.#p("idle")}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#i}get isPaused(){return this.#c}};function mu(r){let e=[ar.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var D0=60;function gu(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:ar[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:ar[e.type],TTL:e.TTL??e.ttl??D0,data:e.data instanceof Uint8Array?O(e.data):e.data}))}}var WS=4;function T0(r,e={}){let t=new Ir({concurrency:e.queryConcurrency??WS});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),mu(o.types).forEach(a=>{s.append("type",ar[a])}),o.onProgress?.(new me("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=gu(await a.json());return o.onProgress?.(new me("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function g6(){return[T0("https://cloudflare-dns.com/dns-query"),T0("https://dns.google/resolve")]}var w6=Qe(k0(),1);var C0=class{lru;constructor(e){this.lru=(0,w6.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return gu({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:ar[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??D0)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function E6(r){return new C0(r)}var zS=1e3,yu=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=E6(e.cacheSize??zS),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=g6())}async query(e,t={}){let n=mu(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new me("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let d of l.Answer)this.cache.add(e,d);return l}catch(l){a.push(l),t.onProgress?.(new me("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var ar;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(ar||(ar={}));function wu(r={}){return new yu(r)}var YS=["string","number","bigint","symbol"],XS=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function b6(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(YS.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(QS(r))return"Buffer";let t=jS(r);return t||"Object"}function QS(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function jS(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(XS.includes(e))return e}var _=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};_.uint=new _(0,"uint",!0);_.negint=new _(1,"negint",!0);_.bytes=new _(2,"bytes",!0);_.string=new _(3,"string",!0);_.array=new _(4,"array",!1);_.map=new _(5,"map",!1);_.tag=new _(6,"tag",!1);_.float=new _(7,"float",!0);_.false=new _(7,"false",!0);_.true=new _(7,"true",!0);_.null=new _(7,"null",!0);_.undefined=new _(7,"undefined",!0);_.break=new _(7,"break",!0);var F=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var hi=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ZS=new TextDecoder,JS=new TextEncoder;function Eu(r){return hi&&globalThis.Buffer.isBuffer(r)}function $a(r){return r instanceof Uint8Array?Eu(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var S6=hi?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):v6(r,e,t):(r,e,t)=>t-e>64?ZS.decode(r.subarray(e,t)):v6(r,e,t),bu=hi?r=>r.length>64?globalThis.Buffer.from(r):x6(r):r=>r.length>64?JS.encode(r):x6(r),hn=r=>Uint8Array.from(r),pi=hi?(r,e,t)=>Eu(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),_6=hi?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),$a(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},A6=hi?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function I6(r,e){if(Eu(r)&&Eu(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function x6(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),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 e}function v6(r,e,t){let n=[];for(;e<t;){let o=r[e],s=null,i=o>239?4:o>223?3:o>191?2:1;if(e+i<=t){let a,c,l,d;switch(i){case 1:o<128&&(s=o);break;case 2:a=r[e+1],(a&192)===128&&(d=(o&31)<<6|a&63,d>127&&(s=d));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(d=(o&15)<<12|(a&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(d=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,d>65535&&d<1114112&&(s=d))}}s===null?(s=65533,i=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),e+=i}return N0(n)}var R6=4096;function N0(r){let e=r.length;if(e<=R6)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=R6));return t}var e_=256,Ha=class{constructor(e=e_){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=A6(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=pi(n,0,this.cursor)}else t=_6(this.chunks,this.cursor);return e&&this.reset(),t}};var Q="CBOR decode error:",mi="CBOR encode error:",qa=[];qa[23]=1;qa[24]=2;qa[25]=3;qa[26]=5;qa[27]=9;function Hn(r,e,t){if(r.length-e<t)throw new Error(`${Q} not enough data for type`)}var gt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function cr(r,e,t){Hn(r,e,1);let n=r[e];if(t.strict===!0&&n<gt[0])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);return n}function lr(r,e,t){Hn(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<gt[1])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);return n}function ur(r,e,t){Hn(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<gt[2])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);return n}function dr(r,e,t){Hn(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],s=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&s<gt[3])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${Q} integers outside of the safe integer range are not supported`)}function D6(r,e,t,n){return new F(_.uint,cr(r,e+1,n),2)}function T6(r,e,t,n){return new F(_.uint,lr(r,e+1,n),3)}function k6(r,e,t,n){return new F(_.uint,ur(r,e+1,n),5)}function C6(r,e,t,n){return new F(_.uint,dr(r,e+1,n),9)}function Dr(r,e){return bt(r,0,e.value)}function bt(r,e,t){if(t<gt[0]){let n=Number(t);r.push([e|n])}else if(t<gt[1]){let n=Number(t);r.push([e|24,n])}else if(t<gt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<gt[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<gt[4]){let o=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=s&255,s=s>>8,o[7]=s&255,s=s>>8,o[6]=s&255,s=s>>8,o[5]=s&255,o[4]=i&255,i=i>>8,o[3]=i&255,i=i>>8,o[2]=i&255,i=i>>8,o[1]=i&255,r.push(o)}else throw new Error(`${Q} encountered BigInt larger than allowable range`)}}Dr.encodedSize=function(e){return bt.encodedSize(e.value)};bt.encodedSize=function(e){return e<gt[0]?1:e<gt[1]?2:e<gt[2]?3:e<gt[3]?5:9};Dr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function N6(r,e,t,n){return new F(_.negint,-1-cr(r,e+1,n),2)}function L6(r,e,t,n){return new F(_.negint,-1-lr(r,e+1,n),3)}function P6(r,e,t,n){return new F(_.negint,-1-ur(r,e+1,n),5)}var L0=BigInt(-1),O6=BigInt(1);function B6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o!="bigint"){let s=-1-o;if(s>=Number.MIN_SAFE_INTEGER)return new F(_.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${Q} integers outside of the safe integer range are not supported`);return new F(_.negint,L0-BigInt(o),9)}function xu(r,e){let t=e.value,n=typeof t=="bigint"?t*L0-O6:t*-1-1;bt(r,e.type.majorEncoded,n)}xu.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*L0-O6:t*-1-1;return n<gt[0]?1:n<gt[1]?2:n<gt[2]?3:n<gt[3]?5:9};xu.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Ga(r,e,t,n){Hn(r,e,t+n);let o=pi(r,e+t,e+t+n);return new F(_.bytes,o,t+n)}function M6(r,e,t,n){return Ga(r,e,1,t)}function U6(r,e,t,n){return Ga(r,e,2,cr(r,e+1,n))}function F6(r,e,t,n){return Ga(r,e,3,lr(r,e+1,n))}function V6(r,e,t,n){return Ga(r,e,5,ur(r,e+1,n))}function K6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer bytes lengths not supported`);return Ga(r,e,9,o)}function vu(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===_.string?bu(r.value):r.value),r.encodedBytes}function gi(r,e){let t=vu(e);bt(r,e.type.majorEncoded,t.length),r.push(t)}gi.encodedSize=function(e){let t=vu(e);return bt.encodedSize(t.length)+t.length};gi.compareTokens=function(e,t){return r_(vu(e),vu(t))};function r_(r,e){return r.length<e.length?-1:r.length>e.length?1:I6(r,e)}function Wa(r,e,t,n,o){let s=t+n;Hn(r,e,s);let i=new F(_.string,S6(r,e+t,e+s),s);return o.retainStringBytes===!0&&(i.byteValue=pi(r,e+t,e+s)),i}function $6(r,e,t,n){return Wa(r,e,1,t,n)}function H6(r,e,t,n){return Wa(r,e,2,cr(r,e+1,n),n)}function q6(r,e,t,n){return Wa(r,e,3,lr(r,e+1,n),n)}function G6(r,e,t,n){return Wa(r,e,5,ur(r,e+1,n),n)}function W6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer string lengths not supported`);return Wa(r,e,9,o,n)}var z6=gi;function yi(r,e,t,n){return new F(_.array,n,t)}function Y6(r,e,t,n){return yi(r,e,1,t)}function X6(r,e,t,n){return yi(r,e,2,cr(r,e+1,n))}function Q6(r,e,t,n){return yi(r,e,3,lr(r,e+1,n))}function j6(r,e,t,n){return yi(r,e,5,ur(r,e+1,n))}function Z6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer array lengths not supported`);return yi(r,e,9,o)}function J6(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Q} indefinite length items not allowed`);return yi(r,e,1,1/0)}function Ru(r,e){bt(r,_.array.majorEncoded,e.value)}Ru.compareTokens=Dr.compareTokens;Ru.encodedSize=function(e){return bt.encodedSize(e.value)};function wi(r,e,t,n){return new F(_.map,n,t)}function e5(r,e,t,n){return wi(r,e,1,t)}function t5(r,e,t,n){return wi(r,e,2,cr(r,e+1,n))}function r5(r,e,t,n){return wi(r,e,3,lr(r,e+1,n))}function n5(r,e,t,n){return wi(r,e,5,ur(r,e+1,n))}function o5(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer map lengths not supported`);return wi(r,e,9,o)}function s5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Q} indefinite length items not allowed`);return wi(r,e,1,1/0)}function Su(r,e){bt(r,_.map.majorEncoded,e.value)}Su.compareTokens=Dr.compareTokens;Su.encodedSize=function(e){return bt.encodedSize(e.value)};function i5(r,e,t,n){return new F(_.tag,t,1)}function a5(r,e,t,n){return new F(_.tag,cr(r,e+1,n),2)}function c5(r,e,t,n){return new F(_.tag,lr(r,e+1,n),3)}function l5(r,e,t,n){return new F(_.tag,ur(r,e+1,n),5)}function u5(r,e,t,n){return new F(_.tag,dr(r,e+1,n),9)}function _u(r,e){bt(r,_.tag.majorEncoded,e.value)}_u.compareTokens=Dr.compareTokens;_u.encodedSize=function(e){return bt.encodedSize(e.value)};var c_=20,l_=21,u_=22,d_=23;function d5(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Q} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new F(_.null,null,1):new F(_.undefined,void 0,1)}function f5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Q} indefinite length items not allowed`);return new F(_.break,void 0,1)}function P0(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Q} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Q} Infinity values are not supported`)}return new F(_.float,r,e)}function h5(r,e,t,n){return P0(O0(r,e+1),3,n)}function p5(r,e,t,n){return P0(B0(r,e+1),5,n)}function m5(r,e,t,n){return P0(E5(r,e+1),9,n)}function Au(r,e,t){let n=e.value;if(n===!1)r.push([_.float.majorEncoded|c_]);else if(n===!0)r.push([_.float.majorEncoded|l_]);else if(n===null)r.push([_.float.majorEncoded|u_]);else if(n===void 0)r.push([_.float.majorEncoded|d_]);else{let o,s=!1;(!t||t.float64!==!0)&&(y5(n),o=O0(Xr,1),n===o||Number.isNaN(n)?(Xr[0]=249,r.push(Xr.slice(0,3)),s=!0):(w5(n),o=B0(Xr,1),n===o&&(Xr[0]=250,r.push(Xr.slice(0,5)),s=!0))),s||(f_(n),o=E5(Xr,1),Xr[0]=251,r.push(Xr.slice(0,9)))}}Au.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){y5(n);let o=O0(Xr,1);if(n===o||Number.isNaN(n))return 3;if(w5(n),o=B0(Xr,1),n===o)return 5}return 9};var g5=new ArrayBuffer(9),Tr=new DataView(g5,1),Xr=new Uint8Array(g5,0);function y5(r){if(r===1/0)Tr.setUint16(0,31744,!1);else if(r===-1/0)Tr.setUint16(0,64512,!1);else if(Number.isNaN(r))Tr.setUint16(0,32256,!1);else{Tr.setFloat32(0,r);let e=Tr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Tr.setUint16(0,31744,!1);else if(t===0)Tr.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Tr.setUint16(0,0):o<-14?Tr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Tr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function O0(r,e){if(r.length-e<2)throw new Error(`${Q} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,s;return n===0?s=o*2**-24:n!==31?s=(o+1024)*2**(n-25):s=o===0?1/0:NaN,t&32768?-s:s}function w5(r){Tr.setFloat32(0,r,!1)}function B0(r,e){if(r.length-e<4)throw new Error(`${Q} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function f_(r){Tr.setFloat64(0,r,!1)}function E5(r,e){if(r.length-e<8)throw new Error(`${Q} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Au.compareTokens=Dr.compareTokens;function _e(r,e,t){throw new Error(`${Q} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Iu(r){return()=>{throw new Error(`${Q} ${r}`)}}var K=[];for(let r=0;r<=23;r++)K[r]=_e;K[24]=D6;K[25]=T6;K[26]=k6;K[27]=C6;K[28]=_e;K[29]=_e;K[30]=_e;K[31]=_e;for(let r=32;r<=55;r++)K[r]=_e;K[56]=N6;K[57]=L6;K[58]=P6;K[59]=B6;K[60]=_e;K[61]=_e;K[62]=_e;K[63]=_e;for(let r=64;r<=87;r++)K[r]=M6;K[88]=U6;K[89]=F6;K[90]=V6;K[91]=K6;K[92]=_e;K[93]=_e;K[94]=_e;K[95]=Iu("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)K[r]=$6;K[120]=H6;K[121]=q6;K[122]=G6;K[123]=W6;K[124]=_e;K[125]=_e;K[126]=_e;K[127]=Iu("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)K[r]=Y6;K[152]=X6;K[153]=Q6;K[154]=j6;K[155]=Z6;K[156]=_e;K[157]=_e;K[158]=_e;K[159]=J6;for(let r=160;r<=183;r++)K[r]=e5;K[184]=t5;K[185]=r5;K[186]=n5;K[187]=o5;K[188]=_e;K[189]=_e;K[190]=_e;K[191]=s5;for(let r=192;r<=215;r++)K[r]=i5;K[216]=a5;K[217]=c5;K[218]=l5;K[219]=u5;K[220]=_e;K[221]=_e;K[222]=_e;K[223]=_e;for(let r=224;r<=243;r++)K[r]=Iu("simple values are not supported");K[244]=_e;K[245]=_e;K[246]=_e;K[247]=d5;K[248]=Iu("simple values are not supported");K[249]=h5;K[250]=p5;K[251]=m5;K[252]=_e;K[253]=_e;K[254]=_e;K[255]=f5;var Qr=[];for(let r=0;r<24;r++)Qr[r]=new F(_.uint,r,1);for(let r=-1;r>=-24;r--)Qr[31-r]=new F(_.negint,r,1);Qr[64]=new F(_.bytes,new Uint8Array(0),1);Qr[96]=new F(_.string,"",1);Qr[128]=new F(_.array,0,1);Qr[160]=new F(_.map,0,1);Qr[244]=new F(_.false,!1,1);Qr[245]=new F(_.true,!0,1);Qr[246]=new F(_.null,null,1);function b5(r){switch(r.type){case _.false:return hn([244]);case _.true:return hn([245]);case _.null:return hn([246]);case _.bytes:return r.value.length?void 0:hn([64]);case _.string:return r.value===""?hn([96]):void 0;case _.array:return r.value===0?hn([128]):void 0;case _.map:return r.value===0?hn([160]):void 0;case _.uint:return r.value<24?hn([Number(r.value)]):void 0;case _.negint:if(r.value>=-24)return hn([31-Number(r.value)])}}var p_={float64:!1,mapSorter:y_,quickEncodeToken:b5};function m_(){let r=[];return r[_.uint.major]=Dr,r[_.negint.major]=xu,r[_.bytes.major]=gi,r[_.string.major]=z6,r[_.array.major]=Ru,r[_.map.major]=Su,r[_.tag.major]=_u,r[_.float.major]=Au,r}var x5=m_(),M0=new Ha,Tu=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${mi} object contains circular references`);return new r(t,e)}},Ao={null:new F(_.null,null),undefined:new F(_.undefined,void 0),true:new F(_.true,!0),false:new F(_.false,!1),emptyArray:new F(_.array,0),emptyMap:new F(_.map,0)},Io={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new F(_.float,r):r>=0?new F(_.uint,r):new F(_.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new F(_.uint,r):new F(_.negint,r)},Uint8Array(r,e,t,n){return new F(_.bytes,r)},string(r,e,t,n){return new F(_.string,r)},boolean(r,e,t,n){return r?Ao.true:Ao.false},null(r,e,t,n){return Ao.null},undefined(r,e,t,n){return Ao.undefined},ArrayBuffer(r,e,t,n){return new F(_.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new F(_.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Ao.emptyArray,new F(_.break)]:Ao.emptyArray;n=Tu.createCheck(n,r);let o=[],s=0;for(let i of r)o[s++]=Du(i,t,n);return t.addBreakTokens?[new F(_.array,r.length),o,new F(_.break)]:[new F(_.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",s=o?r.keys():Object.keys(r),i=o?r.size:s.length;if(!i)return t.addBreakTokens===!0?[Ao.emptyMap,new F(_.break)]:Ao.emptyMap;n=Tu.createCheck(n,r);let a=[],c=0;for(let l of s)a[c++]=[Du(l,t,n),Du(o?r.get(l):r[l],t,n)];return g_(a,t),t.addBreakTokens?[new F(_.map,i),a,new F(_.break)]:[new F(_.map,i),a]}};Io.Map=Io.Object;Io.Buffer=Io.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Io[`${r}Array`]=Io.DataView;function Du(r,e={},t){let n=b6(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Io[n];if(typeof o=="function"){let i=o(r,n,e,t);if(i!=null)return i}let s=Io[n];if(!s)throw new Error(`${mi} unsupported type: ${n}`);return s(r,n,e,t)}function g_(r,e){e.mapSorter&&r.sort(e.mapSorter)}function y_(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,s=x5[o].compareTokens(t,n);return s===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),s}function v5(r,e,t,n){if(Array.isArray(e))for(let o of e)v5(r,o,t,n);else t[e.type.major](r,e,n)}function R5(r,e,t){let n=Du(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let s=e[n.type.major];if(s.encodedSize){let i=s.encodedSize(n,t),a=new Ha(i);if(s(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return $a(a.chunks[0])}}return M0.reset(),v5(M0,n,e,t),M0.toBytes(!0)}function Ei(r,e){return e=Object.assign({},p_,e),R5(r,x5,e)}var w_={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},ku=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Qr[e];if(t===void 0){let n=K[e];if(!n)throw new Error(`${Q} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},za=Symbol.for("DONE"),Cu=Symbol.for("BREAK");function E_(r,e,t){let n=[];for(let o=0;o<r.value;o++){let s=bi(e,t);if(s===Cu){if(r.value===1/0)break;throw new Error(`${Q} got unexpected break to lengthed array`)}if(s===za)throw new Error(`${Q} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=s}return n}function b_(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},s=n?new Map:void 0;for(let i=0;i<r.value;i++){let a=bi(e,t);if(a===Cu){if(r.value===1/0)break;throw new Error(`${Q} got unexpected break to lengthed map`)}if(a===za)throw new Error(`${Q} found map but not enough entries (got ${i} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${Q} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&s.has(a)||!n&&a in o))throw new Error(`${Q} found repeat map key "${a}"`);let c=bi(e,t);if(c===za)throw new Error(`${Q} found map but not enough entries (got ${i} [no value], expected ${r.value})`);n?s.set(a,c):o[a]=c}return n?s:o}function bi(r,e){if(r.done())return za;let t=r.next();if(t.type===_.break)return Cu;if(t.type.terminal)return t.value;if(t.type===_.array)return E_(t,r,e);if(t.type===_.map)return b_(t,r,e);if(t.type===_.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=bi(r,e);return e.tags[t.value](n)}throw new Error(`${Q} tag not supported (${t.value})`)}throw new Error("unsupported")}function U0(r,e){if(!(r instanceof Uint8Array))throw new Error(`${Q} data to decode must be a Uint8Array`);e=Object.assign({},w_,e);let t=e.tokenizer||new ku(r,e),n=bi(t,e);if(n===za)throw new Error(`${Q} did not find any content to decode`);if(n===Cu)throw new Error(`${Q} got unexpected break`);return[n,r.subarray(t.pos())]}function kr(r,e){let[t,n]=U0(r,e);if(n.length>0)throw new Error(`${Q} too many terminals, data makes no sense`);return t}var qn="/",S5=new TextEncoder().encode(qn),Lu=S5[0],Pe=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=M(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Lu)throw new Error("Invalid key")}toString(e="utf8"){return O(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(qn))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=S5),this._buf[0]!==Lu){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Lu,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Lu;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(qn).slice(1)}type(){return x_(this.baseNamespace())}name(){return v_(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(qn)||(e+=qn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(qn):new r(e.slice(0,-1).join(qn))}child(e){return this.toString()===qn?e:e.toString()===qn?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...R_(e.map(t=>t.namespaces()))])}};function x_(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function v_(r){let e=r.split(":");return e[e.length-1]}function R_(r){return[].concat(...r)}var D5="/pin/",_5="/pinned-block/",F0=so,A5=1;function I5(r){return r.version===0&&(r=r.toV1()),new Pe(`${D5}${r.toString(F0)}`)}var Pu=class{datastore;blockstore;dagWalkers;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.dagWalkers=n}async*add(e,t={}){let n=I5(e);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let s=new tr({concurrency:A5});for await(let a of this.#e(e,s,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>Z(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Ei(i),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=this.dagWalkers[e.code];if(o==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let s=await this.blockstore.get(e,n);yield e;for await(let i of o.walk(s))yield*await t.add(async()=>this.#e(i,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new Pe(`${_5}${F0.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=kr(await this.datastore.get(o,n))}catch(a){if(a.code!=="ERR_NOT_FOUND")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Ei(s),n),n.onProgress?.(new me("helia:pin:add",e))}}async*rm(e,t={}){let n=I5(e),o=await this.datastore.get(n,t),s=kr(o);await this.datastore.delete(n,t);let i=new tr({concurrency:A5});for await(let a of this.#e(e,i,{...t,depth:s.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>Z(l,e.bytes)),!0),{...t,depth:s.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:D5+(e.cid!=null?`${e.cid.toString(so)}`:"")},e)){let o=le.parse(t.toString().substring(5),so),s=kr(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new Pe(`${_5}${F0.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}};var S_=5,Ou=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??S_}async start(){await cn(...this.routers)}async stop(){await ln(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new g("No content routers available","ERR_NO_ROUTERS_AVAILABLE");let n=new wr({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of Mt(n.toGenerator(),...xi(this.routers,"findProviders").map(s=>s.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let s=await this.findPeer(o.id,t);return s.multiaddrs.length===0?null:s}catch(s){return this.log.error("could not load multiaddrs for peer %p",o.id,s),null}},{peerId:o.id,signal:t.signal}).catch(s=>{this.log.error("could not load multiaddrs for peer %p",o.id,s)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new g("No content routers available","ERR_NO_ROUTERS_AVAILABLE");await Promise.all(xi(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async put(e,t,n){await Promise.all(xi(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(xi(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new g("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");let n=this,o=Mt(...xi(this.routers,"findPeer").map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s;throw new g("Could not find peer in routing","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new g("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");for await(let n of Mt(...xi(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function xi(r,e){return r.filter(t=>t[e]!=null)}var Do={},vi=r=>{r.addEventListener("message",e=>{vi.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{vi.dispatchEvent("message",r,e)})};vi.addEventListener=(r,e)=>{Do[r]==null&&(Do[r]=[]),Do[r].push(e)};vi.removeEventListener=(r,e)=>{Do[r]!=null&&(Do[r]=Do[r].filter(t=>t===e))};vi.dispatchEvent=function(r,e,t){Do[r]!=null&&Do[r].forEach(n=>n(e,t))};var V0=vi;var K0="lock:worker:request-read",$0="lock:worker:release-read",H0="lock:master:grant-read",q0="lock:worker:request-write",G0="lock:worker:release-write",W0="lock:master:grant-write";var T5=(r=21)=>Math.random().toString().substring(2);var k5=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=d=>{if(d==null||d.data==null)return;let u={type:d.data.type,name:d.data.name,identifier:d.data.identifier};u.type===n&&u.identifier===a.identifier&&(s.removeEventListener("message",l),c())};s.addEventListener("message",l)})}}}))},C5=(r,e,t,n)=>async()=>{let o=T5();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},__={singleProcess:!1},N5=r=>{if(r=Object.assign({},__,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return V0.addEventListener("message",k5(t,"requestReadLock",K0,$0,H0)),V0.addEventListener("message",k5(t,"requestWriteLock",q0,G0,W0)),t}return{isWorker:!0,readLock:t=>C5(t,K0,H0,$0),writeLock:t=>C5(t,q0,W0,G0)}};var ys={},To;async function z0(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>Yr((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var A_=(r,e)=>{if(To.isWorker===!0)return{readLock:To.readLock(r,e),writeLock:To.writeLock(r,e)};let t=new Ir({concurrency:1}),n;return{async readLock(){if(n!=null)return z0(n,e);n=new Ir({concurrency:e.concurrency,autoStart:!1});let o=n,s=z0(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,z0(t,e)}}},I_={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Ya(r){let e=Object.assign({},I_,r);return To==null&&(To=N5(e),To.isWorker!==!0&&(To.addEventListener("requestReadLock",t=>{ys[t.data.name]!=null&&ys[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),To.addEventListener("requestWriteLock",async t=>{ys[t.data.name]!=null&&ys[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),ys[e.name]==null&&(ys[e.name]=A_(e.name,e)),ys[e.name]}var Bu=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Ya({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await cn(this.child),this.started=!0}async stop(){await ln(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let s of e){if(await o.pins.isPinned(s))throw new Error("CID was pinned");yield s}}(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var P5=42;function D_(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=le.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new F(_.tag,P5),new F(_.bytes,t)]}function T_(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function k_(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var L5={float64:!0,typeEncoders:{Object:D_,undefined:T_,number:k_}},GK={...L5,typeEncoders:{...L5.typeEncoders}};function C_(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return le.decode(r.subarray(1))}var Y0={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Y0.tags[P5]=C_;var WK={...Y0,tags:Y0.tags.slice()};var O5=113;var B5=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===_.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===_.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[_.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s);e.push(o)}[_.negint.major](e,t){this[_.uint.major](e,t)}[_.bytes.major](e,t){throw new Error(`${mi} unsupported type: Uint8Array`)}[_.string.major](e,t){this.prefix(e);let n=bu(JSON.stringify(t.value));e.push(n.length>32?$a(n):n)}[_.array.major](e,t){this.prefix(e),this.inRecursive.push({type:_.array,elements:0}),e.push([91])}[_.map.major](e,t){this.prefix(e),this.inRecursive.push({type:_.map,elements:0}),e.push([123])}[_.tag.major](e,t){}[_.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(i.type===_.array)e.push([93]);else if(i.type===_.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${mi} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],s=!1;for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i),!s&&(o[i]===46||o[i]===101||o[i]===69)&&(s=!0);s||(o.push(46),o.push(48)),e.push(o)}};var ws=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${Q} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${Q} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new F(_.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${Q} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${Q} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let s=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(s);return n?new F(_.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new F(i>=0?_.uint:_.negint,i,this._pos-e):new F(i>=0?_.uint:_.negint,BigInt(s),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${Q} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let s=this._pos,i=0;s<this.data.length&&i<65536;s++,i++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,s));return this._pos=s+1,new F(_.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${Q} unexpected end of unicode escape sequence at position ${this._pos}`);let s=0;for(let i=0;i<4;i++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${Q} unexpected unicode escape character at position ${this._pos}`);s=s*16+a,this._pos++}return s},o=()=>{let s=this.ch(),i=null,a=s>239?4:s>223?3:s>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${Q} unexpected unicode sequence at position ${this._pos}`);let c,l,d,u;switch(a){case 1:s<128&&(i=s);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(u=(s&31)<<6|c&63,u>127&&(i=u));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(u=(s&15)<<12|(c&63)<<6|l&63,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],d=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(d&192)===128&&(u=(s&15)<<18|(c&63)<<12|(l&63)<<6|d&63,u>65535&&u<1114112&&(i=u))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let s=this.ch(),i;switch(s){case 92:if(this._pos++,this.done())throw new Error(`${Q} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${Q} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new F(_.string,N0(t),this._pos-e);default:if(s<32)throw new Error(`${Q} invalid control character at position ${this._pos}`);s<128?(t.push(s),this._pos++):o()}}throw new Error(`${Q} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new F(_.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new F(_.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new F(_.null,null,4);case 102:return this.expect([102,97,108,115,101]),new F(_.false,!1,5);case 116:return this.expect([116,114,117,101]),new F(_.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${Q} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new F(_.break,void 0,1);if(this.ch()!==44)throw new Error(`${Q} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new F(_.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new F(_.break,void 0,1);if(this.ch()!==44)throw new Error(`${Q} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new F(_.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${Q} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${Q} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Mu(r,e){return e=Object.assign({tokenizer:new ws(r,e)},e),kr(r,e)}var P_={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};P_.tags[42]=le.parse;var U5=297;var l$=new TextDecoder;var u$=new TextEncoder;var B_=new TextDecoder;function X0(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Uu(r,e){let t;[t,e]=X0(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function F5(r,e){let t;return[t,e]=X0(r,e),[t&7,t>>3,e]}function M_(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=F5(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Uu(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Uu(r,n),e.Name=B_.decode(i)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=X0(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function V5(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=F5(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=Uu(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Uu(r,t),n.push(M_(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let i={};return s&&(i.Data=s),i.Links=n||[],i}var f$=new TextEncoder,h$=2**32,p$=2**31;var y$=new TextEncoder;function K5(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var $5=112;function H5(r){let e=K5(r),t=V5(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=le.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}var F_={codec:$5,*walk(r){yield*H5(r).Links.map(t=>t.Hash)}},V_={codec:Xc,*walk(){}},q5=42,K_={codec:O5,*walk(r){let e=[],t=[];t[q5]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let o=le.decode(n.subarray(1));return e.push(o),o},kr(r,{tags:t}),yield*e}},Q0=class extends ws{tokenBuffer;constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===_.map){let t=this._next();if(t.type===_.string&&t.value==="/"){let n=this._next();if(n.type===_.string){if(this._next().type!==_.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new F(_.tag,42,0)}if(n.type===_.map){let o=this._next();if(o.type===_.string&&o.value==="bytes"){let s=this._next();if(s.type===_.string){for(let a=0;a<2;a++)if(this._next().type!==_.break)throw new Error("Invalid encoded Bytes form");let i=st.decode(`m${s.value}`);return new F(_.bytes,i,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},$_={codec:U5,*walk(r){let e=[],t=[];t[q5]=n=>{let o=le.parse(n);return e.push(o),o},Mu(r,{tags:t,tokenizer:new Q0(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}},H_={codec:W4,*walk(){}};function G5(r=[]){let e={};return[F_,V_,K_,$_,H_,...r].forEach(t=>{e[t.codec]=t}),e}var j0=new Pe("/version"),W5=1;async function z5(r){if(!await r.has(j0)){await r.put(j0,M(`${W5}`));return}let e=await r.get(j0),t=O(e);if(parseInt(t,10)!==W5)throw new Error("Unknown datastore version, a datastore migration may be required")}function Y5(r=[]){let e={};return[Ne,Eh,Wt,...r].forEach(t=>{e[t.code]=t}),e}var Gn=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:o}of e)await this.put(n,o,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var Ri={};pe(Ri,{abortedError:()=>Y_,closeFailedError:()=>G_,deleteFailedError:()=>Q5,getFailedError:()=>W_,hasFailedError:()=>z_,notFoundError:()=>Xa,openFailedError:()=>q_,putFailedError:()=>X5});var Wn=Qe(Yo(),1);function q_(r){return r=r??new Error("Open failed"),(0,Wn.default)(r,"ERR_OPEN_FAILED")}function G_(r){return r=r??new Error("Close failed"),(0,Wn.default)(r,"ERR_CLOSE_FAILED")}function X5(r){return r=r??new Error("Put failed"),(0,Wn.default)(r,"ERR_PUT_FAILED")}function W_(r){return r=r??new Error("Get failed"),(0,Wn.default)(r,"ERR_GET_FAILED")}function Q5(r){return r=r??new Error("Delete failed"),(0,Wn.default)(r,"ERR_DELETE_FAILED")}function z_(r){return r=r??new Error("Has failed"),(0,Wn.default)(r,"ERR_HAS_FAILED")}function Xa(r){return r=r??new Error("Not Found"),(0,Wn.default)(r,"ERR_NOT_FOUND")}function Y_(r){return r=r??new Error("Aborted"),(0,Wn.default)(r,"ERR_ABORTED")}var Qa=class extends Gn{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(ut.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(ut.encode(e.multihash.bytes));if(t==null)throw Xa();return t}has(e){return this.data.has(ut.encode(e.multihash.bytes))}async delete(e){this.data.delete(ut.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:le.createV1(Xc,Mr(ut.decode(e))),block:t}}};function X_(r){return r[Symbol.asyncIterator]!=null}function Q_(r,e){let t=0;if(X_(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Vs(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var jr=Q_;var eH=ir("blockstore:core:tiered");var j5={...Ri};var Fu=0,Vu=class extends Gn{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===Fu||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===Fu)return e.multihash.digest;if(this.child==null)throw j5.notFoundError();return this.child.get(e)}has(e){return e.multihash.code===Fu?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==Fu&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function j_(r){return r[Symbol.asyncIterator]!=null}function Z5(r){return r?.then!=null}function Z_(r,e){let t=0;if(j_(r))return async function*(){for await(let c of r){let l=e(c,t++);Z5(l)&&await l,yield c}}();let n=Vs(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();if(typeof e(o,t++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=e(c,t++);Z5(l)&&await l,yield c}}();let a=e;return function*(){yield o;for(let c of n)a(c,t++),yield c}()}var ja=Z_;var Ku=class{child;hashers;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Vu(e.blockstore),this.hashers=e.hashers??{}}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new me("blocks:put:duplicate",e)),e):(n.onProgress?.(new me("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new me("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=jr(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new me("blocks:put-many:duplicate",s)),!i}),o=ja(n,async({cid:s,block:i})=>{t.onProgress?.(new me("blocks:put-many:providers:notify",s)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(s,i,t)))});t.onProgress?.(new me("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){t.onProgress?.(new me("blocks:get:providers:get",e));let n=await J5(e,this.components.blockBrokers,this.hashers[e.multihash.code],{...t,log:this.log});return t.onProgress?.(new me("blocks:get:blockstore:put",e)),await this.child.put(e,n,t),t.onProgress?.(new me("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n,t))),n}return t.onProgress?.(new me("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new me("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(ja(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){t.onProgress?.(new me("blocks:get-many:providers:get",n));let o=await J5(n,this.components.blockBrokers,this.hashers[n.multihash.code],{...t,log:this.log});t.onProgress?.(new me("blocks:get-many:blockstore:put",n)),await this.child.put(n,o,t),t.onProgress?.(new me("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,o,t)))}}))}async delete(e,t={}){t.onProgress?.(new me("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new me("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of e)yield n}(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new me("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},$u=class extends Ku{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await cn(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await ln(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new Z0({blockstore:this.child,blockBrokers:n,hashers:this.hashers,logger:this.logger},{root:e})}},Z0=class extends Ku{closeController;constructor(e,t){super(e),this.closeController=new AbortController,H(1/0,this.closeController.signal),this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=Ae([this.closeController.signal,n.signal]);H(1/0,o);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Ae([this.closeController.signal,e.signal]);H(1/0,t);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function J_(r){return typeof r.retrieve=="function"}var eA=(r,e)=>{if(e==null)throw new g(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`,"ERR_UNKNOWN_HASH_ALG");return async t=>{let n=await e.digest(t);if(!Z(n.digest,r.multihash.digest))throw new g("Hash of downloaded block did not match multihash from passed CID","ERR_HASH_MISMATCH")}};async function J5(r,e,t,n){let o=eA(r,t),s=new AbortController,i=Ae([s.signal,n.signal]);H(1/0,s.signal,i);let a=[];for(let c of e)J_(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,d=await c.retrieve(r,{...n,signal:i,validateFn:async u=>{await o(u),l=!0}});return l||await o(d),d}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{s.abort(),i.clear()}}var eg=1,tg=5;var J0=Qe(s6(),1);var tA=Math.LN2*Math.LN2,Hu=class r{static create(e,t=.005){let n=rA(e,t);return new r(n)}seeds;bits;buffer;constructor(e={}){e.seeds!=null?this.seeds=e.seeds:this.seeds=nA(e.hashes??8),this.bits=e.bits??1024,this.buffer=Ie(Math.ceil(this.bits/8))}add(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.seeds.length;t++){let o=J0.default.x86.hash32(e,this.seeds[t])%this.bits;this.setbit(o)}}has(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.seeds.length;t++){let o=J0.default.x86.hash32(e,this.seeds[t])%this.bits;if(!this.getbit(o))return!1}return!0}clear(){this.buffer.fill(0)}setbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;let o=this.buffer[t];o|=1<<n,this.buffer[t]=o}getbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;return(this.buffer[t]&1<<n)!==0}};function rA(r,e=.005){let t=Math.round(-1*r*Math.log(e)/tA),n=Math.round(t/r*Math.LN2);return{bits:t,hashes:n}}function nA(r){let e,t,n=[];for(let o=0;o<r;o++)for(e=new ce(pt(4)),n[o]=e.getUint32(0,!0),t=0;t<o;t++)if(n[o]===n[t]){o--;break}return n}var Es=class extends ye{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),H(1/0,this),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Hu.create(this.maxProviders)}async retrieve(e,t={}){let n=st.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let s=J();if(this.requests.set(n,s.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",e)}let i=!1,a=new tr({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{i=!0,s.resolve(l.detail.result)}),a.addEventListener("idle",()=>{i||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c",e,l),s.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,d)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(e,l,t),{provider:l}))).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,l)});try{return await s.promise}finally{this.removeEventListener("provider",c),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=J(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let i of this.findNewProviders(e,n)){if(s===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",s,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),s++,s===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",s);break}}if(this.log("found %d/%d new session peers",s,this.maxProviders),s<t)throw new g(`Found ${s} of ${t} ${this.name} providers for ${e}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",e,i.errors??i),o.reject(i)}),o.promise}};var qu=class{blockstore;datastore;pins;logger;routing;dagWalkers;hashers;dns;metrics;log;constructor(e){this.logger=e.logger??So(),this.log=this.logger.forComponent("helia"),this.hashers=Y5(e.hashers),this.dagWalkers=G5(e.dagWalkers),this.dns=e.dns??wu(),this.metrics=e.metrics;let t={blockstore:e.blockstore,datastore:e.datastore,hashers:this.hashers,dagWalkers:this.dagWalkers,logger:this.logger,blockBrokers:[],dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new Ou(t,{routers:(e.routers??[]).flatMap(o=>{let s=[o];return o[on]!=null&&s.push(o[on]),o[sn]!=null&&s.push(o[sn]),s}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new $u(t);this.pins=new Pu(e.datastore,n,this.dagWalkers),this.blockstore=new Bu(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await z5(this.datastore),await cn(this.blockstore,this.datastore,this.routing)}async stop(){await ln(this.blockstore,this.datastore,this.routing)}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await $t(o.deleteMany(async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new me("helia:gc:deleted",s))}catch(i){n.log.error("Error during gc",i),e.onProgress?.(new me("helia:gc:error",i))}}()))}finally{t()}this.log("gc finished")}};var e2=class extends Es{wantList;network;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let o=await this.wantList.wantSessionBlock(e,t,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has&&o.block!=null)return o.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield n.id}toEvictionKey(e){return e.toBytes()}equals(e,t){return e.equals(t)}};function rg(r,e){return new e2(r,e)}var Gu=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var t2=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Wu(r){let{name:e,metrics:t}=r,n;return t!=null?n=new t2({name:e,metrics:t}):n=new Map,n}function oA(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Bt(r);e.push(t),r=r.slice(Se(t))}return e}var ng=oA;var zu=class extends ye{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),H(1/0,this),this.peers=Fa({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=Wu({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=O(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??rt.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,o)),o.wantType===rt.WantHave&&t.wantType===rt.WantBlock&&(o.wantType=rt.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===rt.WantBlock?(await er(this,"block",t?.signal,{filter:a=>Z(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await er(this,"presence",t?.signal,{filter:i=>Z(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=J(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new $n;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o);for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer",s)}})).catch(e=>{this.log.error("error sending messages",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=O(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new $n;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:rt.WantHave,priority:1}),await this.network.sendMessage(t,o),(await er(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Z(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:rt.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new $n;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:rt.WantBlock,priority:1}),await this.network.sendMessage(t,o),(await er(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Z(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=O(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=ng(o.prefix),i=s[0],a=s[1],c=s[2],l=c===Ne.code?Ne:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let d=l.digest(o.data);d.then!=null&&(d=await d);let u=le.create(i===0?0:1,a,d);this.log("received block from %p for %c",e,u),this.safeDispatchEvent("block",{detail:{sender:e,cid:u,block:o.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:u,has:!0,block:o.data}});let h=O(u.multihash.bytes,"base64"),f=this.wants.get(h);f!=null&&(f.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=le.decode(o);this.log("received %s from %p for %c",s,e,i),this.safeDispatchEvent("presence",{detail:{sender:e,cid:i,has:s===xr.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new $n(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:rt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Yu=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.stats=new Gu(e),this.network=new rl(e,t),this.peerWantLists=new du({...e,network:this.network},t),this.wantList=new zu({...e,network:this.network},t)}createSession(e={}){return rg({wantList:this.wantList,network:this.network,logger:this.logger},e)}async want(e,t={}){let n=new AbortController,o=Ae([n.signal,t.signal]);H(1/0,n.signal,o),this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,s)});try{return(await this.wantList.wantBlock(e,{...t,signal:o})).block}finally{n.abort(),o.clear()}}async notify(e,t,n={}){await Promise.all([this.peerWantLists.receivedBlock(e,n),this.wantList.receivedBlock(e,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var og=(r,e={})=>new Yu(r,e);var r2=class{bitswap;started;constructor(e,t={}){let{hashers:n}=e;this.bitswap=og(e,{hashLoader:{getHasher:async o=>{let s;if(typeof o=="string"?s=Object.values(n).find(i=>i.name===o):s=n[o],s!=null)return s;throw new Error(`Could not load hasher for code/name "${o}"`)}},...t}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t,n){await this.bitswap.notify(e,t,n)}async retrieve(e,t={}){return this.bitswap.want(e,t)}createSession(e){let t=this.bitswap.createSession(e);return{announce:async(n,o,s)=>{await this.bitswap.notify(n,o,s)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function n2(r={}){return e=>new r2(e,r)}var Xu=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let d=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let h=Number.parseInt(u,e);if(!Number.isNaN(h))return h});if(d===void 0)break;if(s*=e,s+=d,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var sg=45,sA=15,Si=new Xu;function o2(r){if(!(r.length>sA))return Si.new(r).parseWith(()=>Si.readIPv4Addr())}function s2(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>sg))return Si.new(r).parseWith(()=>Si.readIPv6Addr())}function Qu(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>sg))return Si.new(r).parseWith(()=>Si.readIPAddr())}function _i(r){return!!o2(r)}function Ai(r){return!!s2(r)}function ju(r){return!!Qu(r)}var ag=Qe(ig(),1),iA=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],aA=iA.map(r=>new ag.Netmask(r));function cA(r){for(let e of aA)if(e.contains(r))return!0;return!1}function lA(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Yt(r){return _i(r)?cA(r):Ai(r)?lA(r):void 0}var Vq=parseInt("0xFFFF",16),Kq=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var ug=_i,pA=Ai,i2=function(r){let e=0;if(r=r.toString().trim(),ug(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(pA(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ug(t[n]),i;s&&(i=i2(t[n]),t[n]=O(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,O(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},dg=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Ii={},a2={},gA=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];gA.forEach(r=>{let e=yA(...r);a2[e.code]=e,Ii[e.name]=e});function yA(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function ee(r){if(typeof r=="number"){if(a2[r]!=null)return a2[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Ii[r]!=null)return Ii[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var vG=ee("ip4"),RG=ee("ip6"),SG=ee("ipcidr");function l2(r,e){switch(ee(r).code){case 4:case 41:return EA(e);case 42:return pg(e);case 6:case 273:case 33:case 132:return gg(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return pg(e);case 421:return RA(e);case 444:return mg(e);case 445:return mg(e);case 466:return vA(e);default:return O(e,"base16")}}function u2(r,e){switch(ee(r).code){case 4:return fg(e);case 41:return fg(e);case 42:return hg(e);case 6:case 273:case 33:case 132:return d2(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return hg(e);case 421:return bA(e);case 444:return SA(e);case 445:return _A(e);case 466:return xA(e);default:return M(e,"base16")}}var c2=Object.values(br).map(r=>r.decoder),wA=function(){let r=c2[0].or(c2[1]);return c2.slice(2).forEach(e=>r=r.or(e)),r}();function fg(r){if(!ju(r))throw new Error("invalid ip address");return i2(r)}function EA(r){let e=dg(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!ju(e))throw new Error("invalid ip address");return e}function d2(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function gg(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function hg(r){let e=M(r),t=Uint8Array.from($e(e.length));return ve([t,e],t.length+e.length)}function pg(r){let e=Bt(r);if(r=r.slice(Se(e)),r.length!==e)throw new Error("inconsistent lengths");return O(r)}function bA(r){let e;r[0]==="Q"||r[0]==="1"?e=Mr(Ye.decode(`z${r}`)).bytes:e=le.parse(r).multihash.bytes;let t=Uint8Array.from($e(e.length));return ve([t,e],t.length+e.length)}function xA(r){let e=wA.decode(r),t=Uint8Array.from($e(e.length));return ve([t,e],t.length+e.length)}function vA(r){let e=Bt(r),t=r.slice(Se(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+O(t,"base64url")}function RA(r){let e=Bt(r),t=r.slice(Se(e));if(t.length!==e)throw new Error("inconsistent lengths");return O(t,"base58btc")}function SA(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=ut.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=d2(n);return ve([t,o],t.length+o.length)}function _A(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ut.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=d2(n);return ve([t,o],t.length+o.length)}function mg(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=O(e,"base32"),o=gg(t);return`${n}:${o}`}function yg(r){r=f2(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=ee(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Eg("invalid address: "+r);if(a.path===!0){n=f2(o.slice(s).join("/")),e.push([a.code,u2(a.code,n)]),t.push([a.code,n]);break}let c=u2(a.code,o[s]);e.push([a.code,c]),t.push([a.code,l2(a.code,c)])}return{string:wg(t),bytes:p2(e),tuples:e,stringTuples:t,path:n}}function h2(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=Bt(r,o),i=Se(s),a=ee(s),c=AA(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Eg("Invalid address Uint8Array: "+O(r,"base16"));e.push([s,l]);let d=l2(s,l);if(t.push([s,d]),a.path===!0){n=d;break}}return{bytes:Uint8Array.from(r),string:wg(t),tuples:e,stringTuples:t,path:n}}function wg(r){let e=[];return r.map(t=>{let n=ee(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),f2(e.join("/"))}function p2(r){return ve(r.map(e=>{let t=ee(e[0]),n=Uint8Array.from($e(t.code));return e.length>1&&e[1]!=null&&(n=ve([n,e[1]])),n}))}function AA(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=Bt(e instanceof Uint8Array?e:Uint8Array.from(e));return t+Se(t)}}function f2(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Eg(r){return new Error("Error parsing address: "+r)}var IA=Symbol.for("nodejs.util.inspect.custom"),m2=Symbol.for("@multiformats/js-multiaddr/multiaddr"),DA=[ee("dns").code,ee("dns4").code,ee("dns6").code,ee("dnsaddr").code],Zu=class r{bytes;#e;#t;#r;#o;[m2]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=h2(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=yg(e)}else if(ko(e))t=h2(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#o=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=ee("tcp"),a=ee("udp"),c=ee("ip4"),l=ee("ip6"),d=ee("dns6"),u=ee("ip6zone");for(let[f,p]of this.stringTuples())f===u.code&&(s=`%${p??""}`),DA.includes(f)&&(t=i.name,o=443,n=`${p??""}${s}`,e=f===d.code?6:4),(f===i.code||f===a.code)&&(t=ee(f).name,o=parseInt(p??"")),(f===c.code||f===l.code)&&(t=ee(f).name,n=`${p??""}${s}`,e=f===l.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},ee(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>ee(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(p2(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===Ii.p2p.code&&e.push([n,o]),n===Ii["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?O(Ye.decode(`z${n}`),"base58btc"):O(le.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#o}equals(e){return Z(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=Di.get(t.name);if(n==null)throw new g(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>j(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[IA](){return`Multiaddr(${this.#e})`}};var Di=new Map;function ko(r){return!!r?.[m2]}function j(r){return new Zu(r)}var TA=r=>r.toString().split("/").slice(1),Ja=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),Te=r=>({match:e=>Ja(t=>t===r).match(e),pattern:r}),t1=()=>({match:r=>Ja(e=>typeof e=="string").match(r),pattern:"{string}"}),r1=()=>({match:r=>Ja(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),xt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Ye.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Ju=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{lh.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),vt=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),fr=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Oe=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function nt(...r){function e(o){let s=TA(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var y2=Oe(Te("dns4"),t1()),w2=Oe(Te("dns6"),t1()),E2=Oe(Te("dnsaddr"),t1()),bg=Oe(Te("dns"),t1()),JG=nt(y2),eW=nt(w2),tW=nt(E2),n1=nt(fr(bg,E2,y2,w2)),xg=Oe(Te("ip4"),Ja(_i)),vg=Oe(Te("ip6"),Ja(Ai)),Rg=fr(xg,vg),pn=fr(Rg,bg,y2,w2,E2),Sg=nt(pn),rW=nt(xg),nW=nt(vg),_g=nt(Rg),o1=Oe(pn,Te("tcp"),r1()),ec=Oe(pn,Te("udp"),r1()),kA=fr(o1,ec),oW=nt(o1),sW=nt(ec),b2=Oe(ec,Te("quic")),s1=Oe(ec,Te("quic-v1")),CA=fr(b2,s1),iW=nt(b2),aW=nt(s1),g2=fr(pn,o1,ec,b2,s1),Ag=fr(Oe(g2,Te("ws"),vt(xt()))),cW=nt(Ag),Ig=fr(Oe(g2,Te("wss"),vt(xt())),Oe(g2,Te("tls"),Te("ws"),vt(xt()))),lW=nt(Ig),Dg=Oe(kA,Te("webrtc-direct"),Ju(),vt(Ju()),vt(xt())),Tg=nt(Dg),kg=Oe(s1,Te("webtransport"),vt(Ju()),vt(Ju()),vt(xt())),i1=nt(kg),e1=fr(Ag,Ig,Oe(o1,vt(xt())),Oe(CA,vt(xt())),Oe(pn,vt(xt())),Dg,kg,xt()),uW=nt(e1),NA=Oe(e1,Te("p2p-circuit"),xt()),bs=nt(NA),LA=fr(Oe(e1,Te("p2p-circuit"),Te("webrtc"),xt()),Oe(e1,Te("webrtc"),vt(xt())),Te("webrtc")),Cg=nt(LA),PA=fr(Oe(pn,Te("tcp"),r1(),Te("http"),vt(xt())),Oe(pn,Te("http"),vt(xt()))),Ng=nt(PA),OA=fr(Oe(pn,Te("tcp"),fr(Oe(Te("443"),Te("http")),Oe(r1(),Te("https"))),vt(xt())),Oe(pn,Te("tls"),Te("http"),vt(xt())),Oe(pn,Te("https"),vt(xt()))),Lg=nt(OA);var BA=[ee("tcp").code,ee("dns").code,ee("dnsaddr").code,ee("dns4").code,ee("dns6").code];function Pg(r){let e;try{e=ee("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function Og(r){return r.some(([e,t])=>e===ee("tls").code)}function hr(r,e,t){let n=Bg[ee(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${ee(r).name}`);let o=n(e,t);return r===ee("ip6").code?`[${o}]`:o}var Bg={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${hr(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${hr(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=Og(e),n=Pg(e);if(t&&n!==null)return`https://${n}`;let o=t?"https://":"http://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let i=hr(s[0],s[1]??"",e);return i=i.replace("tcp://",""),`${o}${i}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return hr(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return hr(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=hr(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=Og(e),n=Pg(e);if(t&&n!==null)return`wss://${n}`;let o=t?"wss://":"ws://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let i=hr(s[0],s[1]??"",e);return i=i.replace("tcp://",""),`${o}${i}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=hr(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function a1(r,e){let n=j(r).stringTuples(),o=n.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let s=ee(o[0]),i=Bg[s.name];if(i==null)throw new Error(`No interpreter found for ${s.name}`);let a=i(o[1]??"",n);return e?.assumeHttp!==!1&&BA.includes(o[0])&&(a=a.replace(/^.*:\/\//,""),o[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var c1=class{url;#e=0;#t=0;#r=0;#o=0;#a=new Map;log;constructor(e,t){this.url=e instanceof URL?e:new URL(e),this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#l(e){let t=e.multihash.bytes;return st.encode(t)}async getRawBlock(e,t){let n=new URL(this.url.toString());if(n.pathname=`/ipfs/${e.toString()}`,n.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let o=this.#l(e),s=new AbortController,i=()=>{s.abort()};t?.addEventListener("abort",i);try{let a=this.#a.get(o);return a==null&&(this.#e++,a=fetch(n.toString(),{signal:s.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async c=>{if(this.log("GET %s %d",n,c.status),!c.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);return this.#o++,new Uint8Array(await c.arrayBuffer())}),this.#a.set(o,a)),await a}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",i),this.#a.delete(o)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#o/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#o,pendingResponses:this.#a.size}}};function MA(r,e,t){return r.filter(n=>Lg.matches(n)||e&&Ng.matches(n)?t||n1.matches(n)?!0:Yt(n.toOptions().host)===!1:!1)}async function*l1(r,e,t,n,o,s){for await(let i of e.findProviders(r,s)){let a=MA(i.multiaddrs,n,o);if(a.length===0)continue;let c=a1(a[0]);yield new c1(c,t)}}var x2=class extends Es{routing;allowInsecure;allowLocal;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??u1,this.allowLocal=t.allowLocal??d1}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let o=await t.getRawBlock(e,n.signal);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*l1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}};function Mg(r,e){return new x2(r,e)}var f1=class{allowInsecure;allowLocal;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??u1,this.allowLocal=t.allowLocal??d1}async retrieve(e,t={}){let n=[];for await(let o of l1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)){this.log("getting block for %c from %s",e,o.url);try{let s=await o.getRawBlock(e,t.signal);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s",e,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s",e,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return Mg({logger:this.logger,routing:this.routing},e)}};var u1=!1,d1=!1;function v2(r={}){return e=>new f1(e,r)}async function*h1(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 KA=Qe(Yo(),1);var $A=Qe(p1(),1);var Ug="ERR_IPNS_EXPIRED_RECORD",m1="ERR_UNRECOGNIZED_VALIDITY";var zn="ERR_SIGNATURE_VERIFICATION";var S2="ERR_UNDEFINED_PARAMETER",Fg="ERR_INVALID_RECORD_DATA",Vg="ERR_INVALID_VALUE",Kg="ERR_INVALID_EMBEDDED_KEY";var $g="ERR_RECORD_TOO_LARGE";var Xt;(function(r){let e;(function(o){o.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(o){o[o.EOL=0]="EOL"})(t||(t={})),function(o){o.codec=()=>He(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=ne((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.value!=null&&(s.uint32(10),s.bytes(o.value)),o.signatureV1!=null&&(s.uint32(18),s.bytes(o.signatureV1)),o.validityType!=null&&(s.uint32(24),r.ValidityType.codec().encode(o.validityType,s)),o.validity!=null&&(s.uint32(34),s.bytes(o.validity)),o.sequence!=null&&(s.uint32(40),s.uint64(o.sequence)),o.ttl!=null&&(s.uint32(48),s.uint64(o.ttl)),o.pubKey!=null&&(s.uint32(58),s.bytes(o.pubKey)),o.signatureV2!=null&&(s.uint32(66),s.bytes(o.signatureV2)),o.data!=null&&(s.uint32(74),s.bytes(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.value=o.bytes();break;case 2:i.signatureV1=o.bytes();break;case 3:i.validityType=r.ValidityType.codec().decode(o);break;case 4:i.validity=o.bytes();break;case 5:i.sequence=o.uint64();break;case 6:i.ttl=o.uint64();break;case 7:i.pubKey=o.bytes();break;case 8:i.signatureV2=o.bytes();break;case 9:i.data=o.bytes();break;default:o.skipType(c&7);break}}return i})),n),r.encode=o=>re(o,r.codec()),r.decode=o=>te(o,r.codec())})(Xt||(Xt={}));var pr=Qe(Yo(),1);var qg=ir("ipns:utils"),Gg=M("/ipns/"),UA=114,Wg=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw qg.error(n),(0,pr.default)(n,S2)}let t;if(e.pubKey!=null){try{t=zr(e.pubKey)}catch(o){throw qg.error(o),o}if(!(await dt(e.pubKey)).equals(r))throw(0,pr.default)(new Error("Embedded public key did not match PeerID"),Kg)}else r.publicKey!=null&&(t=zr(r.publicKey));if(t!=null)return t;throw(0,pr.default)(new Error("no public key is available"),S2)};var zg=r=>{let e=M("ipns-signature:");return ve([e,r])},tc=r=>"signatureV1"in r?Xt.encode({value:M(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:M(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):Xt.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data});function mn(r){let e=Xt.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw(0,pr.default)(new Error("missing data or signatureV2"),zn);let t=Xg(e.data),n=FA(t.Value),o=O(t.Validity);if(e.value!=null&&e.signatureV1!=null)return VA(e),{value:n,validityType:Xt.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:Xt.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}var _2=r=>ve([Gg,r.toBytes()]),Yg=r=>Je(r.slice(Gg.length));var Xg=r=>{let e=kr(r);if(e.ValidityType===0)e.ValidityType=Xt.ValidityType.EOL;else throw(0,pr.default)(new Error("Unknown validity type"),m1);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e},FA=r=>{if(r!=null){if(Ms(r))return`/ipns/${r.toCID().toString(so)}`;if(r instanceof Uint8Array){let n=O(r);n.startsWith("/")&&(r=n)}let e=r.toString().trim();if(e.startsWith("/")&&e.length>1)return e;let t=le.asCID(r);if(t!=null)return t.code===UA?`/ipns/${t.toString(so)}`:`/ipfs/${t.toV1().toString()}`;try{return r instanceof Uint8Array?`/ipfs/${le.decode(r).toV1().toString()}`:`/ipfs/${le.parse(e).toV1().toString()}`}catch{}}throw(0,pr.default)(new Error("Value must be a valid content path starting with /"),Vg)},VA=r=>{if(r.data==null)throw(0,pr.default)(new Error("Record data is missing"),Fg);let e=Xg(r.data);if(!Z(e.Value,r.value??new Uint8Array(0)))throw(0,pr.default)(new Error('Field "value" did not match between protobuf and CBOR'),zn);if(!Z(e.Validity,r.validity??new Uint8Array(0)))throw(0,pr.default)(new Error('Field "validity" did not match between protobuf and CBOR'),zn);if(e.ValidityType!==r.validityType)throw(0,pr.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),zn);if(e.Sequence!==r.sequence)throw(0,pr.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),zn);if(e.TTL!==r.ttl)throw(0,pr.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),zn)};var nz=ir("ipns"),oz=Wt.code,sz=60*60*1e9,HA="/ipns/",iz=HA.length;var rc=Qe(Yo(),1),Qg=Qe(p1(),1);var g1=ir("ipns:validator"),qA=1024*10,GA=async(r,e)=>{let t=mn(e),n;try{let o=zg(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw g1.error("record signature verification failed"),(0,rc.default)(new Error("record signature verification failed"),zn);if(t.validityType===Xt.ValidityType.EOL){if(Qg.default.fromString(t.validity).toDate().getTime()<Date.now())throw g1.error("record has expired"),(0,rc.default)(new Error("record has expired"),Ug)}else if(t.validityType!=null)throw g1.error("unrecognized validity type"),(0,rc.default)(new Error("unrecognized validity type"),m1);g1("ipns record for %s is valid",t.value)};async function y1(r,e){if(e.byteLength>qA)throw(0,rc.default)(new Error("record too large"),$g);let t=Yg(r),n=mn(e),o=await Wg(t,n);await GA(o,e)}async function*nc(r){let e=/\r?\n/,t=new TextDecoder("utf8"),n="";for await(let o of r){typeof o=="string"&&(o=new TextEncoder().encode(o)),n+=t.decode(o,{stream:!0});let s=n.split(e);n=s.pop()??"";for(let i=0;i<s.length;i++)yield JSON.parse(s[i])}n+=t.decode(),n!==""&&(yield JSON.parse(n))}function WA(r){return r[Symbol.asyncIterator]!=null}function zA(r){if(WA(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var xs=zA;var A2=M("/ipns/");function jg(r){return Z(r.subarray(0,A2.byteLength),A2)}var Zg=r=>Je(r.slice(A2.length)),w1=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*Gt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async put(e,t,n){if(!jg(e))return;let o=Zg(e),s=mn(t);await this.client.putIPNS(o,s,n)}async get(e,t){if(!jg(e))throw new g("Not found","ERR_NOT_FOUND");let n=Zg(e);try{let o=await this.client.getIPNS(n,t);return tc(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new g("Not found","ERR_NOT_FOUND"):o}}},E1=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await xs(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new g("Not found","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){}};var Qt=ir("delegated-routing-v1-http-api-client"),Jg={concurrentRequests:4,timeout:3e4},b1=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal),this.httpQueue=new Ir({concurrency:t.concurrentRequests??Jg.concurrentRequests}),this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??Jg.timeout,this.contentRouting=new w1(this),this.peerRouting=new E1(this)}get[on](){return this.contentRouting}get[sn](){return this.peerRouting}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.shutDownController.abort(),this.started=!1}async*getProviders(e,t={}){Qt("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ae([this.shutDownController.signal,n,t.signal]);H(1/0,n,o);let s=J(),i=J();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=`${this.clientUrl}routing/v1/providers/${e.toString()}`,l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new g("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new g("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new g("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let h of u.Providers){let f=this.#e(h);f!=null&&(yield f)}}else for await(let u of nc(h1(l.body))){let h=this.#e(u);h!=null&&(yield h)}}catch(a){Qt.error("getProviders errored:",a)}finally{o.clear(),i.resolve(),Qt("getProviders finished: %c",e)}}async*getPeers(e,t={}){Qt("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ae([this.shutDownController.signal,n,t.signal]);H(1/0,n,o);let s=J(),i=J();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`,l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new g("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new g("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new g("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let h of u.Peers){let f=this.#e(h);f!=null&&(yield f)}}else for await(let u of nc(h1(l.body))){let h=this.#e(u);h!=null&&(yield h)}}catch(a){Qt.error("getPeers errored:",a)}finally{o.clear(),i.resolve(),Qt("getPeers finished: %c",e)}}async getIPNS(e,t={}){Qt("getIPNS starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ae([this.shutDownController.signal,n,t.signal]);H(1/0,n,o);let s=J(),i=J();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await s.promise;let l=await fetch(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(Qt("getIPNS GET %s %d",a,l.status),l.status===404)throw new g("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new g("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new g("GET ipns response had no body","ERR_BAD_RESPONSE");let d=await l.arrayBuffer(),u=new Uint8Array(d,0,d.byteLength);return t.validate!==!1&&await y1(_2(e),u),mn(u)}catch(c){throw Qt.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),i.resolve(),Qt("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){Qt("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=Ae([this.shutDownController.signal,o,n.signal]);H(1/0,o,s);let i=J(),a=J();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await i.promise;let l=tc(t),u=await fetch(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:s});if(Qt("putIPNS PUT %s %d",c,u.status),u.status!==200)throw new g("PUT ipns response had status other than 200","ERR_BAD_RESPONSE")}catch(l){throw Qt.error("putIPNS PUT %s error:",c,l.stack),l}finally{s.clear(),a.resolve(),Qt("putIPNS finished: %c",e)}}#e(e){let t=[],n=e.Addrs?.map(j)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:ge(e.ID),Addrs:n,Protocols:t}}};function e7(r,e={}){return new b1(new URL(r),e)}var t7="[a-fA-F\\d:]",Co=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${t7})|(?<=${t7})(?=\\s|$))`:"",Zr="(?: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}",ct="[a-fA-F\\d]{1,4}",x1=`
23
23
  (?:
24
24
  (?:${ct}:){7}(?:${ct}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
25
25
  (?:${ct}:){6}(?:${Zr}|:${ct}|:)| // 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
@@ -49,7 +49,7 @@ a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host\r
49
49
  a=ice-ufrag:`+e+`
50
50
  `).replace(/\na=ice-pwd:[^\n]*\n/,`
51
51
  a=ice-pwd:`+e+`
52
- `),r}var LE=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),PE=r=>[...Array(r)].map(()=>LE.at(Math.floor(Math.random()*LE.length))).join("");var iN=1e4,Ace=ee("webrtc-direct").code,NE=ee("certhash").code,rf=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){throw Wy("WebRTCTransport.createListener")}listenFilter(e){return e.filter(Tg.exactMatch)}dialFilter(e){return this.listenFilter(e)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[an]=!0;async _connect(e,t){let n=new AbortController,o=n.signal,s=e.getPeerId();if(s===null)throw Bd("we need to have the remote's PeerId");let i=ge(s),a=F3(tf(e)),c=await Zi.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:V3(a.name)}),l=new Zi({certificates:[c]});try{let d=new Promise((R,T)=>{let P=l.createDataChannel("",{negotiated:!0,id:0}),N=setTimeout(()=>{let B=`Data channel was never opened: state: ${P.readyState}`;this.log.error(B),this.metrics?.dialerEvents.increment({open_error:!0}),T(o3("data",B))},iN);P.onopen=B=>{clearTimeout(N),R(P)},P.onerror=B=>{clearTimeout(N);let X=`Error opening a data channel for handshaking: ${B.target?.toString()??"not specified"}`;this.log.error(X),this.metrics?.dialerEvents.increment({unknown_error:!0}),T(o3("data",X))}}),u="libp2p+webrtc+v1/"+PE(32),h=await l.createOffer(),f=CE(h,u);await l.setLocalDescription(f);let p=kE(e,u);await l.setRemoteDescription(p);let m=await d,y=this.components.peerId,w=this.generateNoisePrologue(l,a.code,e),b=Pi({prologueBytes:w})(this.components),E=ji({channel:m,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),x={...E,sink:E.sink.bind(E),source:async function*(){for await(let R of E.source)for(let T of R)yield T}()},v=new ks(this.components,{peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),I=Sc?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(I,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":v.close().catch(R=>{this.log.error("error closing connection",R)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let S=new Cs(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(y,x,i),await t.upgrader.upgradeOutbound(v,{skipProtection:!0,skipEncryption:!0,muxerFactory:S})}catch(d){throw l.close(),d}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw Rc("no local certificate");let o=TE(e,{log:this.log});if(o==null)throw Rc("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=M(s,"hex"),a=OE.encode(i,t),c=U3.decode(tf(n)),l=M("libp2p-webrtc-noise:");return ve([l,a,c])}};function BE(r){return e=>new rf(e,r)}function ME(r){return e=>new Hd(e,r)}var UE=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",o),r.removeEventListener("error",s)}function o(){n(),e()}function s(i){n(),t(i.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",o),r.addEventListener("error",s)})};var FE=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let o of n){try{await UE(r)}catch(s){if(s.message==="socket closed")break;throw s}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(o)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((o,s)=>{r.addEventListener("close",i=>{if(i.wasClean||i.code===1006)o();else{let a=Object.assign(new Error("ws error"),{event:i});s(a)}}),setTimeout(()=>{r.close()})})});var HE=Qe(KE(),1);function $E(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var qE=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,i)=>{if(n){s();return}if(o!=null){i(o);return}let a=d=>{r.removeEventListener("open",c),r.removeEventListener("error",l),d()},c=()=>{a(s)},l=d=>{a(()=>{i(d.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let s=new HE.EventIterator(({push:i,stop:a,fail:c})=>{let l=u=>{let h=null;typeof u.data=="string"&&(h=M(u.data)),$E(u.data)&&(h=new Uint8Array(u.data)),u.data instanceof Uint8Array&&(h=u.data),h!=null&&i(h)},d=u=>{c(u.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",d),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",d),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let i of s)yield $E(i)?new Uint8Array(i):i}(),n=r.readyState===1,o;return r.addEventListener("open",()=>{n=!0,o=null}),r.addEventListener("close",()=>{n=!1,o=null}),r.addEventListener("error",s=>{n||(o=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var GE=(r,e)=>{e=e??{};let t=qE(r),n=e.remoteAddress,o=e.remotePort;if(r.url!=null)try{let i=new URL(r.url);n=i.hostname,o=parseInt(i.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:FE(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(i=>{r.addEventListener("close",()=>{i()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:o,socket:r}};var WE=WebSocket;var cN={"http:":"ws:","https:":"wss:"},zE="ws:",YE=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??zE}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??zE,o=e.host,s=e.port!=null&&o?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${o}${s}${r}`}let t=new URL(r);for(let[n,o]of Object.entries(cN))t.protocol===n&&(t.protocol=o);return t};function XE(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=YE(r,t),o=new WE(n.toString(),e.websocket);return GE(o,e)}function QE(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Mi.matches(t)||_s.matches(t)})}function jE(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return _s.matches(t)})}function ZE(){throw new Error("WebSocket Servers can not be created in the browser!")}function JE(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),o={log:n,async sink(s){try{await r.sink(async function*(){for await(let i of s)i instanceof Uint8Array?yield i:yield i.subarray()}())}catch(i){i.type!=="aborted"&&n.error(i)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(s={}){let i=Date.now();if(s.signal==null){let c=AbortSignal.timeout(500);s={...s,signal:c}}let a=()=>{let{host:c,port:l}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",c,l,Date.now()-i),this.abort(new g("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};s.signal?.addEventListener("abort",a);try{await r.close()}catch(c){n.error("error closing WebSocket gracefully",c),this.abort(c)}finally{s.signal?.removeEventListener("abort",a),o.timeline.close=Date.now()}},abort(s){let{host:i,port:a}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",i,a,s),r.destroy(),o.timeline.close=Date.now()}};return r.socket.addEventListener("close",()=>{o.timeline.close==null&&(o.timeline.close=Date.now())},{once:!0}),o}var H3=class{log;init;logger;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.init=t}[Symbol.toStringTag]="@libp2p/websockets";[an]=!0;async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),o=JE(n,e,{logger:this.logger});this.log("new outbound connection %s",o.remoteAddr);let s=await t.upgrader.upgradeOutbound(o);return this.log("outbound connection %s upgraded",o.remoteAddr),s}async _connect(e,t){if(t?.signal?.aborted===!0)throw new Kt;let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let o=J(),s=XE(a1(e),this.init);if(s.socket.addEventListener("error",()=>{let c=new g(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",c),o.reject(c)}),t.signal==null)return await Promise.race([s.connected(),o.promise]),this.log("connected %s",e),s;let i,a=new Promise((c,l)=>{if(i=()=>{l(new Kt),s.close().catch(d=>{this.log.error("error closing raw socket",d)})},t?.signal?.aborted===!0){i();return}t?.signal?.addEventListener("abort",i)});try{await Promise.race([a,o.promise,s.connected()])}finally{i!=null&&t?.signal?.removeEventListener("abort",i)}return this.log("connected %s",e),s}createListener(e){return ZE({logger:this.logger},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):ed||td?jE(e):QE(e)}dialFilter(e){return this.listenFilter(e)}};function eb(r={}){return e=>new H3(e,r)}function q3(r){throw new Error("Not implemented")}var G3=class extends yn{writer;reader;constructor(e){super(e),this.writer=e.bidiStream.writable.getWriter(),this.reader=e.bidiStream.readable.getReader(),Promise.resolve().then(async()=>{for(;;){let t=await this.reader.read();if(t.done){e.log("remote closed write");return}t.value!=null&&this.sourcePush(new ce(t.value))}}).catch(t=>{e.log.error("error reading from stream",t),this.abort(t)}).finally(()=>{this.remoteCloseWrite()}),this.writer.closed.then(()=>{e.log("writer closed")}).catch(t=>{e.log("writer close promise rejected",t)}).finally(()=>{this.remoteCloseRead()})}sendNewStream(e){}async sendData(e,t){for await(let n of e)this.log("sendData waiting for writer to be ready"),await Ue(this.writer.ready,t?.signal),this.writer.write(n).catch(o=>{this.log.error("error sending stream data",o)})}async sendReset(e){this.log("sendReset aborting writer"),await Ue(this.writer.abort(),e?.signal),this.log("sendReset aborted writer")}async sendCloseWrite(e){this.log("sendCloseWrite closing writer"),await Ue(this.writer.close(),e?.signal),this.log("sendCloseWrite closed writer")}async sendCloseRead(e){this.log("sendCloseRead cancelling reader"),await Ue(this.reader.cancel(),e?.signal),this.log("sendCloseRead cancelled reader")}};async function W3(r,e,t,n,o,s){let i=s.forComponent(`libp2p:webtransport:stream:${t}:${e}`),a=new G3({bidiStream:r,id:e,direction:t,log:i,onEnd:()=>{let c=n.findIndex(l=>l===a);c!==-1&&n.splice(c,1),o?.(a)}});return a}function sf(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}function tb(r,e,t,n){let o=0,s=t.forComponent("libp2p:webtransport:muxer");return{protocol:"webtransport",createStreamMuxer:i=>{typeof i=="function"&&(i={onIncomingStream:i});let a=[];return Promise.resolve().then(async()=>{for(;;){let{done:l,value:d}=await e.read();if(l)break;if(a.length>=n.maxInboundStreams)s(`too many inbound streams open - ${a.length}/${n.maxInboundStreams}, closing new incoming stream`),d.writable.close().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),d.readable.cancel().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await W3(d,String(o++),"inbound",a,i?.onStreamEnd,t);a.push(u),i?.onIncomingStream?.(u)}}}),{protocol:"webtransport",streams:a,newStream:async l=>{s("new outgoing stream",l);let d=await r.createBidirectionalStream(),u=await W3(d,String(o++),i?.direction??"outbound",a,i?.onStreamEnd,t);return a.push(u),u},close:async()=>{s("closing webtransport muxer gracefully"),r.close()},abort:l=>{s("closing webtransport muxer with err:",l),r.close()},...sf()}}}}function rb(r,e){return e.filter(n=>!!r.find(o=>Z(n,o))).length===e.length}var fN=Object.values(br).map(r=>r.decoder).reduce((r,e)=>r.or(e));function hN(r){return Er.decode(fN.decode(r))}function z3(r){if(!i1.matches(r))throw new g("Invalid multiaddr, was not a WebTransport address","ERR_INVALID_MULTIADDR");let e=r.stringTuples(),t=e.filter(([i,a])=>i===ee("certhash").code).map(([i,a])=>hN(a??"")),n=e.filter(([i,a])=>i===ee("p2p").code).map(([i,a])=>ge(a??""))[0],o=r.toOptions(),s=o.host;return o.family===6&&s?.includes(":")&&(s=`[${s}]`),{url:`https://${s}:${o.port}`,certhashes:t,remotePeer:n}}var nb=WebTransport;var Y3=class{log;components;config;metrics;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webtransport"),this.components=e,this.config={...t,maxInboundStreams:t.maxInboundStreams??1e3,certificates:t.certificates??[]},e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webtransport_dialer_events_total",{label:"event",help:"Total count of WebTransport dialer events by type"})})}[Symbol.toStringTag]="@libp2p/webtransport";[an]=!0;async dial(e,t){if(t?.signal?.aborted===!0)throw new Kt;this.log("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new g("Need a local peerid","ERR_INVALID_PARAMETERS");t=t??{};let{url:o,certhashes:s,remotePeer:i}=z3(e),a,c,l=()=>{},d=!1,u=!1,h=!1;try{this.metrics?.dialerEvents.increment({pending:!0});let f=new nb(`${o}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(p=>({algorithm:"sha-256",value:p.digest}))});if(l=p=>{if(!d)try{this.metrics?.dialerEvents.increment({[p]:!0}),f.close()}catch(m){this.log.error("error closing wt session",m)}finally{c!=null&&(c.timeline.close=Date.now()),d=!0}},a=()=>{l(u?"noise_timeout":"ready_timeout")},t.signal?.addEventListener("abort",a,{once:!0}),this.log("wait for session to be ready"),await Promise.race([f.closed,f.ready]),this.log("session became ready"),u=!0,this.metrics?.dialerEvents.increment({ready:!0}),f.closed.catch(p=>{this.log.error("error on remote wt session close",p)}).finally(()=>{l("remote_close")}),h=await Ue(this.authenticateWebTransport(f,n,i,s),t.signal),!h)throw new g("Failed to authenticate webtransport","ERR_AUTHENTICATION_FAILED");return this.metrics?.dialerEvents.increment({open:!0}),c={close:async()=>{this.log("closing webtransport"),l("close")},abort:p=>{this.log("aborting webtransport due to passed err",p),l("abort")},remoteAddr:e,timeline:{open:Date.now()},log:this.components.logger.forComponent("libp2p:webtransport:maconn"),...sf()},await t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:tb(f,f.incomingBidirectionalStreams.getReader(),this.components.logger,this.config),skipProtection:!0})}catch(f){throw this.log.error("caught wt session err",f),l(h?"upgrade_error":u?"noise_error":"ready_error"),f}finally{a!=null&&t.signal?.removeEventListener("abort",a)}}async authenticateWebTransport(e,t,n,o=[],s){if(s?.aborted===!0)throw new Kt;let i=await e.createBidirectionalStream(),a=i.writable.getWriter(),c=i.readable.getReader(),l={source:async function*(){for(;;){let h=await c.read();if(h.value!=null&&(yield h.value),h.done)break}}(),sink:async h=>{for await(let f of h){await Ue(a.ready,s);let p=f instanceof Uint8Array?f:f.subarray();a.write(p).catch(m=>{this.log.error("could not write chunk during authentication of WebTransport stream",m)})}}},d=Pi()(this.components),{remoteExtensions:u}=await d.secureOutbound(t,l,n);if(a.close().catch(h=>{this.log.error(`Failed to close authentication stream writer: ${h.message}`)}),c.cancel().catch(h=>{this.log.error(`Failed to close authentication stream reader: ${h.message}`)}),!rb(u?.webtransportCerthashes??[],o.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}createListener(e){return q3(this.components,{...e,certificates:this.config.certificates,maxInboundStreams:this.config.maxInboundStreams})}listenFilter(){return[]}dialFilter(e){return e.filter(t=>{if(!i1.exactMatch(t))return!1;let{url:n,certhashes:o}=z3(t);return n!=null&&o.length>0})}};function ob(r={}){return e=>new Y3(e,r)}var X3=Qe(p1(),1);function sb(r,e){let t=e.map((n,o)=>({record:mn(n),index:o}));return t.sort((n,o)=>{let s=n.record.sequence,i=o.record.sequence;if(s>i)return-1;if(s<i)return 1;if(n.record.validityType===Xt.ValidityType.EOL&&o.record.validityType===Xt.ValidityType.EOL){let a=X3.default.fromString(n.record.validity).toDate(),c=X3.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var af="1.6.0",cf="libp2p";var ab="4.2.2",cb="helia";var lb={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function lf(r={}){let e=`${cb}/${ab} ${cf}/${af} UserAgent=${globalThis.navigator.userAgent}`;return{peerId:r.peerId,dns:r.dns,addresses:{listen:["/webrtc"]},transports:[kp({discoverRelays:1}),ME(),BE(),ob(),eb()],connectionEncryption:[Pi()],streamMuxers:[j7(),Ky()],peerDiscovery:[h9(lb)],services:{autoNAT:t9(),dcutr:D9(),delegatedRouting:()=>e7("https://delegated-ipfs.dev"),dht:py({clientMode:!0,validators:{ipns:y1},selectors:{ipns:sb}}),identify:$9({agentVersion:e}),identifyPush:H9({agentVersion:e}),keychain:Nd(r.keychain),ping:Gy()}}}var It={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var ca;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>re(i,o.codec()),o.decode=i=>te(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),df.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=df.codec().decode(i,i.uint32());break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>re(i,o.codec()),o.decode=i=>te(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ne((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),uf.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(uf.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let l=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(l.key,l.value);break}case 7:{let l=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(l.key,l.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>re(o,r.codec()),r.decode=o=>te(o,r.codec())})(ca||(ca={}));var uf;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(uf||(uf={}));var df;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(df||(df={}));function la(r,e){let t=ca.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=u8({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:j(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Q3="/peers/";function ua(r){if(!Ms(r)||r.type==null)throw new g("Invalid PeerId",It.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Pe(`${Q3}${e}`)}async function ub(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=j(o.multiaddr)),!ko(o.multiaddr))throw new g("Multiaddr was invalid",It.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function hf(r,e,t,n){if(e==null)throw new g("Invalid PeerData",It.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!Z(e.publicKey,r.publicKey))throw new g("publicKey bytes do not match peer id publicKey bytes",It.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new g("peer id did not match existing peer id",It.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=ff(u,{validate:db})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ff(u,{validate:fb,map:hb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,f]of u)f==null?a.delete(h):a.set(h,f);a=ff([...a.entries()],{validate:db})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[f,p]of u)p==null?h.delete(f):h.set(f,p);c=ff([...h.entries()],{validate:fb,map:hb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let d={addresses:await ub(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((u,h)=>u.localeCompare(h)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:l};return r.type!=="RSA"&&delete d.publicKey,d}function ff(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function db(r,e){if(typeof r!="string")throw new g("Metadata key must be a string",It.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new g("Metadata value must be a Uint8Array",It.ERR_INVALID_PARAMETERS)}function fb(r,e){if(typeof r!="string")throw new g("Tag name must be a string",It.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new g("Tag value must be an integer",It.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new g("Tag value must be between 0-100",It.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new g("Tag ttl must be an integer",It.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new g("Tag ttl must be between greater than 0",It.ERR_INVALID_PARAMETERS)}}function hb(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function pf(r,e,t){let n=r.toString().split("/")[2],o=ut.decode(n),s=Je(o),i=t.get(s);if(i!=null)return i;let a=la(s,e);return t.set(s,a),a}function pN(r,e){return r==null?{}:{prefix:Q3,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(pf(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(pf(n.key,n.value,e),pf(o.key,o.value,e)))}}var mf=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Ya({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(ua(e))}async delete(e){if(this.peerId.equals(e))throw new g("Cannot delete self peer",It.ERR_INVALID_PARAMETERS);await this.datastore.delete(ua(e))}async load(e){let t=await this.datastore.get(ua(e));return la(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new it;for await(let{key:n,value:o}of this.datastore.query(pN(e??{},t))){let s=pf(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(ua(e)),n=la(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=ca.encode(t);return n!=null&&Z(s,n)?{peer:la(e,s),previous:o,updated:!1}:(await this.datastore.put(ua(e),s),{peer:la(e,s),previous:o,updated:!0})}};var gf=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new mf(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await sc(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mr.openAndCertify(e,Vt.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Vt.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await mr.createFromProtobuf(s.peerRecordEnvelope),a=Vt.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function pb(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var mN=r=>r;function j3(r,e){let t=r.getPeerId();return t!=null&&ge(t).equals(e)&&(r=r.decapsulate(j(`/p2p/${e.toString()}`))),r}var yf=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??mN,this._updatePeerStoreAddresses=pb(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>j(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>j(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>j(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>j(e))}addObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>j(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var Z3=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=So())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Fc(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},gN=["metrics","connectionProtector","dns"],yN=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function mb(r={}){let e=new Z3(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!yN.includes(o)){let i=e.components[o];if(i==null&&!gN.includes(o))throw new g(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function gb(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Yt(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function J3(r){try{let{address:e}=r.nodeAddress();return!!Yt(e)}catch{return!0}}function wN(r,e){let t=J3(r.multiaddr),n=J3(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function EN(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function bN(r,e){let t=bs.exactMatch(r.multiaddr),n=bs.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function da(r,e){let t=wN(r,e);if(t!==0)return t;let n=bN(r,e);return n!==0?n:EN(r,e)}var xN=32,{code:vN}=ee("dnsaddr"),Ps=async function(e,t={}){let n=t.maxRecursiveDepth??xN;if(n===0)throw new g("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([l])=>l===vN)??[],i=await(t?.dns??wu()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[ar.TXT]}),a=e.getPeerId(),c=[];for(let l of i.Answer){let d=l.data.replace(/["']/g,"").trim().split("=")[1];if(d==null||a!=null&&!d.includes(a))continue;let u=j(d);if(d.startsWith("/dnsaddr")){let h=await u.resolve({...t,maxRecursiveDepth:n-1});c.push(...h.map(f=>f.toString()))}else c.push(u.toString())}return c};var Jn;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Jn||(Jn={}));var z;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(z||(z={}));var RN={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ps},addressSorter:da},transportManager:{faultTolerance:to.FATAL_ALL}};async function yb(r){let e=Xi(RN,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new g(Jn.ERR_PROTECTOR_REQUIRED,z.ERR_PROTECTOR_REQUIRED);if(!(await dt(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new g("Private key doesn't match peer id",z.ERR_INVALID_KEY);return e}function wf(r){if(Ms(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:ge(t),r.forEach(n=>{if(!ko(n))throw new g("Invalid Multiaddr",z.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new g("Multiaddrs must all have the same peer id or have no peer id",z.ERR_INVALID_PARAMETERS)}else{let s=ge(o);if(e==null||!e.equals(s))throw new g("Multiaddrs must all have the same peer id or have no peer id",z.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}var Ef="last-dial-failure";var bf=5,xf=100,vf=50,Rf=1e3*60*7;var Os={minConnections:bf,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Rf,autoDialDiscoveredPeersDebounce:10},Sf=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Os.minConnections,this.autoDialPriority=t.autoDialPriority??Os.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Os.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Os.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Os.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Os.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new wr({concurrency:t.autoDialConcurrency??Os.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new ht(this.connectionManager.getDialQueue().map(l=>l.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[l=>l.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",l.id),!1):e.has(l.id)?(this.log.trace("not autodialing %p because they are already connected",l.id),!1):n.has(l.id)?(this.log.trace("not autodialing %p because they are already being dialed",l.id),!1):this.queue.has(l.id)?(this.log.trace("not autodialing %p because they are already being autodialed",l.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new it;for(let l of s)i.has(l.id)||i.set(l.id,[...l.tags.values()].reduce((d,u)=>d+u.value,0));let c=s.sort((l,d)=>{let u=i.get(l.id)??0,h=i.get(d.id)??0;return u>h?-1:u<h?1:0}).filter(l=>{let d=l.metadata.get(Ef);if(d==null)return!0;let u=parseInt(O(d));return isNaN(u)?!0:Date.now()-u>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let l of c)this.queue.add(async()=>{let d=this.connectionManager.getConnectionsMap().size;if(d>=this.minConnections){this.log("got enough connections now %d/%d",d,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",l.id),await this.connectionManager.openConnection(l.id,{priority:this.autoDialPriority})},{peerId:l.id}).catch(d=>{this.log.error("could not connect to peerStore stored peer",d)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var _N=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function wb(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??_N;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Eb={maxConnections:xf,allow:[]},_f=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Eb.maxConnections,this.allow=t.allow??Eb.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new it;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((d,u)=>d+u.value,0))}catch(l){l.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>a.remoteAddr.toString().startsWith(l.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await wb(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Af=class extends tr{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};async function bb(r,e){let t=!1;for(let o of Di.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var Lc={addressSorter:da,maxParallelDials:vf,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Ps}},If=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Lc.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Lc.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Lc.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Lc.dialTimeout,this.connections=t.connections??new it,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))Di.set(n,o);this.queue=new Af({concurrency:t.maxParallelDials??Lc.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=wf(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new g("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),this.queue.add(async a=>{let c=this.createDialAbortController(a?.signal),l;try{l=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),l.map(({multiaddr:d})=>d.toString()).forEach(d=>{a?.multiaddrs.add(d)})}catch(d){throw c.clear(),d}try{let d=0,u=[];for(let h of l){if(d===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",d,n),new g("Peer had more than maxPeerAddrsToDial",z.ERR_TOO_MANY_ADDRESSES);d++;try{let f=await this.components.transportManager.dial(h.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",h.multiaddr),f}catch(f){if(this.log.error("dial failed to %a",h.multiaddr,f),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[Ef]:M(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new g(f.message,vn);u.push(f)}}throw u.length===1?u[0]:new Uc(u,"All multiaddr dials failed",z.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??a4,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=Ae([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return H(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:j(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new g("Tried to dial self",z.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new g("The dial request is blocked by gater.allowDialPeer",z.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:h})=>h.toString()))}catch(u){if(u.code!==z.ERR_NOT_FOUND)throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:h})=>h.toString())),o.push(...u.multiaddrs.map(h=>({multiaddr:h,isCertified:!1})))}catch(u){u.code!==z.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,u)}}}let s=(await Promise.all(o.map(async u=>{let h=await bb(u.multiaddr,{dns:this.components.dns,...n,log:this.log});return h.length===1&&h[0].equals(u.multiaddr)?u:h.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;s=s.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(u),isCertified:h.isCertified}:h)}let i=s.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let h=u.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),a=new Map;for(let u of i){let h=u.multiaddr.toString(),f=a.get(h);if(f!=null){f.isCertified=f.isCertified||u.isCertified||!1;continue}a.set(h,u)}let c=[...a.values()];if(c.length===0)throw new g("The dial request has no valid addresses",z.ERR_NO_VALID_ADDRESSES);let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let d=l.sort(this.addressSorter);if(d.length===0)throw new g("The connection gater denied all addresses in the dial request",z.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",d.map(({multiaddr:u})=>u.toString())),d}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!bs.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var a4=50,eo={minConnections:bf,maxConnections:xf,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Rf,autoDialDiscoveredPeersDebounce:10},Df=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??eo.maxConnections;let n=t.minConnections??eo.minConnections;if(this.maxConnections<n)throw new g("Connection Manager maxConnections must be greater than minConnections",z.ERR_INVALID_PARAMETERS);this.connections=new it,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(o=>j(o)),this.deny=(t.deny??[]).map(o=>j(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??eo.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Qi({points:t.inboundConnectionThreshold??eo.inboundConnectionThreshold,duration:1}),this.autoDial=new Sf({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??eo.autoDialConcurrency,autoDialPriority:t.autoDialPriority??eo.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??eo.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??eo.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??eo.autoDialMaxQueueLength}),this.connectionPruner=new _f({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new If(e,{addressSorter:t.addressSorter??da,maxParallelDials:t.maxParallelDials??vf,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Ps},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(R4)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new g("Not started",z.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=wf(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??a4}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>j(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Tf=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new g("No content routers available",z.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ht;for await(let s of Mt(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new g("No content routers available",z.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new g(Jn.NOT_STARTED_YET,z.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new g(Jn.NOT_STARTED_YET,z.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var kf=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}async findPeer(e,t){if(this.routers.length===0)throw new g("No peer routers available",z.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new g("Should not try to find self",z.ERR_FIND_SELF);let n=this,o=Mt(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new g(Jn.NOT_FOUND,z.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new g("No peer routers available",z.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ht;for await(let s of en(async function*(){let i=Mt(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}};var Cf=class extends ye{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,H(1/0,this.shutdownController.signal)}start(){this.shutdownController=new AbortController,H(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ae([this.shutdownController.signal,e?.signal]);H(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=J(),yield(await er(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,H(1/0,this.walkController.signal);let e=Ae([this.walkController.signal,this.shutdownController.signal]);H(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{for await(let o of this.peerRouting.getClosestPeers(pt(32),{signal:e}))e.throwIfAborted(),this.log("found peer %p",o.id),n++,this.safeDispatchEvent("walk:peer",{detail:o}),this.walkers===1&&this.needNext!=null&&await Ue(this.needNext.promise,e)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var c4=32,l4=64,Nf=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new g(`No handler registered for protocol ${e}`,z.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new g(`Handler already registered for protocol ${e}`,z.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=Xi.bind({ignoreUndefined:!0})({maxInboundStreams:c4,maxOutboundStreams:l4},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new g("invalid topology",z.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.code!==z.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Lf=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Wu({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??to.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new g("Transport must have a valid tag",z.ERR_INVALID_KEY);if(this.transports.has(t))throw new g(`There is already a transport with the tag ${t}`,z.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new g(`No transport available for address ${String(e)}`,z.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=z.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new g("Not started",z.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let l of s){this.log("creating listener for %s on %a",n,l);let d=o.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(n)??[];u==null&&(u=[],this.listeners.set(n,u)),u.push(d),d.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:d})}),d.addEventListener("close",()=>{let h=u.findIndex(f=>f===d);u.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:d})}),i.push(d.listen(l))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(l=>l.status==="fulfilled")==null&&this.faultTolerance!==to.NO_FATAL)throw new g(`Transport (${n}) could not listen on any available address`,z.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===to.FATAL_ALL)throw new g(n,z.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Dt="/multistream/1.0.0";var DN=M(`
52
+ `),r}var LE=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),PE=r=>[...Array(r)].map(()=>LE.at(Math.floor(Math.random()*LE.length))).join("");var iN=1e4,Ace=ee("webrtc-direct").code,NE=ee("certhash").code,rf=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){throw Wy("WebRTCTransport.createListener")}listenFilter(e){return e.filter(Tg.exactMatch)}dialFilter(e){return this.listenFilter(e)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[an]=!0;async _connect(e,t){let n=new AbortController,o=n.signal,s=e.getPeerId();if(s===null)throw Bd("we need to have the remote's PeerId");let i=ge(s),a=F3(tf(e)),c=await Zi.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:V3(a.name)}),l=new Zi({certificates:[c]});try{let d=new Promise((R,T)=>{let P=l.createDataChannel("",{negotiated:!0,id:0}),N=setTimeout(()=>{let B=`Data channel was never opened: state: ${P.readyState}`;this.log.error(B),this.metrics?.dialerEvents.increment({open_error:!0}),T(o3("data",B))},iN);P.onopen=B=>{clearTimeout(N),R(P)},P.onerror=B=>{clearTimeout(N);let X=`Error opening a data channel for handshaking: ${B.target?.toString()??"not specified"}`;this.log.error(X),this.metrics?.dialerEvents.increment({unknown_error:!0}),T(o3("data",X))}}),u="libp2p+webrtc+v1/"+PE(32),h=await l.createOffer(),f=CE(h,u);await l.setLocalDescription(f);let p=kE(e,u);await l.setRemoteDescription(p);let m=await d,y=this.components.peerId,w=this.generateNoisePrologue(l,a.code,e),b=Pi({prologueBytes:w})(this.components),E=ji({channel:m,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),x={...E,sink:E.sink.bind(E),source:async function*(){for await(let R of E.source)for(let T of R)yield T}()},v=new ks(this.components,{peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),I=Sc?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(I,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":v.close().catch(R=>{this.log.error("error closing connection",R)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let S=new Cs(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(y,x,i),await t.upgrader.upgradeOutbound(v,{skipProtection:!0,skipEncryption:!0,muxerFactory:S})}catch(d){throw l.close(),d}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw Rc("no local certificate");let o=TE(e,{log:this.log});if(o==null)throw Rc("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=M(s,"hex"),a=OE.encode(i,t),c=U3.decode(tf(n)),l=M("libp2p-webrtc-noise:");return ve([l,a,c])}};function BE(r){return e=>new rf(e,r)}function ME(r){return e=>new Hd(e,r)}var UE=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",o),r.removeEventListener("error",s)}function o(){n(),e()}function s(i){n(),t(i.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",o),r.addEventListener("error",s)})};var FE=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let o of n){try{await UE(r)}catch(s){if(s.message==="socket closed")break;throw s}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(o)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((o,s)=>{r.addEventListener("close",i=>{if(i.wasClean||i.code===1006)o();else{let a=Object.assign(new Error("ws error"),{event:i});s(a)}}),setTimeout(()=>{r.close()})})});var HE=Qe(KE(),1);function $E(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var qE=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,i)=>{if(n){s();return}if(o!=null){i(o);return}let a=d=>{r.removeEventListener("open",c),r.removeEventListener("error",l),d()},c=()=>{a(s)},l=d=>{a(()=>{i(d.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let s=new HE.EventIterator(({push:i,stop:a,fail:c})=>{let l=u=>{let h=null;typeof u.data=="string"&&(h=M(u.data)),$E(u.data)&&(h=new Uint8Array(u.data)),u.data instanceof Uint8Array&&(h=u.data),h!=null&&i(h)},d=u=>{c(u.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",d),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",d),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let i of s)yield $E(i)?new Uint8Array(i):i}(),n=r.readyState===1,o;return r.addEventListener("open",()=>{n=!0,o=null}),r.addEventListener("close",()=>{n=!1,o=null}),r.addEventListener("error",s=>{n||(o=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var GE=(r,e)=>{e=e??{};let t=qE(r),n=e.remoteAddress,o=e.remotePort;if(r.url!=null)try{let i=new URL(r.url);n=i.hostname,o=parseInt(i.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:FE(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(i=>{r.addEventListener("close",()=>{i()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:o,socket:r}};var WE=WebSocket;var cN={"http:":"ws:","https:":"wss:"},zE="ws:",YE=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??zE}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??zE,o=e.host,s=e.port!=null&&o?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${o}${s}${r}`}let t=new URL(r);for(let[n,o]of Object.entries(cN))t.protocol===n&&(t.protocol=o);return t};function XE(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=YE(r,t),o=new WE(n.toString(),e.websocket);return GE(o,e)}function QE(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Mi.matches(t)||_s.matches(t)})}function jE(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return _s.matches(t)})}function ZE(){throw new Error("WebSocket Servers can not be created in the browser!")}function JE(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),o={log:n,async sink(s){try{await r.sink(async function*(){for await(let i of s)i instanceof Uint8Array?yield i:yield i.subarray()}())}catch(i){i.type!=="aborted"&&n.error(i)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(s={}){let i=Date.now();if(s.signal==null){let c=AbortSignal.timeout(500);s={...s,signal:c}}let a=()=>{let{host:c,port:l}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",c,l,Date.now()-i),this.abort(new g("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};s.signal?.addEventListener("abort",a);try{await r.close()}catch(c){n.error("error closing WebSocket gracefully",c),this.abort(c)}finally{s.signal?.removeEventListener("abort",a),o.timeline.close=Date.now()}},abort(s){let{host:i,port:a}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",i,a,s),r.destroy(),o.timeline.close=Date.now()}};return r.socket.addEventListener("close",()=>{o.timeline.close==null&&(o.timeline.close=Date.now())},{once:!0}),o}var H3=class{log;init;logger;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.init=t}[Symbol.toStringTag]="@libp2p/websockets";[an]=!0;async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),o=JE(n,e,{logger:this.logger});this.log("new outbound connection %s",o.remoteAddr);let s=await t.upgrader.upgradeOutbound(o);return this.log("outbound connection %s upgraded",o.remoteAddr),s}async _connect(e,t){if(t?.signal?.aborted===!0)throw new Kt;let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let o=J(),s=XE(a1(e),this.init);if(s.socket.addEventListener("error",()=>{let c=new g(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",c),o.reject(c)}),t.signal==null)return await Promise.race([s.connected(),o.promise]),this.log("connected %s",e),s;let i,a=new Promise((c,l)=>{if(i=()=>{l(new Kt),s.close().catch(d=>{this.log.error("error closing raw socket",d)})},t?.signal?.aborted===!0){i();return}t?.signal?.addEventListener("abort",i)});try{await Promise.race([a,o.promise,s.connected()])}finally{i!=null&&t?.signal?.removeEventListener("abort",i)}return this.log("connected %s",e),s}createListener(e){return ZE({logger:this.logger},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):ed||td?jE(e):QE(e)}dialFilter(e){return this.listenFilter(e)}};function eb(r={}){return e=>new H3(e,r)}function q3(r){throw new Error("Not implemented")}var G3=class extends yn{writer;reader;constructor(e){super(e),this.writer=e.bidiStream.writable.getWriter(),this.reader=e.bidiStream.readable.getReader(),Promise.resolve().then(async()=>{for(;;){let t=await this.reader.read();if(t.done){e.log("remote closed write");return}t.value!=null&&this.sourcePush(new ce(t.value))}}).catch(t=>{e.log.error("error reading from stream",t),this.abort(t)}).finally(()=>{this.remoteCloseWrite()}),this.writer.closed.then(()=>{e.log("writer closed")}).catch(t=>{e.log("writer close promise rejected",t)}).finally(()=>{this.remoteCloseRead()})}sendNewStream(e){}async sendData(e,t){for await(let n of e)this.log("sendData waiting for writer to be ready"),await Ue(this.writer.ready,t?.signal),this.writer.write(n).catch(o=>{this.log.error("error sending stream data",o)})}async sendReset(e){this.log("sendReset aborting writer"),await Ue(this.writer.abort(),e?.signal),this.log("sendReset aborted writer")}async sendCloseWrite(e){this.log("sendCloseWrite closing writer"),await Ue(this.writer.close(),e?.signal),this.log("sendCloseWrite closed writer")}async sendCloseRead(e){this.log("sendCloseRead cancelling reader"),await Ue(this.reader.cancel(),e?.signal),this.log("sendCloseRead cancelled reader")}};async function W3(r,e,t,n,o,s){let i=s.forComponent(`libp2p:webtransport:stream:${t}:${e}`),a=new G3({bidiStream:r,id:e,direction:t,log:i,onEnd:()=>{let c=n.findIndex(l=>l===a);c!==-1&&n.splice(c,1),o?.(a)}});return a}function sf(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}function tb(r,e,t,n){let o=0,s=t.forComponent("libp2p:webtransport:muxer");return{protocol:"webtransport",createStreamMuxer:i=>{typeof i=="function"&&(i={onIncomingStream:i});let a=[];return Promise.resolve().then(async()=>{for(;;){let{done:l,value:d}=await e.read();if(l)break;if(a.length>=n.maxInboundStreams)s(`too many inbound streams open - ${a.length}/${n.maxInboundStreams}, closing new incoming stream`),d.writable.close().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),d.readable.cancel().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await W3(d,String(o++),"inbound",a,i?.onStreamEnd,t);a.push(u),i?.onIncomingStream?.(u)}}}),{protocol:"webtransport",streams:a,newStream:async l=>{s("new outgoing stream",l);let d=await r.createBidirectionalStream(),u=await W3(d,String(o++),i?.direction??"outbound",a,i?.onStreamEnd,t);return a.push(u),u},close:async()=>{s("closing webtransport muxer gracefully"),r.close()},abort:l=>{s("closing webtransport muxer with err:",l),r.close()},...sf()}}}}function rb(r,e){return e.filter(n=>!!r.find(o=>Z(n,o))).length===e.length}var fN=Object.values(br).map(r=>r.decoder).reduce((r,e)=>r.or(e));function hN(r){return Er.decode(fN.decode(r))}function z3(r){if(!i1.matches(r))throw new g("Invalid multiaddr, was not a WebTransport address","ERR_INVALID_MULTIADDR");let e=r.stringTuples(),t=e.filter(([i,a])=>i===ee("certhash").code).map(([i,a])=>hN(a??"")),n=e.filter(([i,a])=>i===ee("p2p").code).map(([i,a])=>ge(a??""))[0],o=r.toOptions(),s=o.host;return o.family===6&&s?.includes(":")&&(s=`[${s}]`),{url:`https://${s}:${o.port}`,certhashes:t,remotePeer:n}}var nb=WebTransport;var Y3=class{log;components;config;metrics;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webtransport"),this.components=e,this.config={...t,maxInboundStreams:t.maxInboundStreams??1e3,certificates:t.certificates??[]},e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webtransport_dialer_events_total",{label:"event",help:"Total count of WebTransport dialer events by type"})})}[Symbol.toStringTag]="@libp2p/webtransport";[an]=!0;async dial(e,t){if(t?.signal?.aborted===!0)throw new Kt;this.log("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new g("Need a local peerid","ERR_INVALID_PARAMETERS");t=t??{};let{url:o,certhashes:s,remotePeer:i}=z3(e),a,c,l=()=>{},d=!1,u=!1,h=!1;try{this.metrics?.dialerEvents.increment({pending:!0});let f=new nb(`${o}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(p=>({algorithm:"sha-256",value:p.digest}))});if(l=p=>{if(!d)try{this.metrics?.dialerEvents.increment({[p]:!0}),f.close()}catch(m){this.log.error("error closing wt session",m)}finally{c!=null&&(c.timeline.close=Date.now()),d=!0}},a=()=>{l(u?"noise_timeout":"ready_timeout")},t.signal?.addEventListener("abort",a,{once:!0}),this.log("wait for session to be ready"),await Promise.race([f.closed,f.ready]),this.log("session became ready"),u=!0,this.metrics?.dialerEvents.increment({ready:!0}),f.closed.catch(p=>{this.log.error("error on remote wt session close",p)}).finally(()=>{l("remote_close")}),h=await Ue(this.authenticateWebTransport(f,n,i,s),t.signal),!h)throw new g("Failed to authenticate webtransport","ERR_AUTHENTICATION_FAILED");return this.metrics?.dialerEvents.increment({open:!0}),c={close:async()=>{this.log("closing webtransport"),l("close")},abort:p=>{this.log("aborting webtransport due to passed err",p),l("abort")},remoteAddr:e,timeline:{open:Date.now()},log:this.components.logger.forComponent("libp2p:webtransport:maconn"),...sf()},await t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:tb(f,f.incomingBidirectionalStreams.getReader(),this.components.logger,this.config),skipProtection:!0})}catch(f){throw this.log.error("caught wt session err",f),l(h?"upgrade_error":u?"noise_error":"ready_error"),f}finally{a!=null&&t.signal?.removeEventListener("abort",a)}}async authenticateWebTransport(e,t,n,o=[],s){if(s?.aborted===!0)throw new Kt;let i=await e.createBidirectionalStream(),a=i.writable.getWriter(),c=i.readable.getReader(),l={source:async function*(){for(;;){let h=await c.read();if(h.value!=null&&(yield h.value),h.done)break}}(),sink:async h=>{for await(let f of h){await Ue(a.ready,s);let p=f instanceof Uint8Array?f:f.subarray();a.write(p).catch(m=>{this.log.error("could not write chunk during authentication of WebTransport stream",m)})}}},d=Pi()(this.components),{remoteExtensions:u}=await d.secureOutbound(t,l,n);if(a.close().catch(h=>{this.log.error(`Failed to close authentication stream writer: ${h.message}`)}),c.cancel().catch(h=>{this.log.error(`Failed to close authentication stream reader: ${h.message}`)}),!rb(u?.webtransportCerthashes??[],o.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}createListener(e){return q3(this.components,{...e,certificates:this.config.certificates,maxInboundStreams:this.config.maxInboundStreams})}listenFilter(){return[]}dialFilter(e){return e.filter(t=>{if(!i1.exactMatch(t))return!1;let{url:n,certhashes:o}=z3(t);return n!=null&&o.length>0})}};function ob(r={}){return e=>new Y3(e,r)}var X3=Qe(p1(),1);function sb(r,e){let t=e.map((n,o)=>({record:mn(n),index:o}));return t.sort((n,o)=>{let s=n.record.sequence,i=o.record.sequence;if(s>i)return-1;if(s<i)return 1;if(n.record.validityType===Xt.ValidityType.EOL&&o.record.validityType===Xt.ValidityType.EOL){let a=X3.default.fromString(n.record.validity).toDate(),c=X3.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var af="1.6.0",cf="libp2p";var ab="4.2.3",cb="helia";var lb={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function lf(r={}){let e=`${cb}/${ab} ${cf}/${af} UserAgent=${globalThis.navigator.userAgent}`;return{peerId:r.peerId,dns:r.dns,addresses:{listen:["/webrtc"]},transports:[kp({discoverRelays:1}),ME(),BE(),ob(),eb()],connectionEncryption:[Pi()],streamMuxers:[j7(),Ky()],peerDiscovery:[h9(lb)],services:{autoNAT:t9(),dcutr:D9(),delegatedRouting:()=>e7("https://delegated-ipfs.dev"),dht:py({clientMode:!0,validators:{ipns:y1},selectors:{ipns:sb}}),identify:$9({agentVersion:e}),identifyPush:H9({agentVersion:e}),keychain:Nd(r.keychain),ping:Gy()}}}var It={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var ca;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>re(i,o.codec()),o.decode=i=>te(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),df.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=df.codec().decode(i,i.uint32());break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>re(i,o.codec()),o.decode=i=>te(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ne((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),uf.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(uf.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let l=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(l.key,l.value);break}case 7:{let l=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(l.key,l.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>re(o,r.codec()),r.decode=o=>te(o,r.codec())})(ca||(ca={}));var uf;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(uf||(uf={}));var df;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(df||(df={}));function la(r,e){let t=ca.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=u8({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:j(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Q3="/peers/";function ua(r){if(!Ms(r)||r.type==null)throw new g("Invalid PeerId",It.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Pe(`${Q3}${e}`)}async function ub(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=j(o.multiaddr)),!ko(o.multiaddr))throw new g("Multiaddr was invalid",It.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function hf(r,e,t,n){if(e==null)throw new g("Invalid PeerData",It.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!Z(e.publicKey,r.publicKey))throw new g("publicKey bytes do not match peer id publicKey bytes",It.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new g("peer id did not match existing peer id",It.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=ff(u,{validate:db})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ff(u,{validate:fb,map:hb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,f]of u)f==null?a.delete(h):a.set(h,f);a=ff([...a.entries()],{validate:db})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[f,p]of u)p==null?h.delete(f):h.set(f,p);c=ff([...h.entries()],{validate:fb,map:hb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let d={addresses:await ub(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((u,h)=>u.localeCompare(h)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:l};return r.type!=="RSA"&&delete d.publicKey,d}function ff(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function db(r,e){if(typeof r!="string")throw new g("Metadata key must be a string",It.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new g("Metadata value must be a Uint8Array",It.ERR_INVALID_PARAMETERS)}function fb(r,e){if(typeof r!="string")throw new g("Tag name must be a string",It.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new g("Tag value must be an integer",It.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new g("Tag value must be between 0-100",It.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new g("Tag ttl must be an integer",It.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new g("Tag ttl must be between greater than 0",It.ERR_INVALID_PARAMETERS)}}function hb(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function pf(r,e,t){let n=r.toString().split("/")[2],o=ut.decode(n),s=Je(o),i=t.get(s);if(i!=null)return i;let a=la(s,e);return t.set(s,a),a}function pN(r,e){return r==null?{}:{prefix:Q3,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(pf(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(pf(n.key,n.value,e),pf(o.key,o.value,e)))}}var mf=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Ya({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(ua(e))}async delete(e){if(this.peerId.equals(e))throw new g("Cannot delete self peer",It.ERR_INVALID_PARAMETERS);await this.datastore.delete(ua(e))}async load(e){let t=await this.datastore.get(ua(e));return la(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new it;for await(let{key:n,value:o}of this.datastore.query(pN(e??{},t))){let s=pf(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(ua(e)),n=la(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=ca.encode(t);return n!=null&&Z(s,n)?{peer:la(e,s),previous:o,updated:!1}:(await this.datastore.put(ua(e),s),{peer:la(e,s),previous:o,updated:!0})}};var gf=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new mf(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await sc(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mr.openAndCertify(e,Vt.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Vt.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await mr.createFromProtobuf(s.peerRecordEnvelope),a=Vt.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function pb(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var mN=r=>r;function j3(r,e){let t=r.getPeerId();return t!=null&&ge(t).equals(e)&&(r=r.decapsulate(j(`/p2p/${e.toString()}`))),r}var yf=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??mN,this._updatePeerStoreAddresses=pb(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>j(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>j(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>j(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>j(e))}addObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>j(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var Z3=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=So())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Fc(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},gN=["metrics","connectionProtector","dns"],yN=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function mb(r={}){let e=new Z3(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!yN.includes(o)){let i=e.components[o];if(i==null&&!gN.includes(o))throw new g(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function gb(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Yt(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function J3(r){try{let{address:e}=r.nodeAddress();return!!Yt(e)}catch{return!0}}function wN(r,e){let t=J3(r.multiaddr),n=J3(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function EN(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function bN(r,e){let t=bs.exactMatch(r.multiaddr),n=bs.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function da(r,e){let t=wN(r,e);if(t!==0)return t;let n=bN(r,e);return n!==0?n:EN(r,e)}var xN=32,{code:vN}=ee("dnsaddr"),Ps=async function(e,t={}){let n=t.maxRecursiveDepth??xN;if(n===0)throw new g("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([l])=>l===vN)??[],i=await(t?.dns??wu()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[ar.TXT]}),a=e.getPeerId(),c=[];for(let l of i.Answer){let d=l.data.replace(/["']/g,"").trim().split("=")[1];if(d==null||a!=null&&!d.includes(a))continue;let u=j(d);if(d.startsWith("/dnsaddr")){let h=await u.resolve({...t,maxRecursiveDepth:n-1});c.push(...h.map(f=>f.toString()))}else c.push(u.toString())}return c};var Jn;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Jn||(Jn={}));var z;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(z||(z={}));var RN={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ps},addressSorter:da},transportManager:{faultTolerance:to.FATAL_ALL}};async function yb(r){let e=Xi(RN,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new g(Jn.ERR_PROTECTOR_REQUIRED,z.ERR_PROTECTOR_REQUIRED);if(!(await dt(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new g("Private key doesn't match peer id",z.ERR_INVALID_KEY);return e}function wf(r){if(Ms(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:ge(t),r.forEach(n=>{if(!ko(n))throw new g("Invalid Multiaddr",z.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new g("Multiaddrs must all have the same peer id or have no peer id",z.ERR_INVALID_PARAMETERS)}else{let s=ge(o);if(e==null||!e.equals(s))throw new g("Multiaddrs must all have the same peer id or have no peer id",z.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}var Ef="last-dial-failure";var bf=5,xf=100,vf=50,Rf=1e3*60*7;var Os={minConnections:bf,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Rf,autoDialDiscoveredPeersDebounce:10},Sf=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Os.minConnections,this.autoDialPriority=t.autoDialPriority??Os.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Os.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Os.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Os.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Os.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new wr({concurrency:t.autoDialConcurrency??Os.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new ht(this.connectionManager.getDialQueue().map(l=>l.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[l=>l.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",l.id),!1):e.has(l.id)?(this.log.trace("not autodialing %p because they are already connected",l.id),!1):n.has(l.id)?(this.log.trace("not autodialing %p because they are already being dialed",l.id),!1):this.queue.has(l.id)?(this.log.trace("not autodialing %p because they are already being autodialed",l.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new it;for(let l of s)i.has(l.id)||i.set(l.id,[...l.tags.values()].reduce((d,u)=>d+u.value,0));let c=s.sort((l,d)=>{let u=i.get(l.id)??0,h=i.get(d.id)??0;return u>h?-1:u<h?1:0}).filter(l=>{let d=l.metadata.get(Ef);if(d==null)return!0;let u=parseInt(O(d));return isNaN(u)?!0:Date.now()-u>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let l of c)this.queue.add(async()=>{let d=this.connectionManager.getConnectionsMap().size;if(d>=this.minConnections){this.log("got enough connections now %d/%d",d,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",l.id),await this.connectionManager.openConnection(l.id,{priority:this.autoDialPriority})},{peerId:l.id}).catch(d=>{this.log.error("could not connect to peerStore stored peer",d)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var _N=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function wb(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??_N;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Eb={maxConnections:xf,allow:[]},_f=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Eb.maxConnections,this.allow=t.allow??Eb.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new it;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((d,u)=>d+u.value,0))}catch(l){l.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>a.remoteAddr.toString().startsWith(l.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await wb(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Af=class extends tr{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};async function bb(r,e){let t=!1;for(let o of Di.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var Lc={addressSorter:da,maxParallelDials:vf,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Ps}},If=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Lc.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Lc.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Lc.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Lc.dialTimeout,this.connections=t.connections??new it,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))Di.set(n,o);this.queue=new Af({concurrency:t.maxParallelDials??Lc.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=wf(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new g("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),this.queue.add(async a=>{let c=this.createDialAbortController(a?.signal),l;try{l=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),l.map(({multiaddr:d})=>d.toString()).forEach(d=>{a?.multiaddrs.add(d)})}catch(d){throw c.clear(),d}try{let d=0,u=[];for(let h of l){if(d===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",d,n),new g("Peer had more than maxPeerAddrsToDial",z.ERR_TOO_MANY_ADDRESSES);d++;try{let f=await this.components.transportManager.dial(h.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",h.multiaddr),f}catch(f){if(this.log.error("dial failed to %a",h.multiaddr,f),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[Ef]:M(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new g(f.message,vn);u.push(f)}}throw u.length===1?u[0]:new Uc(u,"All multiaddr dials failed",z.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??a4,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=Ae([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return H(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:j(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new g("Tried to dial self",z.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new g("The dial request is blocked by gater.allowDialPeer",z.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:h})=>h.toString()))}catch(u){if(u.code!==z.ERR_NOT_FOUND)throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:h})=>h.toString())),o.push(...u.multiaddrs.map(h=>({multiaddr:h,isCertified:!1})))}catch(u){u.code!==z.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,u)}}}let s=(await Promise.all(o.map(async u=>{let h=await bb(u.multiaddr,{dns:this.components.dns,...n,log:this.log});return h.length===1&&h[0].equals(u.multiaddr)?u:h.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;s=s.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(u),isCertified:h.isCertified}:h)}let i=s.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let h=u.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),a=new Map;for(let u of i){let h=u.multiaddr.toString(),f=a.get(h);if(f!=null){f.isCertified=f.isCertified||u.isCertified||!1;continue}a.set(h,u)}let c=[...a.values()];if(c.length===0)throw new g("The dial request has no valid addresses",z.ERR_NO_VALID_ADDRESSES);let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let d=l.sort(this.addressSorter);if(d.length===0)throw new g("The connection gater denied all addresses in the dial request",z.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",d.map(({multiaddr:u})=>u.toString())),d}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!bs.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var a4=50,eo={minConnections:bf,maxConnections:xf,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Rf,autoDialDiscoveredPeersDebounce:10},Df=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??eo.maxConnections;let n=t.minConnections??eo.minConnections;if(this.maxConnections<n)throw new g("Connection Manager maxConnections must be greater than minConnections",z.ERR_INVALID_PARAMETERS);this.connections=new it,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(o=>j(o)),this.deny=(t.deny??[]).map(o=>j(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??eo.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Qi({points:t.inboundConnectionThreshold??eo.inboundConnectionThreshold,duration:1}),this.autoDial=new Sf({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??eo.autoDialConcurrency,autoDialPriority:t.autoDialPriority??eo.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??eo.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??eo.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??eo.autoDialMaxQueueLength}),this.connectionPruner=new _f({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new If(e,{addressSorter:t.addressSorter??da,maxParallelDials:t.maxParallelDials??vf,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Ps},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(R4)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new g("Not started",z.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=wf(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??a4}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>j(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Tf=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new g("No content routers available",z.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ht;for await(let s of Mt(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new g("No content routers available",z.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new g(Jn.NOT_STARTED_YET,z.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new g(Jn.NOT_STARTED_YET,z.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var kf=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}async findPeer(e,t){if(this.routers.length===0)throw new g("No peer routers available",z.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new g("Should not try to find self",z.ERR_FIND_SELF);let n=this,o=Mt(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new g(Jn.NOT_FOUND,z.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new g("No peer routers available",z.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ht;for await(let s of en(async function*(){let i=Mt(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}};var Cf=class extends ye{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,H(1/0,this.shutdownController.signal)}start(){this.shutdownController=new AbortController,H(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ae([this.shutdownController.signal,e?.signal]);H(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=J(),yield(await er(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,H(1/0,this.walkController.signal);let e=Ae([this.walkController.signal,this.shutdownController.signal]);H(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{for await(let o of this.peerRouting.getClosestPeers(pt(32),{signal:e}))e.throwIfAborted(),this.log("found peer %p",o.id),n++,this.safeDispatchEvent("walk:peer",{detail:o}),this.walkers===1&&this.needNext!=null&&await Ue(this.needNext.promise,e)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var c4=32,l4=64,Nf=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new g(`No handler registered for protocol ${e}`,z.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new g(`Handler already registered for protocol ${e}`,z.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=Xi.bind({ignoreUndefined:!0})({maxInboundStreams:c4,maxOutboundStreams:l4},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new g("invalid topology",z.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.code!==z.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Lf=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Wu({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??to.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new g("Transport must have a valid tag",z.ERR_INVALID_KEY);if(this.transports.has(t))throw new g(`There is already a transport with the tag ${t}`,z.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new g(`No transport available for address ${String(e)}`,z.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=z.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new g("Not started",z.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let l of s){this.log("creating listener for %s on %a",n,l);let d=o.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(n)??[];u==null&&(u=[],this.listeners.set(n,u)),u.push(d),d.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:d})}),d.addEventListener("close",()=>{let h=u.findIndex(f=>f===d);u.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:d})}),i.push(d.listen(l))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(l=>l.status==="fulfilled")==null&&this.faultTolerance!==to.NO_FATAL)throw new g(`Transport (${n}) could not listen on any available address`,z.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===to.FATAL_ALL)throw new g(n,z.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Dt="/multistream/1.0.0";var DN=M(`
53
53
  `);async function Bs(r,e,t){await r.write(e,t)}async function xb(r,e,t){await r.writeV(e,t)}async function TN(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==DN[0])throw e.log.error("Invalid mss message - missing newline",t),new g("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return t.sublist(0,-1)}async function qo(r,e){let t=await TN(r,e);return O(t.subarray())}async function Pc(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return kN(r,e[0],t);let n=gn(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Dt,o);let s=M(`${Dt}
54
54
  `),i=M(`${o}
55
55
  `);await xb(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await qo(n,t);if(t.log.trace('select: read "%s"',a),a===Dt&&(t.log.trace("select: reading protocol response"),a=await qo(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Bs(n,M(`${c}