helia 5.2.0-2666d64 → 5.2.0-c7024de
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 +2 -2
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +5 -5
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
`).map(o=>` ${o}`).join(`
|
|
5
5
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
6
6
|
${e.join(`
|
|
7
|
-
`)}`:`${t} :`}};W6=Io;Q.Constructed=W6;Io.NAME="CONSTRUCTED";var du=class extends Bt{fromBER(e,t,n){return t}toBER(e){return Xr}};du.override="EndOfContentValueBlock";var G6,fu=class extends xt{constructor(e={}){super(e,du),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};G6=fu;Q.EndOfContent=G6;fu.NAME=Fa;var Q6,$n=class extends xt{constructor(e={}){super(e,Bt),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}`}};Q6=$n;Q.Null=Q6;$n.NAME="NULL";var hu=class extends zn(Bt){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 qn(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,_2.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};hu.NAME="BooleanValueBlock";var Y6,pu=class extends xt{constructor(e={}){super(e,hu),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}`}};Y6=pu;Q.Boolean=Y6;pu.NAME="BOOLEAN";var mu=class extends zn(xn){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=xn.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let i=0;i<this.value.length;i++){let s=this.value[i].constructor.NAME;if(s===Fa){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(s!==K6)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?xn.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};mu.NAME="OctetStringValueBlock";var X6,Kn=class r extends xt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},mu),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 i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let s=Hu(i,0,i.byteLength);s.offset!==-1&&s.offset===n&&(this.valueBlock.value=[s.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Io.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)}};X6=Kn;Q.OctetString=X6;Kn.NAME=K6;var gu=class extends zn(xn){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=xn.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Fa){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==H6)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 i=we.BufferSourceConverter.toUint8Array(e);if(!qn(this,i,t,n))return-1;let s=i.subarray(t,t+n);if(this.unusedBits=s[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=s.subarray(1);try{if(a.byteLength){let c=Hu(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,t+n}toBER(e,t){if(this.isConstructed)return xn.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Xr;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}}};gu.NAME="BitStringValueBlock";var j6,Es=class extends xt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},gu),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 Io.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)}`}}};j6=Es;Q.BitString=j6;Es.NAME=H6;var Z6;function KS(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<s?s:c,d=0;for(let h=u;h>=0;h--,d++){switch(!0){case d<a.length:l=i[s-d]+a[c-d]+t[0];break;default:l=i[s-d]+t[0]}switch(t[0]=l/10,!0){case d>=i.length:i=ou(new Uint8Array([l%10]),i);break;default:i[s-d]=l%10}}return t[0]>0&&(i=ou(t,i)),i}function $6(r){if(r>=Ma.length)for(let e=Ma.length;e<=r;e++){let t=new Uint8Array([0]),n=Ma[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let i=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=i[0]/10,n[o]=i[0]%10}t[0]>0&&(n=ou(t,n)),Ma.push(n)}return Ma[r]}function HS(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let d=c;d>=0;d--,u++)switch(l=i[s-u]-a[c-u]-t,!0){case l<0:t=1,i[s-u]=l+10;break;default:t=0,i[s-u]=l}if(t>0)for(let d=s-c+1;d>=0;d--,u++)if(l=i[s-u]-t,l<0)t=1,i[s-u]=l+10;else{t=0,i[s-u]=l;break}return i.slice()}var Va=class extends zn(Bt){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=_2.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(U6(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let i=this.fromBER(e,t,n);if(i===-1)return i;let s=this.valueHexView;return s[0]===0&&s[1]&128?this.valueHexView=s.subarray(1):o!==0&&s.length<o&&(o-s.length>1&&(o=s.length+1),this.valueHexView=s.subarray(o-s.length)),i}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,i=this.valueHexView,s="",a=!1;for(let c=i.byteLength-1;c>=0;c--){o=i[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=HS($6(n),t),s="-";break;default:t=KS(t,$6(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(s+=V6.charAt(t[c]));return a===!1&&(s+=V6.charAt(0)),s}};Z6=Va;Va.NAME="IntegerValueBlock";Object.defineProperty(Z6.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var J6,et=class r extends xt{constructor(e={}){super(e,Va),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return iu(),BigInt(this.valueBlock.toString())}static fromBigInt(e){iu();let t=BigInt(e),n=new Ua,o=t.toString(16).replace(/^-/,""),i=new Uint8Array(we.Convert.FromHex(o));if(t<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${we.Convert.ToHex(a)}`)+t,u=we.BufferSourceConverter.toUint8Array(we.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);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()}`}};J6=et;Q.Integer=J6;et.NAME="INTEGER";var e8,yu=class extends et{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};e8=yu;Q.Enumerated=e8;yu.NAME="ENUMERATED";var $a=class extends zn(Bt){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(!qn(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[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=hi(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){iu();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,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=Ao(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Xr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}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}}};$a.NAME="sidBlock";var wu=class extends Bt{constructor({value:e=Ss,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new $a;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}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,Xr;t.push(o)}return k2(t)}fromString(e){this.value=[];let t=0,n=0,o="",i=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,i){let s=this.value[0],a=0;switch(s.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;s.valueDec=c+a,i=!1}else{let s=new $a;if(o>Number.MAX_SAFE_INTEGER){iu();let a=BigInt(o);s.valueBigInt=a}else if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return;this.value.length||(s.isFirstSid=!0,i=!0),this.value.push(s)}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}};wu.NAME="ObjectIdentifierValueBlock";var t8,kr=class extends xt{constructor(e={}){super(e,wu),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()}}};t8=kr;Q.ObjectIdentifier=t8;kr.NAME="OBJECT IDENTIFIER";var Ka=class extends zn(Vn){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(!qn(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[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=hi(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,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=Ao(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Xr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}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}}};Ka.NAME="relativeSidBlock";var bu=class extends Bt{constructor({value:e=Ss,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new Ka;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let i=this.value[o].toBER(e);if(i.byteLength===0)return this.error=this.value[o].error,Xr;n.push(i)}return k2(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 i=new Ka;if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return!0;this.value.push(i)}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}};bu.NAME="RelativeObjectIdentifierValueBlock";var r8,xu=class extends xt{constructor(e={}){super(e,bu),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()}}};r8=xu;Q.RelativeObjectIdentifier=r8;xu.NAME="RelativeObjectIdentifier";var n8,dt=class extends Io{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};n8=dt;Q.Sequence=n8;dt.NAME="SEQUENCE";var o8,vu=class extends Io{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};o8=vu;Q.Set=o8;vu.NAME="SET";var Eu=class extends zn(Bt){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Ss}toJSON(){return{...super.toJSON(),value:this.value}}};Eu.NAME="StringValueBlock";var Su=class extends Eu{};Su.NAME="SimpleStringValueBlock";var Ht=class extends cu{constructor({...e}={}){super(e,Su)}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}};Ht.NAME="SIMPLE STRING";var Au=class extends Ht{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}};Au.NAME="Utf8StringValueBlock";var i8,Hn=class extends Au{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};i8=Hn;Q.Utf8String=i8;Hn.NAME="UTF8String";var Iu=class extends Ht{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))}};Iu.NAME="BmpStringValueBlock";var s8,Tu=class extends Iu{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};s8=Tu;Q.BmpString=s8;Tu.NAME="BMPString";var _u=class extends Ht{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 i=Ao(e.charCodeAt(o),8),s=new Uint8Array(i);if(s.length>4)continue;let a=4-s.length;for(let c=s.length-1;c>=0;c--)n[o*4+c+a]=s[c]}this.valueBlock.value=e}};_u.NAME="UniversalStringValueBlock";var a8,ku=class extends _u{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};a8=ku;Q.UniversalString=a8;ku.NAME="UniversalString";var c8,Cu=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};c8=Cu;Q.NumericString=c8;Cu.NAME="NumericString";var l8,Pu=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};l8=Pu;Q.PrintableString=l8;Pu.NAME="PrintableString";var u8,Ru=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};u8=Ru;Q.TeletexString=u8;Ru.NAME="TeletexString";var d8,Du=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};d8=Du;Q.VideotexString=d8;Du.NAME="VideotexString";var f8,Nu=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};f8=Nu;Q.IA5String=f8;Nu.NAME="IA5String";var h8,Lu=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};h8=Lu;Q.GraphicString=h8;Lu.NAME="GraphicString";var p8,Ha=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};p8=Ha;Q.VisibleString=p8;Ha.NAME="VisibleString";var m8,Bu=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};m8=Bu;Q.GeneralString=m8;Bu.NAME="GeneralString";var g8,Ou=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};g8=Ou;Q.CharacterString=g8;Ou.NAME="CharacterString";var y8,qa=class extends Ha{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]=er(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=er(this.month,2),t[2]=er(this.day,2),t[3]=er(this.hour,2),t[4]=er(this.minute,2),t[5]=er(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}}};y8=qa;Q.UTCTime=y8;qa.NAME="UTCTime";var w8,Mu=class extends qa{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="",i=0,s,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let d=new Number(e[e.length-1]);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let d=1,h=n.indexOf("+"),f="";if(h===-1&&(h=n.indexOf("-"),d=-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=d*p,f.length===4){if(p=parseInt(f.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=d*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let d=new Number(`0${n.substring(l)}`);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");i=d.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=60*i;this.minute=Math.floor(d),d=60*(d-this.minute),this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case o.length===12:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=60*i;this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case o.length===14:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=1e3*i;this.millisecond=Math.floor(d)}break;default:throw new Error("Wrong input string for conversion")}let u=s.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let d=1;d<u.length;d++)switch(d){case 1:this.year=parseInt(u[d],10);break;case 2:this.month=parseInt(u[d],10);break;case 3:this.day=parseInt(u[d],10);break;case 4:this.hour=parseInt(u[d],10)+a;break;case 5:this.minute=parseInt(u[d],10)+c;break;case 6:this.second=parseInt(u[d],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let d=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=d.getUTCFullYear(),this.month=d.getUTCMonth(),this.day=d.getUTCDay(),this.hour=d.getUTCHours(),this.minute=d.getUTCMinutes(),this.second=d.getUTCSeconds(),this.millisecond=d.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(er(this.year,4)),t.push(er(this.month,2)),t.push(er(this.day,2)),t.push(er(this.hour,2)),t.push(er(this.minute,2)),t.push(er(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(er(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};w8=Mu;Q.GeneralizedTime=w8;Mu.NAME="GeneralizedTime";var b8,Uu=class extends Hn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};b8=Uu;Q.DATE=b8;Uu.NAME="DATE";var x8,Fu=class extends Hn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};x8=Fu;Q.TimeOfDay=x8;Fu.NAME="TimeOfDay";var v8,Vu=class extends Hn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};v8=Vu;Q.DateTime=v8;Vu.NAME="DateTime";var E8,$u=class extends Hn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};E8=$u;Q.Duration=E8;$u.NAME="Duration";var S8,Ku=class extends Hn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};S8=Ku;Q.TIME=S8;Ku.NAME="TIME";function $(r,e="utf8"){let t=Ml[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function qt(r){if(isNaN(r)||r<=0)throw new P("random bytes length must be a Number bigger than 0");return ci(r)}var za=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Wa=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},qu=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var A8={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new qu("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var tr=A8;async function I8(r){let e=await tr.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 qS(e);return{privateKey:t[0],publicKey:t[1]}}async function T8(r,e){let t=await tr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await tr.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function _8(r,e,t){let n=await tr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return tr.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function qS(r){if(r.privateKey==null||r.publicKey==null)throw new P("Private and public key are required");return Promise.all([tr.get().subtle.exportKey("jwk",r.privateKey),tr.get().subtle.exportKey("jwk",r.publicKey)])}function R2(r){if(r.kty!=="RSA")throw new P("invalid key type");if(r.n==null)throw new P("invalid key modulus");return M(r.n,"base64url").length*8}var As=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Ga.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return j.createV1(114,this._multihash)}toString(){return Ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:oe(this.raw,e.raw)}verify(e,t){return _8(this._key,t,e)}},Qa=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Ga.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:oe(this.raw,e.raw)}sign(e){return T8(this._key,e)}};var zu=8192,D2=18;function k8(r){let{result:e}=pi(r),t=e.valueBlock.value;return{n:vn(t[1]),e:vn(t[2]),d:vn(t[3]),p:vn(t[4]),q:vn(t[5]),dp:vn(t[6]),dq:vn(t[7]),qi:vn(t[8]),kty:"RSA",alg:"RS256"}}function zS(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 P("JWK was missing components");let t=new dt({value:[new et({value:0}),et.fromBigInt(En(M(r.n,"base64url"))),et.fromBigInt(En(M(r.e,"base64url"))),et.fromBigInt(En(M(r.d,"base64url"))),et.fromBigInt(En(M(r.p,"base64url"))),et.fromBigInt(En(M(r.q,"base64url"))),et.fromBigInt(En(M(r.dp,"base64url"))),et.fromBigInt(En(M(r.dq,"base64url"))),et.fromBigInt(En(M(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function C8(r){let{result:e}=pi(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:vn(t[0]),e:vn(t[1])}}function N2(r){if(r.n==null||r.e==null)throw new P("JWK was missing components");let t=new dt({value:[new dt({value:[new kr({value:"1.2.840.113549.1.1.1"}),new $n]}),new Es({valueHex:new dt({value:[et.fromBigInt(En(M(r.n,"base64url"))),et.fromBigInt(En(M(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function vn(r){let e=r.valueBlock.valueHexView;for(;e[0]===0;)e=e.subarray(1);return $(e,"base64url")}function En(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(""))}function Wu(r){let e=k8(r);return P8(e)}function L2(r){let e=C8(r);if(R2(e)>zu)throw new Rn("Key size is too large");let t=Tr(bn.encode({Type:Qe.RSA,Data:r})),n=jt(D2,t);return new As(e,n)}function P8(r){if(R2(r)>zu)throw new P("Key size is too large");let e=R8(r),t=Tr(bn.encode({Type:Qe.RSA,Data:N2(e.publicKey)})),n=jt(D2,t);return new Qa(e.privateKey,new As(e.publicKey,n))}async function B2(r){if(r>zu)throw new P("Key size is too large");let e=await I8(r),t=Tr(bn.encode({Type:Qe.RSA,Data:N2(e.publicKey)})),n=jt(D2,t);return new Qa(e.privateKey,new As(e.publicKey,n))}function R8(r){if(r==null)throw new P("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Gu=class extends ps{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ii(e);let n=Wr(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?e.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(e){return hs(this),this.iHash.update(e),this}digestInto(e){hs(this),fs(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},To=(r,e,t)=>new Gu(r,e).update(t).digest();To.create=(r,e)=>new Gu(r,e);function D8(r){r.lowS!==void 0&&Gr("lowS",r.lowS),r.prehash!==void 0&&Gr("prehash",r.prehash)}function WS(r){let e=Ra(r);Ir(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("invalid 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("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:GS,hexToBytes:QS}=Xl,O2=class extends Error{constructor(e=""){super(e)}},Wn={Err:O2,_tlv:{encode:(r,e)=>{let{Err:t}=Wn;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=li(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?li(o.length/2|128):"";return li(r)+i+o+e},decode(r,e){let{Err:t}=Wn,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(r){let{Err:e}=Wn;if(r<Gn)throw new e("integer: negative integers are not allowed");let t=li(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Wn;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return GS(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Wn,o=typeof r=="string"?QS(r):r;gs(o);let{v:i,l:s}=n.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Wn,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),i=n+o;return e.encode(48,i)}},Gn=BigInt(0),ht=BigInt(1),vO=BigInt(2),N8=BigInt(3),EO=BigInt(4);function YS(r){let e=WS(r),{Fp:t}=e,n=vo(e.n,e.nBitLength),o=e.toBytes||((m,g,y)=>{let b=g.toAffine();return Un(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),i=e.fromBytes||(m=>{let g=m.subarray(1),y=t.fromBytes(g.subarray(0,t.BYTES)),b=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:y,y:b}});function s(m){let{a:g,b:y}=e,b=t.sqr(m),w=t.mul(b,m);return t.add(t.add(w,t.mul(m,g)),y)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Ca(m,ht,e.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:y,wrapPrivateKey:b,n:w}=e;if(g&&typeof m!="bigint"){if(bo(m)&&(m=Bn(m)),typeof m!="string"||!g.includes(m.length))throw new Error("invalid private key");m=m.padStart(y*2,"0")}let x;try{x=typeof m=="bigint"?m:On(De("private key",m,y))}catch{throw new Error("invalid private key, expected hex or "+y+" bytes, got "+typeof m)}return b&&(x=Te(x,w)),bt("private key",x,ht,w),x}function l(m){if(!(m instanceof h))throw new Error("ProjectivePoint expected")}let u=di((m,g)=>{let{px:y,py:b,pz:w}=m;if(t.eql(w,t.ONE))return{x:y,y:b};let x=m.is0();g==null&&(g=x?t.ONE:t.inv(w));let _=t.mul(y,g),k=t.mul(b,g),E=t.mul(w,g);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(E,t.ONE))throw new Error("invZ was invalid");return{x:_,y:k}}),d=di(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y}=m.toAffine();if(!t.isValid(g)||!t.isValid(y))throw new Error("bad point: x or y not FE");let b=t.sqr(y),w=s(g);if(!t.eql(b,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class h{constructor(g,y,b){if(this.px=g,this.py=y,this.pz=b,g==null||!t.isValid(g))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:y,y:b}=g||{};if(!g||!t.isValid(y)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof h)throw new Error("projective point not allowed");let w=x=>t.eql(x,t.ZERO);return w(y)&&w(b)?h.ZERO:new h(y,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let y=t.invertBatch(g.map(b=>b.pz));return g.map((b,w)=>b.toAffine(y[w])).map(h.fromAffine)}static fromHex(g){let y=h.fromAffine(i(De("pointHex",g)));return y.assertValidity(),y}static fromPrivateKey(g){return h.BASE.multiply(c(g))}static msm(g,y){return eu(h,n,g,y)}_setWindowSize(g){p.setWindowSize(this,g)}assertValidity(){d(this)}hasEvenY(){let{y:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){l(g);let{px:y,py:b,pz:w}=this,{px:x,py:_,pz:k}=g,E=t.eql(t.mul(y,k),t.mul(x,w)),S=t.eql(t.mul(b,k),t.mul(_,w));return E&&S}negate(){return new h(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:y}=e,b=t.mul(y,N8),{px:w,py:x,pz:_}=this,k=t.ZERO,E=t.ZERO,S=t.ZERO,T=t.mul(w,w),V=t.mul(x,x),L=t.mul(_,_),O=t.mul(w,x);return O=t.add(O,O),S=t.mul(w,_),S=t.add(S,S),k=t.mul(g,S),E=t.mul(b,L),E=t.add(k,E),k=t.sub(V,E),E=t.add(V,E),E=t.mul(k,E),k=t.mul(O,k),S=t.mul(b,S),L=t.mul(g,L),O=t.sub(T,L),O=t.mul(g,O),O=t.add(O,S),S=t.add(T,T),T=t.add(S,T),T=t.add(T,L),T=t.mul(T,O),E=t.add(E,T),L=t.mul(x,_),L=t.add(L,L),T=t.mul(L,O),k=t.sub(k,T),S=t.mul(L,V),S=t.add(S,S),S=t.add(S,S),new h(k,E,S)}add(g){l(g);let{px:y,py:b,pz:w}=this,{px:x,py:_,pz:k}=g,E=t.ZERO,S=t.ZERO,T=t.ZERO,V=e.a,L=t.mul(e.b,N8),O=t.mul(y,x),B=t.mul(b,_),D=t.mul(w,k),N=t.add(y,b),I=t.add(x,_);N=t.mul(N,I),I=t.add(O,B),N=t.sub(N,I),I=t.add(y,w);let A=t.add(x,k);return I=t.mul(I,A),A=t.add(O,D),I=t.sub(I,A),A=t.add(b,w),E=t.add(_,k),A=t.mul(A,E),E=t.add(B,D),A=t.sub(A,E),T=t.mul(V,I),E=t.mul(L,D),T=t.add(E,T),E=t.sub(B,T),T=t.add(B,T),S=t.mul(E,T),B=t.add(O,O),B=t.add(B,O),D=t.mul(V,D),I=t.mul(L,I),B=t.add(B,D),D=t.sub(O,D),D=t.mul(V,D),I=t.add(I,D),O=t.mul(B,I),S=t.add(S,O),O=t.mul(A,I),E=t.mul(N,E),E=t.sub(E,O),O=t.mul(N,B),T=t.mul(A,T),T=t.add(T,O),new h(E,S,T)}subtract(g){return this.add(g.negate())}is0(){return this.equals(h.ZERO)}wNAF(g){return p.wNAFCached(this,g,h.normalizeZ)}multiplyUnsafe(g){let{endo:y,n:b}=e;bt("scalar",g,Gn,b);let w=h.ZERO;if(g===Gn)return w;if(this.is0()||g===ht)return this;if(!y||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,g,h.normalizeZ);let{k1neg:x,k1:_,k2neg:k,k2:E}=y.splitScalar(g),S=w,T=w,V=this;for(;_>Gn||E>Gn;)_&ht&&(S=S.add(V)),E&ht&&(T=T.add(V)),V=V.double(),_>>=ht,E>>=ht;return x&&(S=S.negate()),k&&(T=T.negate()),T=new h(t.mul(T.px,y.beta),T.py,T.pz),S.add(T)}multiply(g){let{endo:y,n:b}=e;bt("scalar",g,ht,b);let w,x;if(y){let{k1neg:_,k1:k,k2neg:E,k2:S}=y.splitScalar(g),{p:T,f:V}=this.wNAF(k),{p:L,f:O}=this.wNAF(S);T=p.constTimeNegate(_,T),L=p.constTimeNegate(E,L),L=new h(t.mul(L.px,y.beta),L.py,L.pz),w=T.add(L),x=V.add(O)}else{let{p:_,f:k}=this.wNAF(g);w=_,x=k}return h.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(g,y,b){let w=h.BASE,x=(k,E)=>E===Gn||E===ht||!k.equals(w)?k.multiplyUnsafe(E):k.multiply(E),_=x(this,y).add(x(g,b));return _.is0()?void 0:_}toAffine(g){return u(this,g)}isTorsionFree(){let{h:g,isTorsionFree:y}=e;if(g===ht)return!0;if(y)return y(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:y}=e;return g===ht?this:y?y(h,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return Gr("isCompressed",g),this.assertValidity(),o(h,this,g)}toHex(g=!0){return Gr("isCompressed",g),Bn(this.toRawBytes(g))}}h.BASE=new h(e.Gx,e.Gy,t.ONE),h.ZERO=new h(t.ZERO,t.ONE,t.ZERO);let f=e.nBitLength,p=Jl(h,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:a}}function XS(r){let e=Ra(r);return Ir(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function L8(r){let e=XS(r),{Fp:t,n}=e,o=t.BYTES+1,i=2*t.BYTES+1;function s(D){return Te(D,n)}function a(D){return jl(D,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:d}=YS({...e,toBytes(D,N,I){let A=N.toAffine(),R=t.toBytes(A.x),C=Un;return Gr("isCompressed",I),I?C(Uint8Array.from([N.hasEvenY()?2:3]),R):C(Uint8Array.from([4]),R,t.toBytes(A.y))},fromBytes(D){let N=D.length,I=D[0],A=D.subarray(1);if(N===o&&(I===2||I===3)){let R=On(A);if(!Ca(R,ht,t.ORDER))throw new Error("Point is not on curve");let C=u(R),H;try{H=t.sqrt(C)}catch(ce){let se=ce instanceof Error?": "+ce.message:"";throw new Error("Point is not on curve"+se)}let z=(H&ht)===ht;return(I&1)===1!==z&&(H=t.neg(H)),{x:R,y:H}}else if(N===i&&I===4){let R=t.fromBytes(A.subarray(0,t.BYTES)),C=t.fromBytes(A.subarray(t.BYTES,2*t.BYTES));return{x:R,y:C}}else{let R=o,C=i;throw new Error("invalid Point, expected length of "+R+", or uncompressed "+C+", got "+N)}}}),h=D=>Bn(xo(D,e.nByteLength));function f(D){let N=n>>ht;return D>N}function p(D){return f(D)?s(-D):D}let m=(D,N,I)=>On(D.slice(N,I));class g{constructor(N,I,A){this.r=N,this.s=I,this.recovery=A,this.assertValidity()}static fromCompact(N){let I=e.nByteLength;return N=De("compactSignature",N,I*2),new g(m(N,0,I),m(N,I,2*I))}static fromDER(N){let{r:I,s:A}=Wn.toSig(De("DER",N));return new g(I,A)}assertValidity(){bt("r",this.r,ht,n),bt("s",this.s,ht,n)}addRecoveryBit(N){return new g(this.r,this.s,N)}recoverPublicKey(N){let{r:I,s:A,recovery:R}=this,C=k(De("msgHash",N));if(R==null||![0,1,2,3].includes(R))throw new Error("recovery id invalid");let H=R===2||R===3?I+e.n:I;if(H>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let z=R&1?"03":"02",X=c.fromHex(z+h(H)),ce=a(H),se=s(-C*ce),fe=s(A*ce),ve=c.BASE.multiplyAndAddUnsafe(X,se,fe);if(!ve)throw new Error("point at infinify");return ve.assertValidity(),ve}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return ui(this.toDERHex())}toDERHex(){return Wn.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return ui(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let y={isValidPrivateKey(D){try{return l(D),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let D=m2(e.n);return v6(e.randomBytes(D),e.n)},precompute(D=8,N=c.BASE){return N._setWindowSize(D),N.multiply(BigInt(3)),N}};function b(D,N=!0){return c.fromPrivateKey(D).toRawBytes(N)}function w(D){let N=bo(D),I=typeof D=="string",A=(N||I)&&D.length;return N?A===o||A===i:I?A===2*o||A===2*i:D instanceof c}function x(D,N,I=!0){if(w(D))throw new Error("first arg must be private key");if(!w(N))throw new Error("second arg must be public key");return c.fromHex(N).multiply(l(D)).toRawBytes(I)}let _=e.bits2int||function(D){if(D.length>8192)throw new Error("input is too large");let N=On(D),I=D.length*8-e.nBitLength;return I>0?N>>BigInt(I):N},k=e.bits2int_modN||function(D){return s(_(D))},E=Pa(e.nBitLength);function S(D){return bt("num < 2^"+e.nBitLength,D,Gn,E),xo(D,e.nByteLength)}function T(D,N,I=V){if(["recovered","canonical"].some(Be=>Be in I))throw new Error("sign() legacy options not supported");let{hash:A,randomBytes:R}=e,{lowS:C,prehash:H,extraEntropy:z}=I;C==null&&(C=!0),D=De("msgHash",D),D8(I),H&&(D=De("prehashed msgHash",A(D)));let X=k(D),ce=l(N),se=[S(ce),S(X)];if(z!=null&&z!==!1){let Be=z===!0?R(t.BYTES):z;se.push(De("extraEntropy",Be))}let fe=Un(...se),ve=X;function Le(Be){let $e=_(Be);if(!d($e))return;let kt=a($e),Yt=c.BASE.multiply($e).toAffine(),Ut=s(Yt.x);if(Ut===Gn)return;let fn=s(kt*s(ve+Ut*ce));if(fn===Gn)return;let Pn=(Yt.x===Ut?0:2)|Number(Yt.y&ht),ba=fn;return C&&f(fn)&&(ba=p(fn),Pn^=1),new g(Ut,ba,Pn)}return{seed:fe,k2sig:Le}}let V={lowS:e.lowS,prehash:!1},L={lowS:e.lowS,prehash:!1};function O(D,N,I=V){let{seed:A,k2sig:R}=T(D,N,I),C=e;return u2(C.hash.outputLen,C.nByteLength,C.hmac)(A,R)}c.BASE._setWindowSize(8);function B(D,N,I,A=L){let R=D;N=De("msgHash",N),I=De("publicKey",I);let{lowS:C,prehash:H,format:z}=A;if(D8(A),"strict"in A)throw new Error("options.strict was renamed to lowS");if(z!==void 0&&z!=="compact"&&z!=="der")throw new Error("format must be compact or der");let X=typeof R=="string"||bo(R),ce=!X&&!z&&typeof R=="object"&&R!==null&&typeof R.r=="bigint"&&typeof R.s=="bigint";if(!X&&!ce)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let se,fe;try{if(ce&&(se=new g(R.r,R.s)),X){try{z!=="compact"&&(se=g.fromDER(R))}catch(Pn){if(!(Pn instanceof Wn.Err))throw Pn}!se&&z!=="der"&&(se=g.fromCompact(R))}fe=c.fromHex(I)}catch{return!1}if(!se||C&&se.hasHighS())return!1;H&&(N=e.hash(N));let{r:ve,s:Le}=se,Be=k(N),$e=a(Le),kt=s(Be*$e),Yt=s(ve*$e),Ut=c.BASE.multiplyAndAddUnsafe(fe,kt,Yt)?.toAffine();return Ut?s(Ut.x)===ve:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:x,sign:O,verify:B,ProjectivePoint:c,Signature:g,utils:y}}function jS(r){return{hash:r,hmac:(e,...t)=>To(r,e,n2(...t)),randomBytes:ci}}function B8(r,e){let t=n=>L8({...r,...jS(n)});return{...t(e),create:t}}var U8=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),O8=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ZS=BigInt(1),M2=BigInt(2),M8=(r,e)=>(r+e/M2)/e;function JS(r){let e=U8,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=Ue(u,t,e)*u%e,h=Ue(d,t,e)*u%e,f=Ue(h,M2,e)*l%e,p=Ue(f,o,e)*f%e,m=Ue(p,i,e)*p%e,g=Ue(m,a,e)*m%e,y=Ue(g,c,e)*g%e,b=Ue(y,a,e)*m%e,w=Ue(b,t,e)*u%e,x=Ue(w,s,e)*p%e,_=Ue(x,n,e)*l%e,k=Ue(_,M2,e);if(!U2.eql(U2.sqr(k),r))throw new Error("Cannot find square root");return k}var U2=vo(U8,void 0,void 0,{sqrt:JS}),Cr=B8({a:BigInt(0),b:BigInt(7),Fp:U2,n:O8,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=O8,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-ZS*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,s=BigInt("0x100000000000000000000000000000000"),a=M8(i*r,e),c=M8(-n*r,e),l=Te(r-a*t-c*o,e),u=Te(-a*n-c*i,e),d=l>s,h=u>s;if(d&&(l=e-l),h&&(u=e-u),l>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:d,k1:l,k2neg:h,k2:u}}}},Tr),RO=BigInt(0);var DO=Cr.ProjectivePoint;function F2(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function F8(r,e){let t=lt.digest(e instanceof Uint8Array?e:e.subarray());if(F2(t))return t.then(({digest:n})=>Cr.sign(n,r).toDERRawBytes()).catch(n=>{throw new za(String(n))});try{return Cr.sign(t.digest,r).toDERRawBytes()}catch(n){throw new za(String(n))}}function V8(r,e,t){let n=lt.digest(t instanceof Uint8Array?t:t.subarray());if(F2(n))return n.then(({digest:o})=>Cr.verify(e,o,r)).catch(o=>{throw new Wa(String(o))});try{return Cr.verify(e,n.digest,r)}catch(o){throw new Wa(String(o))}}var Ya=class{type="secp256k1";raw;_key;constructor(e){this._key=H8(e),this.raw=$8(this._key)}toMultihash(){return Zt.digest(Lt(this))}toCID(){return j.createV1(114,this.toMultihash())}toString(){return Ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:oe(this.raw,e.raw)}verify(e,t){return V8(this._key,t,e)}},Xa=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=K8(e),this.publicKey=new Ya(t??q8(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:oe(this.raw,e.raw)}sign(e){return F8(this.raw,e)}};function V2(r){return new Xa(r)}function $2(r){return new Ya(r)}async function z8(){let r=eA();return new Xa(r)}function $8(r){return Cr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function K8(r){try{return Cr.getPublicKey(r,!0),r}catch(e){throw new xa(String(e))}}function H8(r){try{return Cr.ProjectivePoint.fromHex(r),r}catch(e){throw new Rn(String(e))}}function q8(r){try{return Cr.getPublicKey(r,!0)}catch(e){throw new xa(String(e))}}function eA(){return Cr.utils.randomPrivateKey()}async function Qu(r,e){if(r==="Ed25519")return B6();if(r==="secp256k1")return z8();if(r==="RSA")return B2(e??2048);throw new Vr}function tt(r){let{Type:e,Data:t}=bn.decode(r),n=t??new Uint8Array;switch(e){case Qe.RSA:return L2(n);case Qe.Ed25519:return S2(n);case Qe.secp256k1:return $2(n);default:throw new Vr}}function Yu(r){let{Type:e,Data:t}=bn.decode(r.digest),n=t??new Uint8Array;switch(e){case Qe.Ed25519:return S2(n);case Qe.secp256k1:return $2(n);default:throw new Vr}}function Lt(r){return bn.encode({Type:Qe[r.type],Data:r.raw})}function W8(r){let e=Oa.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Qe.RSA:return Wu(t);case Qe.Ed25519:return E2(t);case Qe.secp256k1:return V2(t);default:throw new Vr}}function G8(r){return r.byteLength===64?E2(r):r.byteLength===32?V2(r):Wu(r)}function Is(r){return Oa.encode({Type:Qe[r.type],Data:r.raw})}var Q8=Symbol.for("nodejs.util.inspect.custom"),tA=114,ja=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[hl]=!0;toString(){return this.string==null&&(this.string=Ee.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return j.createV1(tA,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return oe(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return oe(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Q8](){return`PeerId(${this.toString()})`}},Za=class extends ja{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ja=class extends ja{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},ec=class extends ja{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},rA=2336,tc=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Zt.digest(M(this.url))}[Q8](){return`PeerId(${this.url})`}[hl]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return j.createV1(rA,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var nA=114,Y8=2336;function Fe(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ie(Ee.decode(`z${r}`));else{if(e==null)throw new P('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ie(e.decode(r))}return ot(t)}function Sn(r){if(r.type==="Ed25519")return new Ja({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new ec({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Za({multihash:r.toCID().multihash,publicKey:r});throw new Vr}function X8(r){return Sn(r.publicKey)}function ot(r){if(iA(r))return new Za({multihash:r});if(oA(r))try{let e=Yu(r);if(e.type==="Ed25519")return new Ja({multihash:r,publicKey:e});if(e.type==="secp256k1")return new ec({multihash:r,publicKey:e})}catch{let t=$(r.digest);return new tc(new URL(t))}throw new co("Supplied PeerID Multihash is invalid")}function An(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==nA&&r.code!==Y8)throw new wl("Supplied PeerID CID is invalid");if(r.code===Y8){let e=$(r.multihash.digest);return new tc(new URL(e))}return ot(r.multihash)}function oA(r){return r.code===Zt.code}function iA(r){return r.code===lt.code}function mi(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function Xu(r){let e=Ie(Ee.decode(`z${r}`));return ot(e)}var pt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return mi(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return mi(this.map.values(),e=>e.key)}values(){return mi(this.map.values(),e=>e.value)}get size(){return this.map.size}};var zt=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return mi(this.set.entries(),e=>{let t=Xu(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Xu(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return mi(this.set.values(),e=>Xu(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};function K2(){return new zt}function j8(r,e,t,n){ii(r);let o=h6({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(po(i),po(s),po(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Wr(e),l=Wr(t),u=new Uint8Array(s),d=To.create(r,c),h=d._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:a,DK:u,PRF:d,PRFSalt:h}}function Z8(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}function J8(r,e,t,n){let{c:o,dkLen:i,DK:s,PRF:a,PRFSalt:c}=j8(r,e,t,n),l,u=new Uint8Array(4),d=ai(u),h=new Uint8Array(a.outputLen);for(let f=1,p=0;p<i;f++,p+=a.outputLen){let m=s.subarray(p,p+a.outputLen);d.setInt32(0,f,!1),(l=c._cloneInto(l)).update(u).digestInto(h),m.set(h.subarray(0,m.length));for(let g=1;g<o;g++){a._cloneInto(l).update(h).digestInto(h);for(let y=0;y<m.length;y++)m[y]^=h[y]}}return Z8(a,c,s,l,h)}async function ju(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=j8(r,e,t,n),u,d=new Uint8Array(4),h=ai(d),f=new Uint8Array(c.outputLen);for(let p=1,m=0;m<i;p++,m+=c.outputLen){let g=a.subarray(m,m+c.outputLen);h.setInt32(0,p,!1),(u=l._cloneInto(u)).update(d).digestInto(f),g.set(f.subarray(0,g.length)),await d6(o-1,s,()=>{c._cloneInto(u).update(f).digestInto(f);for(let y=0;y<g.length;y++)g[y]^=f[y]})}return Z8(c,l,a,u,f)}var rc=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),_o=new Uint32Array(80),H2=class extends mo{constructor(){super(64,20,8,!1),this.A=rc[0]|0,this.B=rc[1]|0,this.C=rc[2]|0,this.D=rc[3]|0,this.E=rc[4]|0}get(){let{A:e,B:t,C:n,D:o,E:i}=this;return[e,t,n,o,i]}set(e,t,n,o,i){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0}process(e,t){for(let c=0;c<16;c++,t+=4)_o[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)_o[c]=ql(_o[c-3]^_o[c-8]^_o[c-14]^_o[c-16],1);let{A:n,B:o,C:i,D:s,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=zl(o,i,s),u=1518500249):c<40?(l=o^i^s,u=1859775393):c<60?(l=Wl(o,i,s),u=2400959708):(l=o^i^s,u=3395469782);let d=ql(n,5)+l+a+u+_o[c]|0;a=s,s=i,i=ql(o,30),o=n,n=d}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,o,i,s,a)}roundClean(){_o.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}},eg=ms(()=>new H2);var tg={sha1:eg,"sha2-256":Tr,"sha2-512":wo};function nc(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(tg).join(" / ");throw new P(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let i=tg[o],s=J8(i,r,e,{c:t,dkLen:n});return nt.encode(s).substring(1)}var q2=64,jr=class{fp;h;seed;constructor(e,t,n,o=2){if(o>q2)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=ae(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?oe(this.fp,e.fp):!1}};function gi(r,e){return Math.floor(Math.random()*(e-r))+r}var yi=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof jr))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof jr))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof jr))throw new TypeError("Invalid Fingerprint");let t=gi(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof jr))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var z2={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},ig={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},sg=new globalThis.TextEncoder;function sA(r,e){let t=z2[e],n=ig[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function aA(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=z2[e],o=ig[e],i=r;for(;i.length>0;){let s=sg.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function W2(r,{size:e=32,utf8Buffer:t}={}){if(!z2[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return aA(r,e,t);r=sg.encode(r)}return sA(r,e)}var cA=ur(og(),1);var ic={hash:r=>Number(W2(r,{size:32})),hashV:(r,e)=>lA(ic.hash(r,e))};function lA(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),M(e,"base16")}var uA=500,sc=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??ic,this.seed=e.seed??gi(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=M(e));let t=new jr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new yi(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new yi(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[gi(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new yi(this.bucketSize));for(let a=0;a<uA;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new yi(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=M(e));let t=new jr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=M(e));let t=new jr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},dA={1:.5,2:.84,4:.95,8:.98};function fA(r=.001){return r>.002?2:r>1e-5?4:8}function ag(r,e=.001){let t=fA(e),n=dA[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),q2);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var Ju=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??ic,this.seed=e.seed??gi(0,Math.pow(2,10)),this.filterSeries=[new sc({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=M(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new sc({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function rr(r,e=.001,t){return new Ju({...ag(r,e),...t??{}})}var ed=class{filter;constructor(e,t){this.filter=rr(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function G2(r,e=.001){return new ed(r,e)}var Q2=class extends pt{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 ac(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Q2({name:e,metrics:t}):n=new pt,n}var Qn=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=nt.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=nt.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=nt.encode(e.multihash.bytes);this.blocks.set(n,t)}};function hA(r){let e=new Uint8Array(r.reduce((n,o)=>n+me(o),0)),t=0;for(let n of r)e=Ke(n,e,t),t+=me(n);return e}var cg=hA;function Y2(r){return cg([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var td=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 Qn,n=new Set;for(let[o,i]of this.wants.entries())try{let s=await this.blockstore.get(i.cid,e);i.wantType===Je.WantHave?s.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:s,prefix:Y2(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Ar.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:s,prefix:Y2(i.cid)}))}catch(s){if(s.name!=="NotFoundError")throw s;if(this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDontHave===!0)continue;i.sentDontHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Ar.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,i)=>o+i.data.byteLength,0));for(let o of n)this.wants.delete(o)}}};var rd=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=ac({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 td({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,i)=>o+i.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let o of t.wantlist.entries){let i=j.decode(o.cid),s=$(i.multihash.bytes,"base64");o.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,i),n.wants.delete(s)):(o.wantType===Je.WantHave?this.log("peer %p wanted block presence for %c",e,i):this.log("peer %p wanted block for %c",e,i),n.wants.set(s,{cid:i,priority:o.priority,wantType:o.wantType??Je.WantBlock,sendDontHave:o.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=$(e.multihash.bytes,"base64"),o=[];for(let i of this.ledgerMap.values())i.wants.has(n)&&o.push(i);await Promise.all(o.map(async i=>i.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};function pA(r,e){try{if(typeof r=="string"&&r.length>0)return mA(r);if(typeof r=="number"&&isFinite(r))return e?.long?yA(r):gA(r);throw new Error("Value is not a string or number.")}catch(t){let n=wA(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function mA(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var od=pA;function gA(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function yA(r){let e=Math.abs(r);return e>=864e5?nd(r,e,864e5,"day"):e>=36e5?nd(r,e,36e5,"hour"):e>=6e4?nd(r,e,6e4,"minute"):e>=1e3?nd(r,e,1e3,"second"):`${r} ms`}function nd(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function wA(r){return typeof r=="object"&&r!==null&&"message"in r}function X2(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=s,t.humanize=od,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let h=0;h<u.length;h++)d=(d<<5)-d+u.charCodeAt(h),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u){let d,h=null,f,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(d||b);y.diff=w,y.prev=d,y.curr=b,d=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(k,E)=>{if(k==="%%")return"%";x++;let S=t.formatters[E];if(typeof S=="function"){let T=g[x];k=S.call(y,T),g.splice(x,1),x--}return k}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(f!==t.namespaces&&(f=t.namespaces,p=t.enabled(u)),p),set:g=>{h=g}}),typeof t.init=="function"&&t.init(m),m}function n(u,d){let h=t(this.namespace+(typeof d>"u"?":":d)+u);return h.log=this.log,h}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,h=(typeof u=="string"?u:"").split(/[\s,]+/),f=h.length;for(d=0;d<f;d++)h[d]&&(u=h[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function i(){let u=[...t.names.map(a),...t.skips.map(a).map(d=>"-"+d)].join(",");return t.enable(""),u}function s(u){if(u[u.length-1]==="*")return!0;let d,h;for(d=0,h=t.skips.length;d<h;d++)if(t.skips[d].test(u))return!1;for(d=0,h=t.names.length;d<h;d++)if(t.names[d].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var id=IA(),bA=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function xA(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function vA(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+od(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var EA=console.debug??console.log??(()=>{});function SA(r){try{r?id?.setItem("debug",r):id?.removeItem("debug")}catch{}}function AA(){let r;try{r=id?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function IA(){try{return localStorage}catch{}}function TA(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var lg=X2({formatArgs:vA,save:SA,load:AA,useColors:xA,setupFormatters:TA,colors:bA,storage:id,log:EA});var nr=lg;nr.formatters.b=r=>r==null?"undefined":Ee.baseEncode(r);nr.formatters.t=r=>r==null?"undefined":ct.baseEncode(r);nr.formatters.m=r=>r==null?"undefined":nt.baseEncode(r);nr.formatters.p=r=>r==null?"undefined":r.toString();nr.formatters.c=r=>r==null?"undefined":r.toString();nr.formatters.k=r=>r==null?"undefined":r.toString();nr.formatters.a=r=>r==null?"undefined":r.toString();nr.formatters.e=r=>r==null?"undefined":ug(r.stack)??ug(r.message)??r.toString();function _A(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 ko(){return{forComponent(r){return pr(r)}}}function pr(r){let e=_A(`${r}:trace`);return nr.enabled(`${r}:trace`)&&nr.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=nr(`${r}:trace`)),Object.assign(nr(r),{error:nr(`${r}:error`),trace:e})}function ug(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Z2=ur(fg(),1);var lc=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},J2=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},hg=r=>globalThis.DOMException===void 0?new J2(r):new DOMException(r),pg=r=>{let e=r.reason===void 0?hg("This operation was aborted."):r.reason;return e instanceof Error?e:hg(e)};function Zr(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a,l=new Promise((u,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:f}=e;f.aborted&&d(pg(f)),a=()=>{d(pg(f))},f.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,d);return}let h=new lc;s=i.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(f){d(f)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t),(async()=>{try{u(await r)}catch(f){d(f)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},l}function ep(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var uc=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=ep(this.#e,n,(i,s)=>s.priority-i.priority);this.#e.splice(o,0,n)}setPriority(e,t){let n=this.#e.findIndex(i=>i.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}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 In=class extends Z2.default{#e;#t;#r=0;#o;#a;#l=0;#i;#u;#n;#m;#s=0;#d;#c;#g;#b=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:uc,...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#x(){return this.#t||this.#r<this.#o}get#v(){return this.#s<this.#d}#E(){this.#s--,this.#f(),this.emit("next")}#S(){this.#w(),this.#y(),this.#u=void 0}get#A(){let e=Date.now();if(this.#i===void 0){let t=this.#l-e;if(t<0)this.#r=this.#e?this.#s:0;else return this.#u===void 0&&(this.#u=setTimeout(()=>{this.#S()},t)),!0}return!1}#f(){if(this.#n.size===0)return this.#i&&clearInterval(this.#i),this.#i=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#c){let e=!this.#A;if(this.#x&&this.#v){let t=this.#n.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#i!==void 0||(this.#i=setInterval(()=>{this.#w()},this.#a),this.#l=Date.now()+this.#a)}#w(){this.#r===0&&this.#s===0&&this.#i&&(clearInterval(this.#i),this.#i=void 0),this.#r=this.#e?this.#s: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#I(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#n.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#b++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#s++,this.#r++;try{t.signal?.throwIfAborted();let i=e({signal:t.signal});t.timeout&&(i=Zr(Promise.resolve(i),{milliseconds:t.timeout})),t.signal&&(i=Promise.race([i,this.#I(t.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof lc&&!t.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#E()}},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.#s===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.#s}get isPaused(){return this.#c}};function ad(r){let e=[mr.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var tp=60;function cd(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:mr[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:mr[e.type],TTL:e.TTL??e.ttl??tp,data:e.data instanceof Uint8Array?$(e.data):e.data}))}}var PA=4;function rp(r,e={}){let t=new In({concurrency:e.queryConcurrency??PA});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),ad(o.types).forEach(a=>{i.append("type",mr[a])}),o.onProgress?.(new G("dns:query",{detail:n}));let s=await t.add(async()=>{let a=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=cd(await a.json());return o.onProgress?.(new G("dns:response",{detail:c})),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function mg(){return[rp("https://cloudflare-dns.com/dns-query"),rp("https://dns.google/resolve")]}var wg=ur(yg(),1);var np=class{lru;constructor(e){this.lru=(0,wg.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return cd({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:mr[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??tp)*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 bg(r){return new np(r)}var RA=1e3,ld=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=bg(e.cacheSize??RA),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["."]=mg())}async query(e,t={}){let n=ad(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new G("dns:cache",{detail:o})),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new G("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var mr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(mr||(mr={}));function ud(r={}){return new ld(r)}var DA=["string","number","bigint","symbol"],NA=["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 xg(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(DA.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(LA(r))return"Buffer";let t=BA(r);return t||"Object"}function LA(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function BA(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(NA.includes(e))return e}var v=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}};v.uint=new v(0,"uint",!0);v.negint=new v(1,"negint",!0);v.bytes=new v(2,"bytes",!0);v.string=new v(3,"string",!0);v.array=new v(4,"array",!1);v.map=new v(5,"map",!1);v.tag=new v(6,"tag",!1);v.float=new v(7,"float",!0);v.false=new v(7,"false",!0);v.true=new v(7,"true",!0);v.null=new v(7,"null",!0);v.undefined=new v(7,"undefined",!0);v.break=new v(7,"break",!0);var U=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 Ts=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",OA=new TextDecoder,MA=new TextEncoder;function dd(r){return Ts&&globalThis.Buffer.isBuffer(r)}function dc(r){return r instanceof Uint8Array?dd(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Ag=Ts?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):Eg(r,e,t):(r,e,t)=>t-e>64?OA.decode(r.subarray(e,t)):Eg(r,e,t),fd=Ts?r=>r.length>64?globalThis.Buffer.from(r):vg(r):r=>r.length>64?MA.encode(r):vg(r),Tn=r=>Uint8Array.from(r),_s=Ts?(r,e,t)=>dd(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Ig=Ts?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),dc(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},Tg=Ts?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function _g(r,e){if(dd(r)&&dd(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 vg(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 Eg(r,e,t){let n=[];for(;e<t;){let o=r[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=t){let a,c,l,u;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[e+1],(a&192)===128&&(u=(o&31)<<6|a&63,u>127&&(i=u));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(u=(o&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(i=u))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return op(n)}var Sg=4096;function op(r){let e=r.length;if(e<=Sg)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Sg));return t}var UA=256,fc=class{constructor(e=UA){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=Tg(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=_s(n,0,this.cursor)}else t=Ig(this.chunks,this.cursor);return e&&this.reset(),t}};var Z="CBOR decode error:",Yn="CBOR encode error:",hc=[];hc[23]=1;hc[24]=2;hc[25]=3;hc[26]=5;hc[27]=9;function Xn(r,e,t){if(r.length-e<t)throw new Error(`${Z} not enough data for type`)}var mt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function gr(r,e,t){Xn(r,e,1);let n=r[e];if(t.strict===!0&&n<mt[0])throw new Error(`${Z} integer encoded in more bytes than necessary (strict decode)`);return n}function yr(r,e,t){Xn(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<mt[1])throw new Error(`${Z} integer encoded in more bytes than necessary (strict decode)`);return n}function wr(r,e,t){Xn(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<mt[2])throw new Error(`${Z} integer encoded in more bytes than necessary (strict decode)`);return n}function br(r,e,t){Xn(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],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<mt[3])throw new Error(`${Z} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${Z} integers outside of the safe integer range are not supported`)}function kg(r,e,t,n){return new U(v.uint,gr(r,e+1,n),2)}function Cg(r,e,t,n){return new U(v.uint,yr(r,e+1,n),3)}function Pg(r,e,t,n){return new U(v.uint,wr(r,e+1,n),5)}function Rg(r,e,t,n){return new U(v.uint,br(r,e+1,n),9)}function Pr(r,e){return vt(r,0,e.value)}function vt(r,e,t){if(t<mt[0]){let n=Number(t);r.push([e|n])}else if(t<mt[1]){let n=Number(t);r.push([e|24,n])}else if(t<mt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<mt[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<mt[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${Z} encountered BigInt larger than allowable range`)}}Pr.encodedSize=function(e){return vt.encodedSize(e.value)};vt.encodedSize=function(e){return e<mt[0]?1:e<mt[1]?2:e<mt[2]?3:e<mt[3]?5:9};Pr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Dg(r,e,t,n){return new U(v.negint,-1-gr(r,e+1,n),2)}function Ng(r,e,t,n){return new U(v.negint,-1-yr(r,e+1,n),3)}function Lg(r,e,t,n){return new U(v.negint,-1-wr(r,e+1,n),5)}var ip=BigInt(-1),Bg=BigInt(1);function Og(r,e,t,n){let o=br(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new U(v.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${Z} integers outside of the safe integer range are not supported`);return new U(v.negint,ip-BigInt(o),9)}function hd(r,e){let t=e.value,n=typeof t=="bigint"?t*ip-Bg:t*-1-1;vt(r,e.type.majorEncoded,n)}hd.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*ip-Bg:t*-1-1;return n<mt[0]?1:n<mt[1]?2:n<mt[2]?3:n<mt[3]?5:9};hd.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function pc(r,e,t,n){Xn(r,e,t+n);let o=_s(r,e+t,e+t+n);return new U(v.bytes,o,t+n)}function Mg(r,e,t,n){return pc(r,e,1,t)}function Ug(r,e,t,n){return pc(r,e,2,gr(r,e+1,n))}function Fg(r,e,t,n){return pc(r,e,3,yr(r,e+1,n))}function Vg(r,e,t,n){return pc(r,e,5,wr(r,e+1,n))}function $g(r,e,t,n){let o=br(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Z} 64-bit integer bytes lengths not supported`);return pc(r,e,9,o)}function pd(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===v.string?fd(r.value):r.value),r.encodedBytes}function ks(r,e){let t=pd(e);vt(r,e.type.majorEncoded,t.length),r.push(t)}ks.encodedSize=function(e){let t=pd(e);return vt.encodedSize(t.length)+t.length};ks.compareTokens=function(e,t){return VA(pd(e),pd(t))};function VA(r,e){return r.length<e.length?-1:r.length>e.length?1:_g(r,e)}function mc(r,e,t,n,o){let i=t+n;Xn(r,e,i);let s=new U(v.string,Ag(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=_s(r,e+t,e+i)),s}function Kg(r,e,t,n){return mc(r,e,1,t,n)}function Hg(r,e,t,n){return mc(r,e,2,gr(r,e+1,n),n)}function qg(r,e,t,n){return mc(r,e,3,yr(r,e+1,n),n)}function zg(r,e,t,n){return mc(r,e,5,wr(r,e+1,n),n)}function Wg(r,e,t,n){let o=br(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Z} 64-bit integer string lengths not supported`);return mc(r,e,9,o,n)}var Gg=ks;function Cs(r,e,t,n){return new U(v.array,n,t)}function Qg(r,e,t,n){return Cs(r,e,1,t)}function Yg(r,e,t,n){return Cs(r,e,2,gr(r,e+1,n))}function Xg(r,e,t,n){return Cs(r,e,3,yr(r,e+1,n))}function jg(r,e,t,n){return Cs(r,e,5,wr(r,e+1,n))}function Zg(r,e,t,n){let o=br(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Z} 64-bit integer array lengths not supported`);return Cs(r,e,9,o)}function Jg(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Z} indefinite length items not allowed`);return Cs(r,e,1,1/0)}function md(r,e){vt(r,v.array.majorEncoded,e.value)}md.compareTokens=Pr.compareTokens;md.encodedSize=function(e){return vt.encodedSize(e.value)};function Ps(r,e,t,n){return new U(v.map,n,t)}function e5(r,e,t,n){return Ps(r,e,1,t)}function t5(r,e,t,n){return Ps(r,e,2,gr(r,e+1,n))}function r5(r,e,t,n){return Ps(r,e,3,yr(r,e+1,n))}function n5(r,e,t,n){return Ps(r,e,5,wr(r,e+1,n))}function o5(r,e,t,n){let o=br(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Z} 64-bit integer map lengths not supported`);return Ps(r,e,9,o)}function i5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Z} indefinite length items not allowed`);return Ps(r,e,1,1/0)}function gd(r,e){vt(r,v.map.majorEncoded,e.value)}gd.compareTokens=Pr.compareTokens;gd.encodedSize=function(e){return vt.encodedSize(e.value)};function s5(r,e,t,n){return new U(v.tag,t,1)}function a5(r,e,t,n){return new U(v.tag,gr(r,e+1,n),2)}function c5(r,e,t,n){return new U(v.tag,yr(r,e+1,n),3)}function l5(r,e,t,n){return new U(v.tag,wr(r,e+1,n),5)}function u5(r,e,t,n){return new U(v.tag,br(r,e+1,n),9)}function yd(r,e){vt(r,v.tag.majorEncoded,e.value)}yd.compareTokens=Pr.compareTokens;yd.encodedSize=function(e){return vt.encodedSize(e.value)};var WA=20,GA=21,QA=22,YA=23;function d5(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Z} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new U(v.null,null,1):new U(v.undefined,void 0,1)}function f5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Z} indefinite length items not allowed`);return new U(v.break,void 0,1)}function sp(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Z} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Z} Infinity values are not supported`)}return new U(v.float,r,e)}function h5(r,e,t,n){return sp(ap(r,e+1),3,n)}function p5(r,e,t,n){return sp(cp(r,e+1),5,n)}function m5(r,e,t,n){return sp(b5(r,e+1),9,n)}function wd(r,e,t){let n=e.value;if(n===!1)r.push([v.float.majorEncoded|WA]);else if(n===!0)r.push([v.float.majorEncoded|GA]);else if(n===null)r.push([v.float.majorEncoded|QA]);else if(n===void 0)r.push([v.float.majorEncoded|YA]);else{let o,i=!1;(!t||t.float64!==!0)&&(y5(n),o=ap(Jr,1),n===o||Number.isNaN(n)?(Jr[0]=249,r.push(Jr.slice(0,3)),i=!0):(w5(n),o=cp(Jr,1),n===o&&(Jr[0]=250,r.push(Jr.slice(0,5)),i=!0))),i||(XA(n),o=b5(Jr,1),Jr[0]=251,r.push(Jr.slice(0,9)))}}wd.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=ap(Jr,1);if(n===o||Number.isNaN(n))return 3;if(w5(n),o=cp(Jr,1),n===o)return 5}return 9};var g5=new ArrayBuffer(9),Rr=new DataView(g5,1),Jr=new Uint8Array(g5,0);function y5(r){if(r===1/0)Rr.setUint16(0,31744,!1);else if(r===-1/0)Rr.setUint16(0,64512,!1);else if(Number.isNaN(r))Rr.setUint16(0,32256,!1);else{Rr.setFloat32(0,r);let e=Rr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Rr.setUint16(0,31744,!1);else if(t===0)Rr.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Rr.setUint16(0,0):o<-14?Rr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Rr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function ap(r,e){if(r.length-e<2)throw new Error(`${Z} 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,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function w5(r){Rr.setFloat32(0,r,!1)}function cp(r,e){if(r.length-e<4)throw new Error(`${Z} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function XA(r){Rr.setFloat64(0,r,!1)}function b5(r,e){if(r.length-e<8)throw new Error(`${Z} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}wd.compareTokens=Pr.compareTokens;function Se(r,e,t){throw new Error(`${Z} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function bd(r){return()=>{throw new Error(`${Z} ${r}`)}}var K=[];for(let r=0;r<=23;r++)K[r]=Se;K[24]=kg;K[25]=Cg;K[26]=Pg;K[27]=Rg;K[28]=Se;K[29]=Se;K[30]=Se;K[31]=Se;for(let r=32;r<=55;r++)K[r]=Se;K[56]=Dg;K[57]=Ng;K[58]=Lg;K[59]=Og;K[60]=Se;K[61]=Se;K[62]=Se;K[63]=Se;for(let r=64;r<=87;r++)K[r]=Mg;K[88]=Ug;K[89]=Fg;K[90]=Vg;K[91]=$g;K[92]=Se;K[93]=Se;K[94]=Se;K[95]=bd("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)K[r]=Kg;K[120]=Hg;K[121]=qg;K[122]=zg;K[123]=Wg;K[124]=Se;K[125]=Se;K[126]=Se;K[127]=bd("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)K[r]=Qg;K[152]=Yg;K[153]=Xg;K[154]=jg;K[155]=Zg;K[156]=Se;K[157]=Se;K[158]=Se;K[159]=Jg;for(let r=160;r<=183;r++)K[r]=e5;K[184]=t5;K[185]=r5;K[186]=n5;K[187]=o5;K[188]=Se;K[189]=Se;K[190]=Se;K[191]=i5;for(let r=192;r<=215;r++)K[r]=s5;K[216]=a5;K[217]=c5;K[218]=l5;K[219]=u5;K[220]=Se;K[221]=Se;K[222]=Se;K[223]=Se;for(let r=224;r<=243;r++)K[r]=bd("simple values are not supported");K[244]=Se;K[245]=Se;K[246]=Se;K[247]=d5;K[248]=bd("simple values are not supported");K[249]=h5;K[250]=p5;K[251]=m5;K[252]=Se;K[253]=Se;K[254]=Se;K[255]=f5;var en=[];for(let r=0;r<24;r++)en[r]=new U(v.uint,r,1);for(let r=-1;r>=-24;r--)en[31-r]=new U(v.negint,r,1);en[64]=new U(v.bytes,new Uint8Array(0),1);en[96]=new U(v.string,"",1);en[128]=new U(v.array,0,1);en[160]=new U(v.map,0,1);en[244]=new U(v.false,!1,1);en[245]=new U(v.true,!0,1);en[246]=new U(v.null,null,1);function x5(r){switch(r.type){case v.false:return Tn([244]);case v.true:return Tn([245]);case v.null:return Tn([246]);case v.bytes:return r.value.length?void 0:Tn([64]);case v.string:return r.value===""?Tn([96]):void 0;case v.array:return r.value===0?Tn([128]):void 0;case v.map:return r.value===0?Tn([160]):void 0;case v.uint:return r.value<24?Tn([Number(r.value)]):void 0;case v.negint:if(r.value>=-24)return Tn([31-Number(r.value)])}}var ZA={float64:!1,mapSorter:tI,quickEncodeToken:x5};function JA(){let r=[];return r[v.uint.major]=Pr,r[v.negint.major]=hd,r[v.bytes.major]=ks,r[v.string.major]=Gg,r[v.array.major]=md,r[v.map.major]=gd,r[v.tag.major]=yd,r[v.float.major]=wd,r}var v5=JA(),lp=new fc,vd=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(`${Yn} object contains circular references`);return new r(t,e)}},Co={null:new U(v.null,null),undefined:new U(v.undefined,void 0),true:new U(v.true,!0),false:new U(v.false,!1),emptyArray:new U(v.array,0),emptyMap:new U(v.map,0)},Po={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new U(v.float,r):r>=0?new U(v.uint,r):new U(v.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new U(v.uint,r):new U(v.negint,r)},Uint8Array(r,e,t,n){return new U(v.bytes,r)},string(r,e,t,n){return new U(v.string,r)},boolean(r,e,t,n){return r?Co.true:Co.false},null(r,e,t,n){return Co.null},undefined(r,e,t,n){return Co.undefined},ArrayBuffer(r,e,t,n){return new U(v.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new U(v.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Co.emptyArray,new U(v.break)]:Co.emptyArray;n=vd.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=xd(s,t,n);return t.addBreakTokens?[new U(v.array,r.length),o,new U(v.break)]:[new U(v.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return t.addBreakTokens===!0?[Co.emptyMap,new U(v.break)]:Co.emptyMap;n=vd.createCheck(n,r);let a=[],c=0;for(let l of i)a[c++]=[xd(l,t,n),xd(o?r.get(l):r[l],t,n)];return eI(a,t),t.addBreakTokens?[new U(v.map,s),a,new U(v.break)]:[new U(v.map,s),a]}};Po.Map=Po.Object;Po.Buffer=Po.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Po[`${r}Array`]=Po.DataView;function xd(r,e={},t){let n=xg(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Po[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=Po[n];if(!i)throw new Error(`${Yn} unsupported type: ${n}`);return i(r,n,e,t)}function eI(r,e){e.mapSorter&&r.sort(e.mapSorter)}function tI(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,i=v5[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function E5(r,e,t,n){if(Array.isArray(e))for(let o of e)E5(r,o,t,n);else t[e.type.major](r,e,n)}function up(r,e,t){let n=xd(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,t),a=new fc(s);if(i(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return dc(a.chunks[0])}}return lp.reset(),E5(lp,n,e,t),lp.toBytes(!0)}function Ro(r,e){return e=Object.assign({},ZA,e),up(r,v5,e)}var rI={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Ed=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=en[e];if(t===void 0){let n=K[e];if(!n)throw new Error(`${Z} 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}},gc=Symbol.for("DONE"),Sd=Symbol.for("BREAK");function nI(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=Rs(e,t);if(i===Sd){if(r.value===1/0)break;throw new Error(`${Z} got unexpected break to lengthed array`)}if(i===gc)throw new Error(`${Z} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function oI(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=Rs(e,t);if(a===Sd){if(r.value===1/0)break;throw new Error(`${Z} got unexpected break to lengthed map`)}if(a===gc)throw new Error(`${Z} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${Z} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${Z} found repeat map key "${a}"`);let c=Rs(e,t);if(c===gc)throw new Error(`${Z} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(a,c):o[a]=c}return n?i:o}function Rs(r,e){if(r.done())return gc;let t=r.next();if(t.type===v.break)return Sd;if(t.type.terminal)return t.value;if(t.type===v.array)return nI(t,r,e);if(t.type===v.map)return oI(t,r,e);if(t.type===v.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Rs(r,e);return e.tags[t.value](n)}throw new Error(`${Z} tag not supported (${t.value})`)}throw new Error("unsupported")}function dp(r,e){if(!(r instanceof Uint8Array))throw new Error(`${Z} data to decode must be a Uint8Array`);e=Object.assign({},rI,e);let t=e.tokenizer||new Ed(r,e),n=Rs(t,e);if(n===gc)throw new Error(`${Z} did not find any content to decode`);if(n===Sd)throw new Error(`${Z} got unexpected break`);return[n,r.subarray(t.pos())]}function xr(r,e){let[t,n]=dp(r,e);if(n.length>0)throw new Error(`${Z} too many terminals, data makes no sense`);return t}var jn="/",S5=new TextEncoder().encode(jn),Ad=S5[0],Ne=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]!==Ad)throw new Error("Invalid key")}toString(e="utf8"){return $(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(jn))}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]!==Ad){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ad,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ad;)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 i=t[o],s=n[o];if(i<s)return!0;if(i>s)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(jn).slice(1)}type(){return iI(this.baseNamespace())}name(){return sI(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(jn)||(e+=jn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(jn):new r(e.slice(0,-1).join(jn))}child(e){return this.toString()===jn?e:e.toString()===jn?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(),...aI(e.map(t=>t.namespaces()))])}};function iI(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function sI(r){let e=r.split(":");return e[e.length-1]}function aI(r){return[].concat(...r)}function Id({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*cI(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=j.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*hp(n,o))}else{let t=j.asCID(e);t!=null?yield[r.join("/"),t]:yield*hp(e,r)}}function*hp(r,e){if(r==null||r instanceof Uint8Array)return;let t=j.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*cI(i,o)}}function*lI(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&j.asCID(n)==null&&(yield*pp(n,o))}else yield*pp(e,r)}function*pp(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let o=[...e,t];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&j.asCID(n)==null&&(yield*lI(o,n))}}function uI(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=j.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var mp=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:Id(),bytes:Id(),value:Id(),asBlock:Id()})}links(){return hp(this.value,[])}tree(){return pp(this.value,[])}get(e="/"){return uI(this.value,e.split("/").filter(Boolean))}};function A5({bytes:r,cid:e,value:t,codec:n}){let o=t!==void 0?t:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new mp({cid:e,bytes:r,value:o})}var _5="/pin/",I5="/pinned-block/",gp=yn,T5=1;function Td(r){return r.version===0&&(r=r.toV1()),new Ne(`${_5}${r.toString(gp)}`)}var _d=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=Td(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 i=new Vt({concurrency:T5});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>oe(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Ro(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await this.blockstore.get(e,n),s=A5({bytes:i,cid:e,codec:o});yield e;for await(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new Ne(`${I5}${gp.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=xr(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Ro(i),n),n.onProgress?.(new G("helia:pin:add",e))}}async*rm(e,t={}){let n=Td(e),o=await this.datastore.get(n,t),i=xr(o);await this.datastore.delete(n,t);let s=new Vt({concurrency:T5});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>oe(l,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:_5+(e.cid!=null?`${e.cid.toString(yn)}`:"")},e)){let o=j.parse(t.toString().substring(5),yn),i=xr(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new Ne(`${I5}${gp.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=Td(e),o=await this.datastore.get(n,t);return xr(o)}async setMetadata(e,t,n){let o=Td(e),i=await this.datastore.get(o,n),s=xr(i);s.metadata=t??{},await this.datastore.put(o,Ro(s),n)}};var yp=1,wp=5;var yc=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Do=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},wc=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},bc=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var dI=5,kd=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??dI,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await yt(...this.routers)}async stop(){await Ct(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Do("No content routers available");let n=new wt({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of Kt(n.toGenerator(),...bi(this.routers,"findProviders").map(i=>i.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,t);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer %p",o.id,i),null}},{peerId:o.id,signal:t.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer %p",o.id,i)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new Do("No content routers available");await Promise.all(bi(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(bi(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(bi(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(bi(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new Do("No peer routers available");let n=this,o=Kt(...bi(this.routers,"findPeer").map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i;throw new Oe("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Do("No peer routers available");for await(let n of Kt(...bi(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function bi(r,e){return r.filter(t=>t[e]!=null)}var No={},Ds=r=>{r.addEventListener("message",e=>{Ds.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Ds.dispatchEvent("message",r,e)})};Ds.addEventListener=(r,e)=>{No[r]==null&&(No[r]=[]),No[r].push(e)};Ds.removeEventListener=(r,e)=>{No[r]!=null&&(No[r]=No[r].filter(t=>t===e))};Ds.dispatchEvent=function(r,e,t){No[r]!=null&&No[r].forEach(n=>n(e,t))};var bp=Ds;var xp="lock:worker:request-read",vp="lock:worker:release-read",Ep="lock:master:grant-read",Sp="lock:worker:request-write",Ap="lock:worker:release-write",Ip="lock:master:grant-write";var k5=(r=21)=>Math.random().toString().substring(2);var C5=(r,e,t,n,o)=>(i,s)=>{if(s.data.type!==t)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{i.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=u=>{if(u?.data==null)return;let d={type:u.data.type,name:u.data.name,identifier:u.data.identifier};d.type===n&&d.identifier===a.identifier&&(i.removeEventListener("message",l),c())};i.addEventListener("message",l)})}}}))},P5=(r,e,t,n)=>async()=>{let o=k5();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(i=>{let s=a=>{if(a?.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",s),i(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",s)})},fI={singleProcess:!1},R5=r=>{if(r=Object.assign({},fI,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return bp.addEventListener("message",C5(t,"requestReadLock",xp,vp,Ep)),bp.addEventListener("message",C5(t,"requestWriteLock",Sp,Ap,Ip)),t}return{isWorker:!0,readLock:t=>P5(t,xp,Ep,vp),writeLock:t=>P5(t,Sp,Ip,Ap)}};var xi={},Lo;async function Tp(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>Zr((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var hI=(r,e)=>{if(Lo.isWorker===!0)return{readLock:Lo.readLock(r,e),writeLock:Lo.writeLock(r,e)};let t=new In({concurrency:1}),n;return{async readLock(){if(n!=null)return Tp(n,e);n=new In({concurrency:e.concurrency,autoStart:!1});let o=n,i=Tp(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,Tp(t,e)}}},pI={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function vi(r){let e=Object.assign({},pI,r);return Lo==null&&(Lo=R5(e),Lo.isWorker!==!0&&(Lo.addEventListener("requestReadLock",t=>{xi[t.data.name]!=null&&xi[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),Lo.addEventListener("requestWriteLock",async t=>{xi[t.data.name]!=null&&xi[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),xi[e.name]==null&&(xi[e.name]=hI(e.name,e)),xi[e.name]}var Cd=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=vi({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await yt(this.child),this.started=!0}async stop(){await Ct(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 i of e){if(await o.pins.isPinned(i))throw new Error("CID was pinned");yield i}}(),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 _p=new Ne("/version"),D5=1;async function N5(r){if(!await r.has(_p)){await r.put(_p,M(`${D5}`));return}let e=await r.get(_p),t=$(e);if(parseInt(t,10)!==D5)throw new Error("Unknown datastore version, a datastore migration may be required")}var Pp={};Ye(Pp,{code:()=>Cp,decode:()=>SI,decodeOptions:()=>xI,encode:()=>EI,encodeOptions:()=>wI,name:()=>vI,toByteView:()=>B5});var L5=42;function B5(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function mI(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=j.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new U(v.tag,L5),new U(v.bytes,t)]}function gI(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function yI(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 kp={float64:!0,typeEncoders:{Object:mI,undefined:gI,number:yI}},wI={...kp,typeEncoders:{...kp.typeEncoders}};function bI(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return j.decode(r.subarray(1))}var Pd={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Pd.tags[L5]=bI;var xI={...Pd,tags:Pd.tags.slice()},vI="dag-cbor",Cp=113,EI=r=>Ro(r,kp),SI=r=>xr(B5(r),Pd);var Mp={};Ye(Mp,{code:()=>Op,decode:()=>M5,encode:()=>O5,format:()=>LI,name:()=>NI,parse:()=>OI,stringify:()=>LI});var Rp=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===v.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===v.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[v.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[v.negint.major](e,t){this[v.uint.major](e,t)}[v.bytes.major](e,t){throw new Error(`${Yn} unsupported type: Uint8Array`)}[v.string.major](e,t){this.prefix(e);let n=fd(JSON.stringify(t.value));e.push(n.length>32?dc(n):n)}[v.array.major](e,t){this.prefix(e),this.inRecursive.push({type:v.array,elements:0}),e.push([91])}[v.map.major](e,t){this.prefix(e),this.inRecursive.push({type:v.map,elements:0}),e.push([123])}[v.tag.major](e,t){}[v.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===v.array)e.push([93]);else if(s.type===v.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(`${Yn} 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=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function AI(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Yn} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==v.string||n.type!==v.string)throw new Error(`${Yn} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Yn} unexpected duplicate map keys, this is not supported`)}var II={addBreakTokens:!0,mapSorter:AI};function Dp(r,e){return e=Object.assign({},II,e),up(r,new Rp,e)}var Ns=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(`${Z} 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(`${Z} 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 U(v.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(`${Z} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${Z} 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 i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new U(v.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new U(s>=0?v.uint:v.negint,s,this._pos-e):new U(s>=0?v.uint:v.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${Z} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new U(v.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${Z} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){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(`${Z} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${Z} unexpected unicode sequence at position ${this._pos}`);let c,l,u,d;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(d=(i&31)<<6|c&63,d>127&&(s=d));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(d=(i&15)<<12|(c&63)<<6|l&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(d=(i&15)<<18|(c&63)<<12|(l&63)<<6|u&63,d>65535&&d<1114112&&(s=d))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${Z} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);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(`${Z} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new U(v.string,op(t),this._pos-e);default:if(i<32)throw new Error(`${Z} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${Z} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new U(v.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new U(v.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new U(v.null,null,4);case 102:return this.expect([102,97,108,115,101]),new U(v.false,!1,5);case 116:return this.expect([116,114,117,101]),new U(v.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(`${Z} 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 U(v.break,void 0,1);if(this.ch()!==44)throw new Error(`${Z} 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 U(v.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 U(v.break,void 0,1);if(this.ch()!==44)throw new Error(`${Z} 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 U(v.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${Z} 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(`${Z} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Np(r,e){return e=Object.assign({tokenizer:new Ns(r,e)},e),xr(r,e)}function _I(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function kI(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=j.asCID(r);if(!e)return null;let t=e.toString();return[new U(v.map,1/0,1),new U(v.string,"/",1),new U(v.string,t,t.length),new U(v.break,void 0,1)]}function Rd(r){let e=nt.encode(r).slice(1);return[new U(v.map,1/0,1),new U(v.string,"/",1),new U(v.map,1/0,1),new U(v.string,"bytes",5),new U(v.string,e,e.length),new U(v.break,void 0,1),new U(v.break,void 0,1)]}function tn(r){return Rd(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function CI(r){return Rd(new Uint8Array(r))}function PI(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function RI(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 DI={typeEncoders:{Object:kI,Buffer:Rd,Uint8Array:Rd,Int8Array:tn,Uint16Array:tn,Int16Array:tn,Uint32Array:tn,Int32Array:tn,Float32Array:tn,Float64Array:tn,Uint8ClampedArray:tn,BigInt64Array:tn,BigUint64Array:tn,DataView:tn,ArrayBuffer:CI,undefined:PI,number:RI}},Lp=class extends Ns{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===v.map){let t=this._next();if(t.type===v.string&&t.value==="/"){let n=this._next();if(n.type===v.string){if(this._next().type!==v.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new U(v.tag,42,0)}if(n.type===v.map){let o=this._next();if(o.type===v.string&&o.value==="bytes"){let i=this._next();if(i.type===v.string){for(let a=0;a<2;a++)if(this._next().type!==v.break)throw new Error("Invalid encoded Bytes form");let s=nt.decode(`m${i.value}`);return new U(v.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Bp={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Bp.tags[42]=j.parse;var NI="dag-json",Op=297,O5=r=>Dp(r,DI),M5=r=>{let e=_I(r),t=Object.assign(Bp,{tokenizer:new Lp(e,Bp)});return Np(e,t)},LI=r=>BI.decode(O5(r));var BI=new TextDecoder,OI=r=>M5(MI.encode(r)),MI=new TextEncoder;var Hp={};Ye(Hp,{code:()=>Kp,createLink:()=>G5,createNode:()=>W5,decode:()=>XI,encode:()=>YI,name:()=>QI,prepare:()=>Vp,validate:()=>$p});var UI=new TextDecoder;function Up(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 Dd(r,e){let t;[t,e]=Up(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 U5(r,e){let t;return[t,e]=Up(r,e),[t&7,t>>3,e]}function FI(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=U5(r,n),i===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]=Dd(r,n)}else if(i===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 s;[s,n]=Dd(r,n),e.Name=UI.decode(s)}else if(i===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]=Up(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function F5(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=U5(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=Dd(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]=Dd(r,t),n.push(FI(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 s={};return i&&(s.Data=i),s.Links=n||[],s}var $5=new TextEncoder,V5=2**32,VI=2**31;function $I(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=xc(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=$5.encode(r.Name);t-=n.length,e.set(n,t),t=xc(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=xc(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function K5(r){let e=HI(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=xc(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=$I(r.Links[o],t.subarray(0,n));n-=i,n=xc(t,n,i)-1,t[n]=18}return t}function KI(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Ls(t)}if(typeof r.Name=="string"){let t=$5.encode(r.Name).length;e+=1+t+Ls(t)}return typeof r.Tsize=="number"&&(e+=1+Ls(r.Tsize)),e}function HI(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Ls(t)}if(r.Links)for(let t of r.Links){let n=KI(t);e+=1+n+Ls(n)}return e}function xc(r,e,t){e-=Ls(t);let n=e;for(;t>=VI;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Ls(r){return r%2===0&&r++,Math.floor((qI(r)+6)/7)}function qI(r){let e=0;return r>=V5&&(r=Math.floor(r/V5),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+zI[r]}var zI=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var WI=["Data","Links"],GI=["Hash","Name","Tsize"],Fp=new TextEncoder;function q5(r,e){if(r===e)return 0;let t=r.Name?Fp.encode(r.Name):[],n=e.Name?Fp.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function H5(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function z5(r){if(typeof r.asCID=="object"){let t=j.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=j.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=j.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=j.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function Vp(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=Fp.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(z5),e.Links.sort(q5);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function $p(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!H5(r,WI))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!H5(t,GI))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&q5(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function W5(r,e=[]){return Vp({Data:r,Links:e})}function G5(r,e,t){return z5({Hash:t,Name:r,Tsize:e})}function Q5(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var QI="dag-pb",Kp=112;function YI(r){$p(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),K5(e)}function XI(r){let e=Q5(r),t=F5(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=j.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function Bs(r){return r?.then!=null}function Y5(r=[],e){let t={[Kp]:Hp,[ei]:is,[Cp]:Pp,[Op]:Mp,[F0]:Ll};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Bs(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new bc(`Could not load codec for ${n}`)}}function X5(r=[],e){let t={[lt.code]:lt,[Ol.code]:Ol,[Zt.code]:Zt};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Bs(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new wc(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var Dr=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var Zn=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 Nd=0,Ld=class extends Zn{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===Nd||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===Nd)return e.multihash.digest;if(this.child==null)throw new Dr;return this.child.get(e)}has(e){return e.multihash.code===Nd?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==Nd&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function jI(r){return r[Symbol.asyncIterator]!=null}function ZI(r,e){let t=0;if(jI(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=ns(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=e(o,t++);if(typeof s.then=="function")return async function*(){await s&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){s===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var rn=ZI;function JI(r){return r[Symbol.asyncIterator]!=null}function j5(r){return r?.then!=null}function eT(r,e){let t=0;if(JI(r))return async function*(){for await(let c of r){let l=e(c,t++);j5(l)&&await l,yield c}}();let n=ns(r),{value:o,done:i}=n.next();if(i===!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++);j5(l)&&await l,yield c}}();let a=e;return function*(){yield o;for(let c of n)a(c,t++),yield c}()}var Ei=eT;var Bd=class{child;getHasher;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Ld(e.blockstore),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new G("blocks:put:duplicate",e)),e):(n.onProgress?.(new G("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new G("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=rn(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new G("blocks:put-many:duplicate",i)),!s}),o=Ei(n,async({cid:i,block:s})=>{t.onProgress?.(new G("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(i,s,t)))});t.onProgress?.(new G("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)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new G("blocks:get:providers:get",e));let o=await Z5(e,this.components.blockBrokers,n,{...t,log:this.log});return t.onProgress?.(new G("blocks:get:blockstore:put",e)),await this.child.put(e,o,t),t.onProgress?.(new G("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(e,o,t))),o}return t.onProgress?.(new G("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new G("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Ei(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let o=await this.getHasher(n.multihash.code);t.onProgress?.(new G("blocks:get-many:providers:get",n));let i=await Z5(n,this.components.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new G("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,t),t.onProgress?.(new G("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,i,t)))}}))}async delete(e,t={}){t.onProgress?.(new G("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new G("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 G("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},Od=class extends Bd{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await yt(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await Ct(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 qp({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},qp=class extends Bd{closeController;constructor(e,t){super(e),this.closeController=new AbortController,F(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=le([this.closeController.signal,n.signal]);F(1/0,o);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=le([this.closeController.signal,t.signal]);F(1/0,n);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=le([this.closeController.signal,t.signal]);F(1/0,n);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=le([this.closeController.signal,t.signal]);F(1/0,n);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=le([this.closeController.signal,t.signal]);F(1/0,n);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=le([this.closeController.signal,t.signal]);F(1/0,n);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=le([this.closeController.signal,t.signal]);F(1/0,n);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=le([this.closeController.signal,e.signal]);F(1/0,t);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function tT(r){return typeof r.retrieve=="function"}var rT=(r,e)=>{if(e==null)throw new P(`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`);return async t=>{let n,o=e.digest(t);if(Bs(o)?n=await o:n=o,!oe(n.digest,r.multihash.digest))throw new co("Hash of downloaded block did not match multihash from passed CID")}};async function Z5(r,e,t,n){let o=rT(r,t),i=new AbortController,s=le([i.signal,n.signal]);F(1/0,i.signal,s);let a=[];for(let c of e)tT(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:s,validateFn:async d=>{await o(d),l=!0}});return l||await o(u),u}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{i.abort(),s.clear()}}var Si=class extends ye{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),F(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=rr(this.maxProviders)}async retrieve(e,t={}){let n=nt.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let i=ee();if(this.requests.set(n,i.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 s=!1,a=new Vt({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=>{s=!0,i.resolve(l.detail.result)}),a.addEventListener("idle",()=>{s||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 u=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(u)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c",e,l),i.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(u=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,u)})};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 i.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=ee(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let s of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new yc(`Found ${i} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",e,s.errors??s),o.reject(s)}),o.promise}};var Md=class{blockstore;datastore;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??ko(),this.log=this.logger.forComponent("helia"),this.getHasher=X5(e.hashers,e.loadHasher),this.getCodec=Y5(e.codecs,e.loadCodec),this.dns=e.dns??ud(),this.metrics=e.metrics;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new kd(t,{routers:(e.routers??[]).flatMap(o=>{let i=[o];return o[hn]!=null&&i.push(o[hn]),o[pn]!=null&&i.push(o[pn]),i}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new Od(t);this.pins=new _d(e.datastore,n,this.getCodec),this.blockstore=new Cd(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await N5(this.datastore),await yt(this.blockstore,this.datastore,this.routing)}async stop(){await Ct(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 Rt(o.deleteMany(async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new G("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new G("helia:gc:error",s))}}()))}finally{t()}this.log("gc finished")}};var zp=class extends Si{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.toMultihash().bytes}equals(e,t){return e.equals(t)}};function J5(r,e){return new zp(r,e)}var Ud=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 Wp=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 Fd(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Wp({name:e,metrics:t}):n=new Map,n}function nT(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=$t(r);e.push(t),r=r.slice(me(t))}return e}var e7=nT;var Vd=class extends ye{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),F(1/0,this),this.peers=ac({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=Fd({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=$(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??Je.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,o)),o.wantType===Je.WantHave&&t.wantType===Je.WantBlock&&(o.wantType=Je.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===Je.WantBlock?(await fr(this,"block",t?.signal,{filter:a=>oe(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await fr(this,"presence",t?.signal,{filter:s=>oe(e.multihash.digest,s.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=ee(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Qn;for(let[i,s]of this.wants.entries())t.has(i)||s.cancel||(n.add(i),o.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:s.priority,wantType:s.wantType,cancel:s.cancel,sendDontHave:s.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o);for(let i of n)t.add(i)}catch(i){this.log.error("error sending full wantlist to new peer",i)}})).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=$(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Qn;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:Je.WantHave,priority:1}),await this.network.sendMessage(t,o),(await fr(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&oe(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:Je.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Qn;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:Je.WantBlock,priority:1}),await this.network.sendMessage(t,o),(await fr(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&oe(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=$(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 i=e7(o.prefix),s=i[0],a=i[1],c=i[2],l=c===lt.code?lt:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let u=l.digest(o.data);u.then!=null&&(u=await u);let d=j.create(s===0?0:1,a,u);this.log("received block from %p for %c",e,d),this.safeDispatchEvent("block",{detail:{sender:e,cid:d,block:o.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:d,has:!0,block:o.data}});let h=$(d.multihash.bytes,"base64"),f=this.wants.get(h);f!=null&&(f.cancel=!0,n=!0)}for(let{cid:o,type:i}of t.blockPresences){let s=j.decode(o);this.log("received %s from %p for %c",i,e,s),this.safeDispatchEvent("presence",{detail:{sender:e,cid:s,has:i===Ar.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Qn(!0);for(let[o,i]of this.wants.entries())i.cancel||(t.add(o),n.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:1,wantType:Je.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 $d=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 Ud(e),this.network=new Hl(e,t),this.peerWantLists=new rd({...e,network:this.network},t),this.wantList=new Vd({...e,network:this.network},t)}createSession(e={}){return J5({wantList:this.wantList,network:this.network,logger:this.logger},e)}async want(e,t={}){let n=new AbortController,o=le([n.signal,t.signal]);F(1/0,n.signal,o),this.network.findAndConnect(e,{...t,signal:o}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,i)});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 t7=(r,e={})=>new $d(r,e);var Gp=class{bitswap;started;constructor(e,t={}){let{getHasher:n}=e;this.bitswap=t7(e,{hashLoader:{getHasher:async o=>n(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,i)=>{await this.bitswap.notify(n,o,i)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function Qp(r={}){return e=>new Gp(e,r)}var Kd=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 i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let h=Number.parseInt(d,e);if(!Number.isNaN(h))return h});if(u===void 0)break;if(i*=e,i+=u,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}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 s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&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 i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var r7=45,oT=15,Os=new Kd;function Hd(r){if(!(r.length>oT))return Os.new(r).parseWith(()=>Os.readIPv4Addr())}function qd(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>r7))return Os.new(r).parseWith(()=>Os.readIPv6Addr())}function Ai(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>r7))return Os.new(r).parseWith(()=>Os.readIPAddr())}function nn(r){return!!Hd(r)}function Ms(r){return!!qd(r)}function zd(r){return!!Ai(r)}var o7=ur(n7(),1),iT=["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"],sT=iT.map(r=>new o7.Netmask(r));function Yp(r){for(let e of sT)if(e.contains(r))return!0;return!1}function aT(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function cT(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Yp(o)}function lT(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function uT(r){let e=r.split(":"),t=e[e.length-1];return Yp(t)}function dT(r){return/^::$/.test(r)||/^::1$/.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 vr(r){return nn(r)?Yp(r):aT(r)?cT(r):lT(r)?uT(r):Ms(r)?dT(r):void 0}var fT=r=>r.toString().split("/").slice(1),Us=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),pe=r=>({match:e=>Us(t=>t===r).match(e),pattern:r}),Ii=()=>({match:r=>Us(e=>typeof e=="string").match(r),pattern:"{string}"}),Ec=()=>({match:r=>Us(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Ce=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Ee.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Sc=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{B0.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),_e=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Mt=(...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(", ")})`}),ge=(...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 Pe(...r){function e(o){let i=fT(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function t(o){return e(o)!==!1}function n(o){let i=e(o);return i===!1?!1:i.length===0}return{matchers:r,matches:t,exactMatch:n}}var Gd=ge(pe("dns4"),Ii()),Qd=ge(pe("dns6"),Ii()),Yd=ge(pe("dnsaddr"),Ii()),jp=ge(pe("dns"),Ii()),LH=Pe(Gd,_e(Ce())),BH=Pe(Qd,_e(Ce())),OH=Pe(Yd,_e(Ce())),Ac=Pe(Mt(jp,Yd,Gd,Qd),_e(Ce())),i7=ge(pe("ip4"),Us(nn)),s7=ge(pe("ip6"),Us(Ms)),Zp=Mt(i7,s7),Jn=Mt(Zp,jp,Gd,Qd,Yd),a7=Pe(Mt(Zp,ge(Mt(jp,Yd,Gd,Qd),_e(Ce())))),MH=Pe(i7),UH=Pe(s7),c7=Pe(Zp),Jp=ge(Jn,pe("tcp"),Ec()),Ic=ge(Jn,pe("udp"),Ec()),Tc=Pe(ge(Jp,_e(Ce()))),FH=Pe(Ic),em=ge(Ic,pe("quic"),_e(Ce())),Xd=ge(Ic,pe("quic-v1"),_e(Ce())),hT=Mt(em,Xd),VH=Pe(em),$H=Pe(Xd),Xp=Mt(Jn,Jp,Ic,em,Xd),l7=Mt(ge(Xp,pe("ws"),_e(Ce()))),Ti=Pe(l7),u7=Mt(ge(Xp,pe("wss"),_e(Ce())),ge(Xp,pe("tls"),_e(ge(pe("sni"),Ii())),pe("ws"),_e(Ce()))),_c=Pe(u7),d7=ge(Ic,pe("webrtc-direct"),_e(Sc()),_e(Sc()),_e(Ce())),kc=Pe(d7),f7=ge(Xd,pe("webtransport"),_e(Sc()),_e(Sc()),_e(Ce())),tm=Pe(f7),Wd=Mt(l7,u7,ge(Jp,_e(Ce())),ge(hT,_e(Ce())),ge(Jn,_e(Ce())),d7,f7,Ce()),jd=Pe(Wd),pT=ge(Wd,pe("p2p-circuit"),Ce()),or=Pe(pT),mT=Mt(ge(Wd,pe("p2p-circuit"),pe("webrtc"),_e(Ce())),ge(Wd,pe("webrtc"),_e(Ce())),ge(pe("webrtc"),_e(Ce()))),Cc=Pe(mT),gT=Mt(ge(Jn,pe("tcp"),Ec(),pe("http"),_e(Ce())),ge(Jn,pe("http"),_e(Ce()))),h7=Pe(gT),yT=Mt(ge(Jn,pe("tcp"),Mt(ge(pe("443"),pe("http")),ge(Ec(),pe("https"))),_e(Ce())),ge(Jn,pe("tls"),pe("http"),_e(Ce())),ge(Jn,pe("https"),_e(Ce()))),p7=Pe(yT),wT=Mt(ge(pe("memory"),Ii(),_e(Ce()))),KH=Pe(wT);function m7(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function g7(r,e,t,n){let o=0;for(let i of r)if(!(o<t)){if(o>n)break;if(i!==e[o])return!1;o++}return!0}function rm(r){switch(r.length){case _i:return r.join(".");case ki:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function y7(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;n&128;)e++,n=n<<1;if(n&128)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function w7(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var _i=4,ki=16,QH=parseInt("0xFFFF",16),bT=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Pc(r,e){e.length===ki&&r.length===_i&&m7(e,0,11)&&(e=e.slice(12)),e.length===_i&&r.length===ki&&g7(r,bT,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function b7(r,e){if(typeof e=="string"&&(e=Ai(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function nm(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=_i,o=Hd(e);if(o==null&&(n=ki,o=qd(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let i=parseInt(t,10);if(Number.isNaN(i)||String(i).length!==t.length||i<0||i>n*8)throw new Error("Failed to parse given CIDR: "+r);let s=om(i,8*n);return{network:Pc(o,s),mask:s}}function om(r,e){if(e!==8*_i&&e!==8*ki)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var Ci=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=nm(e));else{let n=Ai(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let i=Ai(t);if(i==null)throw new Error("Failed to parse mask");this.mask=i}else this.mask=om(o,8*n.length);this.network=Pc(n,this.mask)}}contains(e){return b7({network:this.network,mask:this.mask},e)}toString(){let e=y7(this.mask),t=e!==-1?String(e):w7(this.mask);return rm(this.network)+"/"+t}};function x7(r,e){return new Ci(r).contains(e)}var v7=nn,xT=Ms,im=function(r){let e=0;if(r=r.toString().trim(),v7(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(xT(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=v7(t[n]),s;i&&(s=im(t[n]),t[n]=$(s.slice(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,$(s.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 i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let i=parseInt(t[n],16);o[e++]=i>>8&255,o[e++]=i&255}return o}throw new Error("invalid ip address")},E7=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 i=0;i<t;i++)o.push(r[e+i]);return o.join(".")}if(t===16){let o=[];for(let i=0;i<t;i+=2)o.push(n.getUint16(e+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Fs={},sm={},ET=[[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"],[481,-1,"http-path"],[777,-1,"memory"]];ET.forEach(r=>{let e=ST(...r);sm[e.code]=e,Fs[e.name]=e});function ST(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function J(r){if(typeof r=="number"){if(sm[r]!=null)return sm[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Fs[r]!=null)return Fs[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var AT=J("ip4"),IT=J("ip6"),TT=J("ipcidr");function um(r,e){switch(J(r).code){case 4:case 41:return kT(e);case 42:return lm(e);case 43:return $(e,"base10");case 6:case 273:case 33:case 132:return I7(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return lm(e);case 421:return DT(e);case 444:return A7(e);case 445:return A7(e);case 466:return RT(e);case 481:return globalThis.encodeURIComponent(lm(e));default:return $(e,"base16")}}function dm(r,e){switch(J(r).code){case 4:return S7(e);case 41:return S7(e);case 42:return cm(e);case 43:return M(e,"base10");case 6:case 273:case 33:case 132:return hm(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return cm(e);case 421:return CT(e);case 444:return NT(e);case 445:return LT(e);case 466:return PT(e);case 481:return cm(globalThis.decodeURIComponent(e));default:return M(e,"base16")}}function fm(r){let e,t;if(r.stringTuples().forEach(([n,o])=>{(n===AT.code||n===IT.code)&&(t=o),n===TT.code&&(e=o)}),e==null||t==null)throw new Error("Invalid multiaddr");return new Ci(t,e)}var am=Object.values(ri).map(r=>r.decoder),_T=function(){let r=am[0].or(am[1]);return am.slice(2).forEach(e=>r=r.or(e)),r}();function S7(r){if(!zd(r))throw new Error("invalid ip address");return im(r)}function kT(r){let e=E7(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!zd(e))throw new Error("invalid ip address");return e}function hm(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function I7(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function cm(r){let e=M(r),t=Uint8Array.from(Ke(e.length));return Re([t,e],t.length+e.length)}function lm(r){let e=$t(r);if(r=r.slice(me(e)),r.length!==e)throw new Error("inconsistent lengths");return $(r)}function CT(r){let e;r[0]==="Q"||r[0]==="1"?e=Ie(Ee.decode(`z${r}`)).bytes:e=j.parse(r).multihash.bytes;let t=Uint8Array.from(Ke(e.length));return Re([t,e],t.length+e.length)}function PT(r){let e=_T.decode(r),t=Uint8Array.from(Ke(e.length));return Re([t,e],t.length+e.length)}function RT(r){let e=$t(r),t=r.slice(me(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+$(t,"base64url")}function DT(r){let e=$t(r),t=r.slice(me(e));if(t.length!==e)throw new Error("inconsistent lengths");return $(t,"base58btc")}function NT(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=ct.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=hm(n);return Re([t,o],t.length+o.length)}function LT(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=ct.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=hm(n);return Re([t,o],t.length+o.length)}function A7(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=$(e,"base32"),o=I7(t);return`${n}:${o}`}function T7(r){r=pm(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 i=0;i<o.length;i++){let s=o[i],a=J(s);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(i++,i>=o.length)throw k7("invalid address: "+r);if(a.path===!0){n=pm(o.slice(i).join("/")),e.push([a.code,dm(a.code,n)]),t.push([a.code,n]);break}let c=dm(a.code,o[i]);e.push([a.code,c]),t.push([a.code,um(a.code,c)])}return{string:_7(t),bytes:gm(e),tuples:e,stringTuples:t,path:n}}function mm(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let i=$t(r,o),s=me(i),a=J(i),c=BT(a,r.slice(o+s));if(c===0){e.push([i]),t.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw k7("Invalid address Uint8Array: "+$(r,"base16"));e.push([i,l]);let u=um(i,l);if(t.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:_7(t),tuples:e,stringTuples:t,path:n}}function _7(r){let e=[];return r.map(t=>{let n=J(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),pm(e.join("/"))}function gm(r){return Re(r.map(e=>{let t=J(e[0]),n=Uint8Array.from(Ke(t.code));return e.length>1&&e[1]!=null&&(n=Re([n,e[1]])),n}))}function BT(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=$t(e instanceof Uint8Array?e:Uint8Array.from(e));return t+me(t)}}function pm(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function k7(r){return new Error("Error parsing address: "+r)}var OT=Symbol.for("nodejs.util.inspect.custom"),wm=Symbol.for("@multiformats/js-multiaddr/multiaddr"),MT=[J("dns").code,J("dns4").code,J("dns6").code,J("dnsaddr").code],ym=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},Zd=class r{bytes;#e;#t;#r;#o;[wm]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=mm(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=T7(e)}else if(Bo(e))t=mm(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,i="",s=J("tcp"),a=J("udp"),c=J("ip4"),l=J("ip6"),u=J("dns6"),d=J("ip6zone");for(let[f,p]of this.stringTuples())f===d.code&&(i=`%${p??""}`),MT.includes(f)&&(t=s.name,o=443,n=`${p??""}${i}`,e=f===u.code?6:4),(f===s.code||f===a.code)&&(t=J(f).name,o=parseInt(p??"")),(f===c.code||f===l.code)&&(t=J(f).name,n=`${p??""}${i}`,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({},J(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>J(e).name)}tuples(){return this.#t.map(([e,t])=>t==null?[e]:[e,t])}stringTuples(){return this.#r.map(([e,t])=>t==null?[e]:[e,t])}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(gm(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===Fs.p2p.code&&e.push([n,o]),n===Fs["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?$(Ee.decode(`z${n}`),"base58btc"):$(j.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#o}equals(e){return oe(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(i=>i.resolvable);if(t==null)return[this];let n=Vs.get(t.name);if(n==null)throw new ym(`no available resolver for ${t.name}`);return(await n(this,e)).map(i=>q(i))}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)}[OT](){return`Multiaddr(${this.#e})`}};var Vs=new Map;function Bo(r){return!!r?.[wm]}function q(r){return new Zd(r)}var UT=[J("tcp").code,J("dns").code,J("dnsaddr").code,J("dns4").code,J("dns6").code];function C7(r){return D7("sni",r)?.[1]}function P7(r){let e=D7("tcp",r)?.[1];return e==null?"":`:${e}`}function D7(r,e){let t;try{t=J(r).code}catch{return}for(let[n,o]of e)if(n===t&&o!=null)return[n,o]}function R7(r){return r.some(([e,t])=>e===J("tls").code)}function on(r,e,t){let n=N7[J(r).name];if(n==null)throw new Error(`Can't interpret protocol ${J(r).name}`);let o=n(e,t);return r===J("ip6").code?`[${o}]`:o}var N7={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${on(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${on(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==null)throw new Error("Unexpected end of multiaddr");return`${on(t[0],t[1]??"",e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${on(t[0],t[1]??"",e)}`},http:(r,e)=>{let t=R7(e),n=C7(e),o=P7(e);if(t&&n!=null)return`https://${n}${o}`;let i=t?"https://":"http://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=on(s[0],s[1]??"",e);return a=a.replace("tcp://",""),`${i}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=on(t[0],t[1]??"",e),o=decodeURIComponent(r);return`${n}/${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return on(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return on(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=on(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=R7(e),n=C7(e),o=P7(e);if(t&&n!=null)return`wss://${n}${o}`;let i=t?"wss://":"ws://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=on(s[0],s[1]??"",e);return a=a.replace("tcp://",""),`${i}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=on(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`}};function Jd(r,e){let n=q(r).stringTuples(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let i=J(o[0]),s=N7[i.name];if(s==null)throw new Error(`No interpreter found for ${i.name}`);let a=s(o[1]??"",n);return e?.assumeHttp!==!1&&UT.includes(o[0])&&(a=a.replace(/^.*:\/\//,""),o[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://")||a.startsWith("ws://")||a.startsWith("wss://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var e1=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 nt.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),i=new AbortController,s=()=>{i.abort()};t?.addEventListener("abort",s);try{let a=this.#a.get(o);return a==null&&(this.#e++,a=fetch(n.toString(),{signal:i.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",s),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 FT(r,e,t){return r.filter(n=>{if(p7.matches(n)||e&&h7.matches(n))return t||Ac.matches(n)?!0:vr(n.toOptions().host)===!1;if(!e&&t){let{host:o}=n.toOptions();if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*t1(r,e,t,n,o,i){for await(let s of e.findProviders(r,i)){let a=FT(s.multiaddrs,n,o);if(a.length===0)continue;let c=Jd(a[0]);yield new e1(c,t)}}var bm=class extends Si{routing;allowInsecure;allowLocal;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??r1,this.allowLocal=t.allowLocal??n1}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*t1(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 L7(r,e){return new bm(r,e)}var o1=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??r1,this.allowLocal=t.allowLocal??n1}async retrieve(e,t={}){let n=[];for await(let o of t1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)){this.log("getting block for %c from %s",e,o.url);try{let i=await o.getRawBlock(e,t.signal);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(i)}catch(s){this.log.error("failed to validate block for %c from %s",e,o.url,s);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s",e,o.url,i),i instanceof Error?n.push(i):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 L7({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure})}};var r1=!1,n1=!1;function xm(r={}){return e=>new o1(e,r)}async function*i1(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 zT=ur(s1(),1);var sn=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},a1=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},$s=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},c1=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},l1=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},u1=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},Rc=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var ir;(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,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.value!=null&&(i.uint32(10),i.bytes(o.value)),o.signatureV1!=null&&(i.uint32(18),i.bytes(o.signatureV1)),o.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(o.validityType,i)),o.validity!=null&&(i.uint32(34),i.bytes(o.validity)),o.sequence!=null&&(i.uint32(40),i.uint64(o.sequence)),o.ttl!=null&&(i.uint32(48),i.uint64(o.ttl)),o.pubKey!=null&&(i.uint32(58),i.bytes(o.pubKey)),o.signatureV2!=null&&(i.uint32(66),i.bytes(o.signatureV2)),o.data!=null&&(i.uint32(74),i.bytes(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>re(o,r.codec()),r.decode=(o,i)=>te(o,r.codec(),i)})(ir||(ir={}));var VT=pr("ipns:utils"),B7=M("/ipns/");var $T=0,KT=18;function O7(r){let e;if(r.pubKey!=null)try{e=tt(r.pubKey)}catch(t){throw VT.error(t),t}if(e!=null)return e}function M7(r){let e=M("ipns-signature:");return Re([e,r])}function Dc(r){return"signatureV1"in r?ir.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}):ir.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function _n(r){let e=ir.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 new sn("Missing data or signatureV2");let t=U7(e.data),n=HT(t.Value),o=$(t.Validity);if(e.value!=null&&e.signatureV1!=null)return qT(e),{value:n,validityType:ir.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:ir.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")}function Nc(r){return Re([B7,r.bytes])}function Ks(r){let e=Ie(r.slice(B7.length));if(!d1(e,$T)&&!d1(e,KT))throw new co("Multihash in IPNS key was not identity or sha2-256");return e}function U7(r){let e=xr(r);if(e.ValidityType===0)e.ValidityType=ir.ValidityType.EOL;else throw new $s("The validity type is unsupported");return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e}function HT(r){let e=$(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${j.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${j.parse(e).toV1().toString()}`}catch{}throw new l1("Value must be a valid content path starting with /")}function qT(r){if(r.data==null)throw new u1("Record data is missing");let e=U7(r.data);if(!oe(e.Value,r.value??new Uint8Array(0)))throw new sn('Field "value" did not match between protobuf and CBOR');if(!oe(e.Validity,r.validity??new Uint8Array(0)))throw new sn('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new sn('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new sn('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new sn('Field "ttl" did not match between protobuf and CBOR')}function d1(r,e){return r.code===e}var Oz=pr("ipns"),Mz=60*60*1e9,WT="/ipns/",Uz=WT.length;var F7=ur(s1(),1);var f1=pr("ipns:validator"),GT=1024*10,QT=async(r,e)=>{let t=_n(e),n;try{let o=M7(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw f1.error("record signature verification failed"),new sn("Record signature verification failed");if(t.validityType===ir.ValidityType.EOL){if(F7.default.fromString(t.validity).toDate().getTime()<Date.now())throw f1.error("record has expired"),new a1("record has expired")}else if(t.validityType!=null)throw f1.error("the validity type is unsupported"),new $s("The validity type is unsupported");f1("ipns record for %s is valid",t.value)};async function h1(r,e){if(e.byteLength>GT)throw new c1("The record is too large");let t=Ks(r),n;d1(t,0)&&(n=Yu(t));let o=_n(e),i=O7(o)??n;if(i==null)throw new Rc("Could not extract public key from IPNS record or routing key");let s=Nc(i.toMultihash());if(!oe(r,s))throw new Rc("Embedded public key did not match routing key");await QT(i,e)}var p1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*Lc(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let i of r){if(typeof i=="string"&&(i=new TextEncoder().encode(i)),rs(i)&&(i=i.subarray()),o+=n.decode(i,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new p1("Incoming message too long");let s=o.split(t);o=s.pop()??"";for(let a=0;a<s.length;a++)yield JSON.parse(s[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var Hs=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},Pi=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function YT(r){return r[Symbol.asyncIterator]!=null}function XT(r){if(YT(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var V7=XT;var $7=M("/ipns/");function K7(r){return oe(r.subarray(0,$7.byteLength),$7)}var m1=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*Xt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!K7(e))return;let o=Ks(e),i=j.createV1(114,o),s=_n(t);await this.client.putIPNS(i,s,n)}async get(e,t){if(!K7(e))throw new Oe("Not found");let n=Ks(e),o=j.createV1(114,n);try{let i=await this.client.getIPNS(o,t);return Dc(i)}catch(i){throw i.name==="BadResponseError"?new Oe("Not found"):i}}},g1=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await V7(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new Oe("Not found")}async*getClosestPeers(e,t={}){}};var gt=pr("delegated-routing-v1-http-api-client"),y1={concurrentRequests:4,timeout:3e4,cacheTTL:5*60*1e3,cacheName:"delegated-routing-v1-cache"},w1=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,F(1/0,this.shutDownController.signal),this.httpQueue=new In({concurrency:t.concurrentRequests??y1.concurrentRequests}),this.inFlightRequests=new Map,this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??y1.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new m1(this),this.peerRouting=new g1(this),this.cacheName=t.cacheName??y1.cacheName,this.cacheTTL=t.cacheTTL??y1.cacheTTL}get[hn](){return this.contentRouting}get[pn](){return this.peerRouting}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&>("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){gt("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=le([this.shutDownController.signal,n,t.signal]);F(1/0,n,o);let i=ee(),s=ee();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/providers/${e.toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(l.status===404)throw new Oe("No matching records found");if(l.status===422)throw new Hs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Pi("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let d=await l.json();for(let h of d.Providers){let f=this.#e(h);f!=null&&(yield f)}}else for await(let d of Lc(i1(l.body))){let h=this.#e(d);h!=null&&(yield h)}}catch(a){gt.error("getProviders errored:",a)}finally{o.clear(),s.resolve(),gt("getProviders finished: %c",e)}}async*getPeers(e,t={}){gt("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=le([this.shutDownController.signal,n,t.signal]);F(1/0,n,o);let i=ee(),s=ee();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(l.status===404)throw new Oe("No matching records found");if(l.status===422)throw new Hs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Pi("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let d=await l.json();for(let h of d.Peers){let f=this.#e(h);f!=null&&(yield f)}}else for await(let d of Lc(i1(l.body))){let h=this.#e(d);h!=null&&(yield h)}}catch(a){gt.error("getPeers errored:",a)}finally{o.clear(),s.resolve(),gt("getPeers finished: %c",e)}}async getIPNS(e,t={}){gt("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),o=le([this.shutDownController.signal,n,t.signal]);F(1/0,n,o);let i=ee(),s=ee();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${e}`;try{await i.promise;let c={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o},l=await this.#r(a,c);if(gt("getIPNS GET %s %d",a,l.status),l.status===404)throw new Oe("No matching records found");if(l.status===422)throw new Hs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Pi("GET ipns response had no body");let u=await l.arrayBuffer(),d=new Uint8Array(u,0,u.byteLength);return t.validate!==!1&&await h1(Nc(e.multihash),d),_n(d)}catch(c){throw gt.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),s.resolve(),gt("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){gt("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),i=le([this.shutDownController.signal,o,n.signal]);F(1/0,o,i);let s=ee(),a=ee();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e}`;try{await s.promise;let l=Dc(t),u={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i},d=await this.#r(c,u);if(gt("putIPNS PUT %s %d",c,d.status),d.status!==200)throw new Pi("PUT ipns response had status other than 200")}catch(l){throw gt.error("putIPNS PUT %s error:",c,l.stack),l}finally{i.clear(),a.resolve(),gt("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(q)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:Fe(e.ID),Addrs:n,Protocols:t}}catch(t){gt.error("could not conform record to peer schema",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#r(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return gt("returning cached response for %s",o),c;await this.cache?.delete(e)}}let i=this.inFlightRequests.get(o);if(i!=null){let c=await i;return gt("deduplicating outgoing request for %s",o),c.clone()}let s=fetch(e,t).then(async c=>{if(this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,u=new Headers(c.headers);u.set("x-cache-expires",l.toString());let d=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:u});await this.cache.put(e,d)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,s),await s}};function H7(r,e={}){return new w1(new URL(r),e)}function Em(){return{filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}var q7="[a-fA-F\\d:]",Oo=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${q7})|(?<=${q7})(?=\\s|$))`:"",an="(?: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}",it="[a-fA-F\\d]{1,4}",b1=`
|
|
7
|
+
`)}`:`${t} :`}};W6=Io;Q.Constructed=W6;Io.NAME="CONSTRUCTED";var du=class extends Bt{fromBER(e,t,n){return t}toBER(e){return Xr}};du.override="EndOfContentValueBlock";var G6,fu=class extends xt{constructor(e={}){super(e,du),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};G6=fu;Q.EndOfContent=G6;fu.NAME=Fa;var Q6,$n=class extends xt{constructor(e={}){super(e,Bt),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}`}};Q6=$n;Q.Null=Q6;$n.NAME="NULL";var hu=class extends zn(Bt){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 qn(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,_2.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};hu.NAME="BooleanValueBlock";var Y6,pu=class extends xt{constructor(e={}){super(e,hu),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}`}};Y6=pu;Q.Boolean=Y6;pu.NAME="BOOLEAN";var mu=class extends zn(xn){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=xn.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let i=0;i<this.value.length;i++){let s=this.value[i].constructor.NAME;if(s===Fa){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(s!==K6)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?xn.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};mu.NAME="OctetStringValueBlock";var X6,Kn=class r extends xt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},mu),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 i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let s=Hu(i,0,i.byteLength);s.offset!==-1&&s.offset===n&&(this.valueBlock.value=[s.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Io.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)}};X6=Kn;Q.OctetString=X6;Kn.NAME=K6;var gu=class extends zn(xn){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=xn.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Fa){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==H6)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 i=we.BufferSourceConverter.toUint8Array(e);if(!qn(this,i,t,n))return-1;let s=i.subarray(t,t+n);if(this.unusedBits=s[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=s.subarray(1);try{if(a.byteLength){let c=Hu(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,t+n}toBER(e,t){if(this.isConstructed)return xn.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Xr;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}}};gu.NAME="BitStringValueBlock";var j6,Es=class extends xt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},gu),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 Io.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)}`}}};j6=Es;Q.BitString=j6;Es.NAME=H6;var Z6;function KS(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<s?s:c,d=0;for(let h=u;h>=0;h--,d++){switch(!0){case d<a.length:l=i[s-d]+a[c-d]+t[0];break;default:l=i[s-d]+t[0]}switch(t[0]=l/10,!0){case d>=i.length:i=ou(new Uint8Array([l%10]),i);break;default:i[s-d]=l%10}}return t[0]>0&&(i=ou(t,i)),i}function $6(r){if(r>=Ma.length)for(let e=Ma.length;e<=r;e++){let t=new Uint8Array([0]),n=Ma[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let i=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=i[0]/10,n[o]=i[0]%10}t[0]>0&&(n=ou(t,n)),Ma.push(n)}return Ma[r]}function HS(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let d=c;d>=0;d--,u++)switch(l=i[s-u]-a[c-u]-t,!0){case l<0:t=1,i[s-u]=l+10;break;default:t=0,i[s-u]=l}if(t>0)for(let d=s-c+1;d>=0;d--,u++)if(l=i[s-u]-t,l<0)t=1,i[s-u]=l+10;else{t=0,i[s-u]=l;break}return i.slice()}var Va=class extends zn(Bt){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=_2.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(U6(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let i=this.fromBER(e,t,n);if(i===-1)return i;let s=this.valueHexView;return s[0]===0&&s[1]&128?this.valueHexView=s.subarray(1):o!==0&&s.length<o&&(o-s.length>1&&(o=s.length+1),this.valueHexView=s.subarray(o-s.length)),i}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,i=this.valueHexView,s="",a=!1;for(let c=i.byteLength-1;c>=0;c--){o=i[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=HS($6(n),t),s="-";break;default:t=KS(t,$6(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(s+=V6.charAt(t[c]));return a===!1&&(s+=V6.charAt(0)),s}};Z6=Va;Va.NAME="IntegerValueBlock";Object.defineProperty(Z6.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var J6,et=class r extends xt{constructor(e={}){super(e,Va),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return iu(),BigInt(this.valueBlock.toString())}static fromBigInt(e){iu();let t=BigInt(e),n=new Ua,o=t.toString(16).replace(/^-/,""),i=new Uint8Array(we.Convert.FromHex(o));if(t<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${we.Convert.ToHex(a)}`)+t,u=we.BufferSourceConverter.toUint8Array(we.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);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()}`}};J6=et;Q.Integer=J6;et.NAME="INTEGER";var e8,yu=class extends et{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};e8=yu;Q.Enumerated=e8;yu.NAME="ENUMERATED";var $a=class extends zn(Bt){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(!qn(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[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=hi(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){iu();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,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=Ao(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Xr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}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}}};$a.NAME="sidBlock";var wu=class extends Bt{constructor({value:e=Ss,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new $a;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}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,Xr;t.push(o)}return k2(t)}fromString(e){this.value=[];let t=0,n=0,o="",i=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,i){let s=this.value[0],a=0;switch(s.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;s.valueDec=c+a,i=!1}else{let s=new $a;if(o>Number.MAX_SAFE_INTEGER){iu();let a=BigInt(o);s.valueBigInt=a}else if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return;this.value.length||(s.isFirstSid=!0,i=!0),this.value.push(s)}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}};wu.NAME="ObjectIdentifierValueBlock";var t8,kr=class extends xt{constructor(e={}){super(e,wu),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()}}};t8=kr;Q.ObjectIdentifier=t8;kr.NAME="OBJECT IDENTIFIER";var Ka=class extends zn(Vn){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(!qn(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[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=hi(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,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=Ao(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Xr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}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}}};Ka.NAME="relativeSidBlock";var bu=class extends Bt{constructor({value:e=Ss,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new Ka;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let i=this.value[o].toBER(e);if(i.byteLength===0)return this.error=this.value[o].error,Xr;n.push(i)}return k2(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 i=new Ka;if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return!0;this.value.push(i)}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}};bu.NAME="RelativeObjectIdentifierValueBlock";var r8,xu=class extends xt{constructor(e={}){super(e,bu),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()}}};r8=xu;Q.RelativeObjectIdentifier=r8;xu.NAME="RelativeObjectIdentifier";var n8,dt=class extends Io{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};n8=dt;Q.Sequence=n8;dt.NAME="SEQUENCE";var o8,vu=class extends Io{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};o8=vu;Q.Set=o8;vu.NAME="SET";var Eu=class extends zn(Bt){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Ss}toJSON(){return{...super.toJSON(),value:this.value}}};Eu.NAME="StringValueBlock";var Su=class extends Eu{};Su.NAME="SimpleStringValueBlock";var Ht=class extends cu{constructor({...e}={}){super(e,Su)}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}};Ht.NAME="SIMPLE STRING";var Au=class extends Ht{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}};Au.NAME="Utf8StringValueBlock";var i8,Hn=class extends Au{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};i8=Hn;Q.Utf8String=i8;Hn.NAME="UTF8String";var Iu=class extends Ht{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))}};Iu.NAME="BmpStringValueBlock";var s8,Tu=class extends Iu{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};s8=Tu;Q.BmpString=s8;Tu.NAME="BMPString";var _u=class extends Ht{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 i=Ao(e.charCodeAt(o),8),s=new Uint8Array(i);if(s.length>4)continue;let a=4-s.length;for(let c=s.length-1;c>=0;c--)n[o*4+c+a]=s[c]}this.valueBlock.value=e}};_u.NAME="UniversalStringValueBlock";var a8,ku=class extends _u{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};a8=ku;Q.UniversalString=a8;ku.NAME="UniversalString";var c8,Cu=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};c8=Cu;Q.NumericString=c8;Cu.NAME="NumericString";var l8,Pu=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};l8=Pu;Q.PrintableString=l8;Pu.NAME="PrintableString";var u8,Ru=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};u8=Ru;Q.TeletexString=u8;Ru.NAME="TeletexString";var d8,Du=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};d8=Du;Q.VideotexString=d8;Du.NAME="VideotexString";var f8,Nu=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};f8=Nu;Q.IA5String=f8;Nu.NAME="IA5String";var h8,Lu=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};h8=Lu;Q.GraphicString=h8;Lu.NAME="GraphicString";var p8,Ha=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};p8=Ha;Q.VisibleString=p8;Ha.NAME="VisibleString";var m8,Bu=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};m8=Bu;Q.GeneralString=m8;Bu.NAME="GeneralString";var g8,Ou=class extends Ht{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};g8=Ou;Q.CharacterString=g8;Ou.NAME="CharacterString";var y8,qa=class extends Ha{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]=er(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=er(this.month,2),t[2]=er(this.day,2),t[3]=er(this.hour,2),t[4]=er(this.minute,2),t[5]=er(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}}};y8=qa;Q.UTCTime=y8;qa.NAME="UTCTime";var w8,Mu=class extends qa{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="",i=0,s,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let d=new Number(e[e.length-1]);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let d=1,h=n.indexOf("+"),f="";if(h===-1&&(h=n.indexOf("-"),d=-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=d*p,f.length===4){if(p=parseInt(f.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=d*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let d=new Number(`0${n.substring(l)}`);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");i=d.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=60*i;this.minute=Math.floor(d),d=60*(d-this.minute),this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case o.length===12:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=60*i;this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case o.length===14:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=1e3*i;this.millisecond=Math.floor(d)}break;default:throw new Error("Wrong input string for conversion")}let u=s.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let d=1;d<u.length;d++)switch(d){case 1:this.year=parseInt(u[d],10);break;case 2:this.month=parseInt(u[d],10);break;case 3:this.day=parseInt(u[d],10);break;case 4:this.hour=parseInt(u[d],10)+a;break;case 5:this.minute=parseInt(u[d],10)+c;break;case 6:this.second=parseInt(u[d],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let d=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=d.getUTCFullYear(),this.month=d.getUTCMonth(),this.day=d.getUTCDay(),this.hour=d.getUTCHours(),this.minute=d.getUTCMinutes(),this.second=d.getUTCSeconds(),this.millisecond=d.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(er(this.year,4)),t.push(er(this.month,2)),t.push(er(this.day,2)),t.push(er(this.hour,2)),t.push(er(this.minute,2)),t.push(er(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(er(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};w8=Mu;Q.GeneralizedTime=w8;Mu.NAME="GeneralizedTime";var b8,Uu=class extends Hn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};b8=Uu;Q.DATE=b8;Uu.NAME="DATE";var x8,Fu=class extends Hn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};x8=Fu;Q.TimeOfDay=x8;Fu.NAME="TimeOfDay";var v8,Vu=class extends Hn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};v8=Vu;Q.DateTime=v8;Vu.NAME="DateTime";var E8,$u=class extends Hn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};E8=$u;Q.Duration=E8;$u.NAME="Duration";var S8,Ku=class extends Hn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};S8=Ku;Q.TIME=S8;Ku.NAME="TIME";function $(r,e="utf8"){let t=Ml[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function qt(r){if(isNaN(r)||r<=0)throw new P("random bytes length must be a Number bigger than 0");return ci(r)}var za=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Wa=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},qu=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var A8={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new qu("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var tr=A8;async function I8(r){let e=await tr.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 qS(e);return{privateKey:t[0],publicKey:t[1]}}async function T8(r,e){let t=await tr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await tr.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function _8(r,e,t){let n=await tr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return tr.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function qS(r){if(r.privateKey==null||r.publicKey==null)throw new P("Private and public key are required");return Promise.all([tr.get().subtle.exportKey("jwk",r.privateKey),tr.get().subtle.exportKey("jwk",r.publicKey)])}function R2(r){if(r.kty!=="RSA")throw new P("invalid key type");if(r.n==null)throw new P("invalid key modulus");return M(r.n,"base64url").length*8}var As=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Ga.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return j.createV1(114,this._multihash)}toString(){return Ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:oe(this.raw,e.raw)}verify(e,t){return _8(this._key,t,e)}},Qa=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Ga.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:oe(this.raw,e.raw)}sign(e){return T8(this._key,e)}};var zu=8192,D2=18;function k8(r){let{result:e}=pi(r),t=e.valueBlock.value;return{n:vn(t[1]),e:vn(t[2]),d:vn(t[3]),p:vn(t[4]),q:vn(t[5]),dp:vn(t[6]),dq:vn(t[7]),qi:vn(t[8]),kty:"RSA",alg:"RS256"}}function zS(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 P("JWK was missing components");let t=new dt({value:[new et({value:0}),et.fromBigInt(En(M(r.n,"base64url"))),et.fromBigInt(En(M(r.e,"base64url"))),et.fromBigInt(En(M(r.d,"base64url"))),et.fromBigInt(En(M(r.p,"base64url"))),et.fromBigInt(En(M(r.q,"base64url"))),et.fromBigInt(En(M(r.dp,"base64url"))),et.fromBigInt(En(M(r.dq,"base64url"))),et.fromBigInt(En(M(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function C8(r){let{result:e}=pi(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:vn(t[0]),e:vn(t[1])}}function N2(r){if(r.n==null||r.e==null)throw new P("JWK was missing components");let t=new dt({value:[new dt({value:[new kr({value:"1.2.840.113549.1.1.1"}),new $n]}),new Es({valueHex:new dt({value:[et.fromBigInt(En(M(r.n,"base64url"))),et.fromBigInt(En(M(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function vn(r){let e=r.valueBlock.valueHexView;for(;e[0]===0;)e=e.subarray(1);return $(e,"base64url")}function En(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(""))}function Wu(r){let e=k8(r);return P8(e)}function L2(r){let e=C8(r);if(R2(e)>zu)throw new Rn("Key size is too large");let t=Tr(bn.encode({Type:Qe.RSA,Data:r})),n=jt(D2,t);return new As(e,n)}function P8(r){if(R2(r)>zu)throw new P("Key size is too large");let e=R8(r),t=Tr(bn.encode({Type:Qe.RSA,Data:N2(e.publicKey)})),n=jt(D2,t);return new Qa(e.privateKey,new As(e.publicKey,n))}async function B2(r){if(r>zu)throw new P("Key size is too large");let e=await I8(r),t=Tr(bn.encode({Type:Qe.RSA,Data:N2(e.publicKey)})),n=jt(D2,t);return new Qa(e.privateKey,new As(e.publicKey,n))}function R8(r){if(r==null)throw new P("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Gu=class extends ps{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ii(e);let n=Wr(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?e.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(e){return hs(this),this.iHash.update(e),this}digestInto(e){hs(this),fs(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},To=(r,e,t)=>new Gu(r,e).update(t).digest();To.create=(r,e)=>new Gu(r,e);function D8(r){r.lowS!==void 0&&Gr("lowS",r.lowS),r.prehash!==void 0&&Gr("prehash",r.prehash)}function WS(r){let e=Ra(r);Ir(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("invalid 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("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:GS,hexToBytes:QS}=Xl,O2=class extends Error{constructor(e=""){super(e)}},Wn={Err:O2,_tlv:{encode:(r,e)=>{let{Err:t}=Wn;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=li(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?li(o.length/2|128):"";return li(r)+i+o+e},decode(r,e){let{Err:t}=Wn,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(r){let{Err:e}=Wn;if(r<Gn)throw new e("integer: negative integers are not allowed");let t=li(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Wn;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return GS(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Wn,o=typeof r=="string"?QS(r):r;gs(o);let{v:i,l:s}=n.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Wn,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),i=n+o;return e.encode(48,i)}},Gn=BigInt(0),ht=BigInt(1),vO=BigInt(2),N8=BigInt(3),EO=BigInt(4);function YS(r){let e=WS(r),{Fp:t}=e,n=vo(e.n,e.nBitLength),o=e.toBytes||((m,g,y)=>{let b=g.toAffine();return Un(Uint8Array.from([4]),t.toBytes(b.x),t.toBytes(b.y))}),i=e.fromBytes||(m=>{let g=m.subarray(1),y=t.fromBytes(g.subarray(0,t.BYTES)),b=t.fromBytes(g.subarray(t.BYTES,2*t.BYTES));return{x:y,y:b}});function s(m){let{a:g,b:y}=e,b=t.sqr(m),w=t.mul(b,m);return t.add(t.add(w,t.mul(m,g)),y)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Ca(m,ht,e.n)}function c(m){let{allowedPrivateKeyLengths:g,nByteLength:y,wrapPrivateKey:b,n:w}=e;if(g&&typeof m!="bigint"){if(bo(m)&&(m=Bn(m)),typeof m!="string"||!g.includes(m.length))throw new Error("invalid private key");m=m.padStart(y*2,"0")}let x;try{x=typeof m=="bigint"?m:On(De("private key",m,y))}catch{throw new Error("invalid private key, expected hex or "+y+" bytes, got "+typeof m)}return b&&(x=Te(x,w)),bt("private key",x,ht,w),x}function l(m){if(!(m instanceof h))throw new Error("ProjectivePoint expected")}let u=di((m,g)=>{let{px:y,py:b,pz:w}=m;if(t.eql(w,t.ONE))return{x:y,y:b};let x=m.is0();g==null&&(g=x?t.ONE:t.inv(w));let _=t.mul(y,g),k=t.mul(b,g),E=t.mul(w,g);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(E,t.ONE))throw new Error("invZ was invalid");return{x:_,y:k}}),d=di(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:g,y}=m.toAffine();if(!t.isValid(g)||!t.isValid(y))throw new Error("bad point: x or y not FE");let b=t.sqr(y),w=s(g);if(!t.eql(b,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class h{constructor(g,y,b){if(this.px=g,this.py=y,this.pz=b,g==null||!t.isValid(g))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(b==null||!t.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(g){let{x:y,y:b}=g||{};if(!g||!t.isValid(y)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof h)throw new Error("projective point not allowed");let w=x=>t.eql(x,t.ZERO);return w(y)&&w(b)?h.ZERO:new h(y,b,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){let y=t.invertBatch(g.map(b=>b.pz));return g.map((b,w)=>b.toAffine(y[w])).map(h.fromAffine)}static fromHex(g){let y=h.fromAffine(i(De("pointHex",g)));return y.assertValidity(),y}static fromPrivateKey(g){return h.BASE.multiply(c(g))}static msm(g,y){return eu(h,n,g,y)}_setWindowSize(g){p.setWindowSize(this,g)}assertValidity(){d(this)}hasEvenY(){let{y:g}=this.toAffine();if(t.isOdd)return!t.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){l(g);let{px:y,py:b,pz:w}=this,{px:x,py:_,pz:k}=g,E=t.eql(t.mul(y,k),t.mul(x,w)),S=t.eql(t.mul(b,k),t.mul(_,w));return E&&S}negate(){return new h(this.px,t.neg(this.py),this.pz)}double(){let{a:g,b:y}=e,b=t.mul(y,N8),{px:w,py:x,pz:_}=this,k=t.ZERO,E=t.ZERO,S=t.ZERO,T=t.mul(w,w),V=t.mul(x,x),L=t.mul(_,_),O=t.mul(w,x);return O=t.add(O,O),S=t.mul(w,_),S=t.add(S,S),k=t.mul(g,S),E=t.mul(b,L),E=t.add(k,E),k=t.sub(V,E),E=t.add(V,E),E=t.mul(k,E),k=t.mul(O,k),S=t.mul(b,S),L=t.mul(g,L),O=t.sub(T,L),O=t.mul(g,O),O=t.add(O,S),S=t.add(T,T),T=t.add(S,T),T=t.add(T,L),T=t.mul(T,O),E=t.add(E,T),L=t.mul(x,_),L=t.add(L,L),T=t.mul(L,O),k=t.sub(k,T),S=t.mul(L,V),S=t.add(S,S),S=t.add(S,S),new h(k,E,S)}add(g){l(g);let{px:y,py:b,pz:w}=this,{px:x,py:_,pz:k}=g,E=t.ZERO,S=t.ZERO,T=t.ZERO,V=e.a,L=t.mul(e.b,N8),O=t.mul(y,x),B=t.mul(b,_),D=t.mul(w,k),N=t.add(y,b),I=t.add(x,_);N=t.mul(N,I),I=t.add(O,B),N=t.sub(N,I),I=t.add(y,w);let A=t.add(x,k);return I=t.mul(I,A),A=t.add(O,D),I=t.sub(I,A),A=t.add(b,w),E=t.add(_,k),A=t.mul(A,E),E=t.add(B,D),A=t.sub(A,E),T=t.mul(V,I),E=t.mul(L,D),T=t.add(E,T),E=t.sub(B,T),T=t.add(B,T),S=t.mul(E,T),B=t.add(O,O),B=t.add(B,O),D=t.mul(V,D),I=t.mul(L,I),B=t.add(B,D),D=t.sub(O,D),D=t.mul(V,D),I=t.add(I,D),O=t.mul(B,I),S=t.add(S,O),O=t.mul(A,I),E=t.mul(N,E),E=t.sub(E,O),O=t.mul(N,B),T=t.mul(A,T),T=t.add(T,O),new h(E,S,T)}subtract(g){return this.add(g.negate())}is0(){return this.equals(h.ZERO)}wNAF(g){return p.wNAFCached(this,g,h.normalizeZ)}multiplyUnsafe(g){let{endo:y,n:b}=e;bt("scalar",g,Gn,b);let w=h.ZERO;if(g===Gn)return w;if(this.is0()||g===ht)return this;if(!y||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,g,h.normalizeZ);let{k1neg:x,k1:_,k2neg:k,k2:E}=y.splitScalar(g),S=w,T=w,V=this;for(;_>Gn||E>Gn;)_&ht&&(S=S.add(V)),E&ht&&(T=T.add(V)),V=V.double(),_>>=ht,E>>=ht;return x&&(S=S.negate()),k&&(T=T.negate()),T=new h(t.mul(T.px,y.beta),T.py,T.pz),S.add(T)}multiply(g){let{endo:y,n:b}=e;bt("scalar",g,ht,b);let w,x;if(y){let{k1neg:_,k1:k,k2neg:E,k2:S}=y.splitScalar(g),{p:T,f:V}=this.wNAF(k),{p:L,f:O}=this.wNAF(S);T=p.constTimeNegate(_,T),L=p.constTimeNegate(E,L),L=new h(t.mul(L.px,y.beta),L.py,L.pz),w=T.add(L),x=V.add(O)}else{let{p:_,f:k}=this.wNAF(g);w=_,x=k}return h.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(g,y,b){let w=h.BASE,x=(k,E)=>E===Gn||E===ht||!k.equals(w)?k.multiplyUnsafe(E):k.multiply(E),_=x(this,y).add(x(g,b));return _.is0()?void 0:_}toAffine(g){return u(this,g)}isTorsionFree(){let{h:g,isTorsionFree:y}=e;if(g===ht)return!0;if(y)return y(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:g,clearCofactor:y}=e;return g===ht?this:y?y(h,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return Gr("isCompressed",g),this.assertValidity(),o(h,this,g)}toHex(g=!0){return Gr("isCompressed",g),Bn(this.toRawBytes(g))}}h.BASE=new h(e.Gx,e.Gy,t.ONE),h.ZERO=new h(t.ZERO,t.ONE,t.ZERO);let f=e.nBitLength,p=Jl(h,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:a}}function XS(r){let e=Ra(r);return Ir(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function L8(r){let e=XS(r),{Fp:t,n}=e,o=t.BYTES+1,i=2*t.BYTES+1;function s(D){return Te(D,n)}function a(D){return jl(D,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:d}=YS({...e,toBytes(D,N,I){let A=N.toAffine(),R=t.toBytes(A.x),C=Un;return Gr("isCompressed",I),I?C(Uint8Array.from([N.hasEvenY()?2:3]),R):C(Uint8Array.from([4]),R,t.toBytes(A.y))},fromBytes(D){let N=D.length,I=D[0],A=D.subarray(1);if(N===o&&(I===2||I===3)){let R=On(A);if(!Ca(R,ht,t.ORDER))throw new Error("Point is not on curve");let C=u(R),H;try{H=t.sqrt(C)}catch(ce){let se=ce instanceof Error?": "+ce.message:"";throw new Error("Point is not on curve"+se)}let z=(H&ht)===ht;return(I&1)===1!==z&&(H=t.neg(H)),{x:R,y:H}}else if(N===i&&I===4){let R=t.fromBytes(A.subarray(0,t.BYTES)),C=t.fromBytes(A.subarray(t.BYTES,2*t.BYTES));return{x:R,y:C}}else{let R=o,C=i;throw new Error("invalid Point, expected length of "+R+", or uncompressed "+C+", got "+N)}}}),h=D=>Bn(xo(D,e.nByteLength));function f(D){let N=n>>ht;return D>N}function p(D){return f(D)?s(-D):D}let m=(D,N,I)=>On(D.slice(N,I));class g{constructor(N,I,A){this.r=N,this.s=I,this.recovery=A,this.assertValidity()}static fromCompact(N){let I=e.nByteLength;return N=De("compactSignature",N,I*2),new g(m(N,0,I),m(N,I,2*I))}static fromDER(N){let{r:I,s:A}=Wn.toSig(De("DER",N));return new g(I,A)}assertValidity(){bt("r",this.r,ht,n),bt("s",this.s,ht,n)}addRecoveryBit(N){return new g(this.r,this.s,N)}recoverPublicKey(N){let{r:I,s:A,recovery:R}=this,C=k(De("msgHash",N));if(R==null||![0,1,2,3].includes(R))throw new Error("recovery id invalid");let H=R===2||R===3?I+e.n:I;if(H>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let z=R&1?"03":"02",X=c.fromHex(z+h(H)),ce=a(H),se=s(-C*ce),fe=s(A*ce),ve=c.BASE.multiplyAndAddUnsafe(X,se,fe);if(!ve)throw new Error("point at infinify");return ve.assertValidity(),ve}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return ui(this.toDERHex())}toDERHex(){return Wn.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return ui(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let y={isValidPrivateKey(D){try{return l(D),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let D=m2(e.n);return v6(e.randomBytes(D),e.n)},precompute(D=8,N=c.BASE){return N._setWindowSize(D),N.multiply(BigInt(3)),N}};function b(D,N=!0){return c.fromPrivateKey(D).toRawBytes(N)}function w(D){let N=bo(D),I=typeof D=="string",A=(N||I)&&D.length;return N?A===o||A===i:I?A===2*o||A===2*i:D instanceof c}function x(D,N,I=!0){if(w(D))throw new Error("first arg must be private key");if(!w(N))throw new Error("second arg must be public key");return c.fromHex(N).multiply(l(D)).toRawBytes(I)}let _=e.bits2int||function(D){if(D.length>8192)throw new Error("input is too large");let N=On(D),I=D.length*8-e.nBitLength;return I>0?N>>BigInt(I):N},k=e.bits2int_modN||function(D){return s(_(D))},E=Pa(e.nBitLength);function S(D){return bt("num < 2^"+e.nBitLength,D,Gn,E),xo(D,e.nByteLength)}function T(D,N,I=V){if(["recovered","canonical"].some(Be=>Be in I))throw new Error("sign() legacy options not supported");let{hash:A,randomBytes:R}=e,{lowS:C,prehash:H,extraEntropy:z}=I;C==null&&(C=!0),D=De("msgHash",D),D8(I),H&&(D=De("prehashed msgHash",A(D)));let X=k(D),ce=l(N),se=[S(ce),S(X)];if(z!=null&&z!==!1){let Be=z===!0?R(t.BYTES):z;se.push(De("extraEntropy",Be))}let fe=Un(...se),ve=X;function Le(Be){let $e=_(Be);if(!d($e))return;let kt=a($e),Yt=c.BASE.multiply($e).toAffine(),Ut=s(Yt.x);if(Ut===Gn)return;let fn=s(kt*s(ve+Ut*ce));if(fn===Gn)return;let Pn=(Yt.x===Ut?0:2)|Number(Yt.y&ht),ba=fn;return C&&f(fn)&&(ba=p(fn),Pn^=1),new g(Ut,ba,Pn)}return{seed:fe,k2sig:Le}}let V={lowS:e.lowS,prehash:!1},L={lowS:e.lowS,prehash:!1};function O(D,N,I=V){let{seed:A,k2sig:R}=T(D,N,I),C=e;return u2(C.hash.outputLen,C.nByteLength,C.hmac)(A,R)}c.BASE._setWindowSize(8);function B(D,N,I,A=L){let R=D;N=De("msgHash",N),I=De("publicKey",I);let{lowS:C,prehash:H,format:z}=A;if(D8(A),"strict"in A)throw new Error("options.strict was renamed to lowS");if(z!==void 0&&z!=="compact"&&z!=="der")throw new Error("format must be compact or der");let X=typeof R=="string"||bo(R),ce=!X&&!z&&typeof R=="object"&&R!==null&&typeof R.r=="bigint"&&typeof R.s=="bigint";if(!X&&!ce)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let se,fe;try{if(ce&&(se=new g(R.r,R.s)),X){try{z!=="compact"&&(se=g.fromDER(R))}catch(Pn){if(!(Pn instanceof Wn.Err))throw Pn}!se&&z!=="der"&&(se=g.fromCompact(R))}fe=c.fromHex(I)}catch{return!1}if(!se||C&&se.hasHighS())return!1;H&&(N=e.hash(N));let{r:ve,s:Le}=se,Be=k(N),$e=a(Le),kt=s(Be*$e),Yt=s(ve*$e),Ut=c.BASE.multiplyAndAddUnsafe(fe,kt,Yt)?.toAffine();return Ut?s(Ut.x)===ve:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:x,sign:O,verify:B,ProjectivePoint:c,Signature:g,utils:y}}function jS(r){return{hash:r,hmac:(e,...t)=>To(r,e,n2(...t)),randomBytes:ci}}function B8(r,e){let t=n=>L8({...r,...jS(n)});return{...t(e),create:t}}var U8=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),O8=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ZS=BigInt(1),M2=BigInt(2),M8=(r,e)=>(r+e/M2)/e;function JS(r){let e=U8,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=Ue(u,t,e)*u%e,h=Ue(d,t,e)*u%e,f=Ue(h,M2,e)*l%e,p=Ue(f,o,e)*f%e,m=Ue(p,i,e)*p%e,g=Ue(m,a,e)*m%e,y=Ue(g,c,e)*g%e,b=Ue(y,a,e)*m%e,w=Ue(b,t,e)*u%e,x=Ue(w,s,e)*p%e,_=Ue(x,n,e)*l%e,k=Ue(_,M2,e);if(!U2.eql(U2.sqr(k),r))throw new Error("Cannot find square root");return k}var U2=vo(U8,void 0,void 0,{sqrt:JS}),Cr=B8({a:BigInt(0),b:BigInt(7),Fp:U2,n:O8,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=O8,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-ZS*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,s=BigInt("0x100000000000000000000000000000000"),a=M8(i*r,e),c=M8(-n*r,e),l=Te(r-a*t-c*o,e),u=Te(-a*n-c*i,e),d=l>s,h=u>s;if(d&&(l=e-l),h&&(u=e-u),l>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:d,k1:l,k2neg:h,k2:u}}}},Tr),RO=BigInt(0);var DO=Cr.ProjectivePoint;function F2(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function F8(r,e){let t=lt.digest(e instanceof Uint8Array?e:e.subarray());if(F2(t))return t.then(({digest:n})=>Cr.sign(n,r).toDERRawBytes()).catch(n=>{throw new za(String(n))});try{return Cr.sign(t.digest,r).toDERRawBytes()}catch(n){throw new za(String(n))}}function V8(r,e,t){let n=lt.digest(t instanceof Uint8Array?t:t.subarray());if(F2(n))return n.then(({digest:o})=>Cr.verify(e,o,r)).catch(o=>{throw new Wa(String(o))});try{return Cr.verify(e,n.digest,r)}catch(o){throw new Wa(String(o))}}var Ya=class{type="secp256k1";raw;_key;constructor(e){this._key=H8(e),this.raw=$8(this._key)}toMultihash(){return Zt.digest(Lt(this))}toCID(){return j.createV1(114,this.toMultihash())}toString(){return Ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:oe(this.raw,e.raw)}verify(e,t){return V8(this._key,t,e)}},Xa=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=K8(e),this.publicKey=new Ya(t??q8(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:oe(this.raw,e.raw)}sign(e){return F8(this.raw,e)}};function V2(r){return new Xa(r)}function $2(r){return new Ya(r)}async function z8(){let r=eA();return new Xa(r)}function $8(r){return Cr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function K8(r){try{return Cr.getPublicKey(r,!0),r}catch(e){throw new xa(String(e))}}function H8(r){try{return Cr.ProjectivePoint.fromHex(r),r}catch(e){throw new Rn(String(e))}}function q8(r){try{return Cr.getPublicKey(r,!0)}catch(e){throw new xa(String(e))}}function eA(){return Cr.utils.randomPrivateKey()}async function Qu(r,e){if(r==="Ed25519")return B6();if(r==="secp256k1")return z8();if(r==="RSA")return B2(e??2048);throw new Vr}function tt(r){let{Type:e,Data:t}=bn.decode(r),n=t??new Uint8Array;switch(e){case Qe.RSA:return L2(n);case Qe.Ed25519:return S2(n);case Qe.secp256k1:return $2(n);default:throw new Vr}}function Yu(r){let{Type:e,Data:t}=bn.decode(r.digest),n=t??new Uint8Array;switch(e){case Qe.Ed25519:return S2(n);case Qe.secp256k1:return $2(n);default:throw new Vr}}function Lt(r){return bn.encode({Type:Qe[r.type],Data:r.raw})}function W8(r){let e=Oa.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Qe.RSA:return Wu(t);case Qe.Ed25519:return E2(t);case Qe.secp256k1:return V2(t);default:throw new Vr}}function G8(r){return r.byteLength===64?E2(r):r.byteLength===32?V2(r):Wu(r)}function Is(r){return Oa.encode({Type:Qe[r.type],Data:r.raw})}var Q8=Symbol.for("nodejs.util.inspect.custom"),tA=114,ja=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[hl]=!0;toString(){return this.string==null&&(this.string=Ee.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return j.createV1(tA,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return oe(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return oe(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Q8](){return`PeerId(${this.toString()})`}},Za=class extends ja{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ja=class extends ja{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},ec=class extends ja{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},rA=2336,tc=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Zt.digest(M(this.url))}[Q8](){return`PeerId(${this.url})`}[hl]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return j.createV1(rA,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=$(e)),e.toString()===this.toString())}};var nA=114,Y8=2336;function Fe(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Ie(Ee.decode(`z${r}`));else{if(e==null)throw new P('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Ie(e.decode(r))}return ot(t)}function Sn(r){if(r.type==="Ed25519")return new Ja({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new ec({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Za({multihash:r.toCID().multihash,publicKey:r});throw new Vr}function X8(r){return Sn(r.publicKey)}function ot(r){if(iA(r))return new Za({multihash:r});if(oA(r))try{let e=Yu(r);if(e.type==="Ed25519")return new Ja({multihash:r,publicKey:e});if(e.type==="secp256k1")return new ec({multihash:r,publicKey:e})}catch{let t=$(r.digest);return new tc(new URL(t))}throw new co("Supplied PeerID Multihash is invalid")}function An(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==nA&&r.code!==Y8)throw new wl("Supplied PeerID CID is invalid");if(r.code===Y8){let e=$(r.multihash.digest);return new tc(new URL(e))}return ot(r.multihash)}function oA(r){return r.code===Zt.code}function iA(r){return r.code===lt.code}function mi(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function Xu(r){let e=Ie(Ee.decode(`z${r}`));return ot(e)}var pt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return mi(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return mi(this.map.values(),e=>e.key)}values(){return mi(this.map.values(),e=>e.value)}get size(){return this.map.size}};var zt=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return mi(this.set.entries(),e=>{let t=Xu(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Xu(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return mi(this.set.values(),e=>Xu(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};function K2(){return new zt}function j8(r,e,t,n){ii(r);let o=h6({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(po(i),po(s),po(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Wr(e),l=Wr(t),u=new Uint8Array(s),d=To.create(r,c),h=d._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:a,DK:u,PRF:d,PRFSalt:h}}function Z8(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}function J8(r,e,t,n){let{c:o,dkLen:i,DK:s,PRF:a,PRFSalt:c}=j8(r,e,t,n),l,u=new Uint8Array(4),d=ai(u),h=new Uint8Array(a.outputLen);for(let f=1,p=0;p<i;f++,p+=a.outputLen){let m=s.subarray(p,p+a.outputLen);d.setInt32(0,f,!1),(l=c._cloneInto(l)).update(u).digestInto(h),m.set(h.subarray(0,m.length));for(let g=1;g<o;g++){a._cloneInto(l).update(h).digestInto(h);for(let y=0;y<m.length;y++)m[y]^=h[y]}}return Z8(a,c,s,l,h)}async function ju(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=j8(r,e,t,n),u,d=new Uint8Array(4),h=ai(d),f=new Uint8Array(c.outputLen);for(let p=1,m=0;m<i;p++,m+=c.outputLen){let g=a.subarray(m,m+c.outputLen);h.setInt32(0,p,!1),(u=l._cloneInto(u)).update(d).digestInto(f),g.set(f.subarray(0,g.length)),await d6(o-1,s,()=>{c._cloneInto(u).update(f).digestInto(f);for(let y=0;y<g.length;y++)g[y]^=f[y]})}return Z8(c,l,a,u,f)}var rc=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),_o=new Uint32Array(80),H2=class extends mo{constructor(){super(64,20,8,!1),this.A=rc[0]|0,this.B=rc[1]|0,this.C=rc[2]|0,this.D=rc[3]|0,this.E=rc[4]|0}get(){let{A:e,B:t,C:n,D:o,E:i}=this;return[e,t,n,o,i]}set(e,t,n,o,i){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0}process(e,t){for(let c=0;c<16;c++,t+=4)_o[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)_o[c]=ql(_o[c-3]^_o[c-8]^_o[c-14]^_o[c-16],1);let{A:n,B:o,C:i,D:s,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=zl(o,i,s),u=1518500249):c<40?(l=o^i^s,u=1859775393):c<60?(l=Wl(o,i,s),u=2400959708):(l=o^i^s,u=3395469782);let d=ql(n,5)+l+a+u+_o[c]|0;a=s,s=i,i=ql(o,30),o=n,n=d}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,o,i,s,a)}roundClean(){_o.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}},eg=ms(()=>new H2);var tg={sha1:eg,"sha2-256":Tr,"sha2-512":wo};function nc(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(tg).join(" / ");throw new P(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let i=tg[o],s=J8(i,r,e,{c:t,dkLen:n});return nt.encode(s).substring(1)}var q2=64,jr=class{fp;h;seed;constructor(e,t,n,o=2){if(o>q2)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=ae(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?oe(this.fp,e.fp):!1}};function gi(r,e){return Math.floor(Math.random()*(e-r))+r}var yi=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof jr))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof jr))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof jr))throw new TypeError("Invalid Fingerprint");let t=gi(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof jr))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var z2={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},ig={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},sg=new globalThis.TextEncoder;function sA(r,e){let t=z2[e],n=ig[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function aA(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=z2[e],o=ig[e],i=r;for(;i.length>0;){let s=sg.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function W2(r,{size:e=32,utf8Buffer:t}={}){if(!z2[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return aA(r,e,t);r=sg.encode(r)}return sA(r,e)}var cA=ur(og(),1);var ic={hash:r=>Number(W2(r,{size:32})),hashV:(r,e)=>lA(ic.hash(r,e))};function lA(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),M(e,"base16")}var uA=500,sc=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??ic,this.seed=e.seed??gi(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=M(e));let t=new jr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new yi(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new yi(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[gi(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new yi(this.bucketSize));for(let a=0;a<uA;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new yi(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=M(e));let t=new jr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=M(e));let t=new jr(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},dA={1:.5,2:.84,4:.95,8:.98};function fA(r=.001){return r>.002?2:r>1e-5?4:8}function ag(r,e=.001){let t=fA(e),n=dA[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),q2);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var Ju=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??ic,this.seed=e.seed??gi(0,Math.pow(2,10)),this.filterSeries=[new sc({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=M(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new sc({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function rr(r,e=.001,t){return new Ju({...ag(r,e),...t??{}})}var ed=class{filter;constructor(e,t){this.filter=rr(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function G2(r,e=.001){return new ed(r,e)}var Q2=class extends pt{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 ac(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Q2({name:e,metrics:t}):n=new pt,n}var Qn=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=nt.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=nt.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=nt.encode(e.multihash.bytes);this.blocks.set(n,t)}};function hA(r){let e=new Uint8Array(r.reduce((n,o)=>n+me(o),0)),t=0;for(let n of r)e=Ke(n,e,t),t+=me(n);return e}var cg=hA;function Y2(r){return cg([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var td=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 Qn,n=new Set;for(let[o,i]of this.wants.entries())try{let s=await this.blockstore.get(i.cid,e);i.wantType===Je.WantHave?s.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:s,prefix:Y2(i.cid)})):(this.log("sending have for %c",i.cid),t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Ar.HaveBlock})):(this.log("sending block for %c",i.cid),n.add(o),t.addBlock(i.cid,{data:s,prefix:Y2(i.cid)}))}catch(s){if(s.name!=="NotFoundError")throw s;if(this.log("do not have block for %c",i.cid),!i.sendDontHave||i.sentDontHave===!0)continue;i.sentDontHave=!0,t.addBlockPresence(i.cid,{cid:i.cid.bytes,type:Ar.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,i)=>o+i.data.byteLength,0));for(let o of n)this.wants.delete(o)}}};var rd=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=ac({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 td({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,i)=>o+i.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let o of t.wantlist.entries){let i=j.decode(o.cid),s=$(i.multihash.bytes,"base64");o.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,i),n.wants.delete(s)):(o.wantType===Je.WantHave?this.log("peer %p wanted block presence for %c",e,i):this.log("peer %p wanted block for %c",e,i),n.wants.set(s,{cid:i,priority:o.priority,wantType:o.wantType??Je.WantBlock,sendDontHave:o.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=$(e.multihash.bytes,"base64"),o=[];for(let i of this.ledgerMap.values())i.wants.has(n)&&o.push(i);await Promise.all(o.map(async i=>i.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};function pA(r,e){try{if(typeof r=="string"&&r.length>0)return mA(r);if(typeof r=="number"&&isFinite(r))return e?.long?yA(r):gA(r);throw new Error("Value is not a string or number.")}catch(t){let n=wA(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function mA(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var od=pA;function gA(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function yA(r){let e=Math.abs(r);return e>=864e5?nd(r,e,864e5,"day"):e>=36e5?nd(r,e,36e5,"hour"):e>=6e4?nd(r,e,6e4,"minute"):e>=1e3?nd(r,e,1e3,"second"):`${r} ms`}function nd(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function wA(r){return typeof r=="object"&&r!==null&&"message"in r}function X2(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=s,t.humanize=od,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let h=0;h<u.length;h++)d=(d<<5)-d+u.charCodeAt(h),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u){let d,h=null,f,p;function m(...g){if(!m.enabled)return;let y=m,b=Number(new Date),w=b-(d||b);y.diff=w,y.prev=d,y.curr=b,d=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let x=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(k,E)=>{if(k==="%%")return"%";x++;let S=t.formatters[E];if(typeof S=="function"){let T=g[x];k=S.call(y,T),g.splice(x,1),x--}return k}),t.formatArgs.call(y,g),(y.log||t.log).apply(y,g)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(f!==t.namespaces&&(f=t.namespaces,p=t.enabled(u)),p),set:g=>{h=g}}),typeof t.init=="function"&&t.init(m),m}function n(u,d){let h=t(this.namespace+(typeof d>"u"?":":d)+u);return h.log=this.log,h}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,h=(typeof u=="string"?u:"").split(/[\s,]+/),f=h.length;for(d=0;d<f;d++)h[d]&&(u=h[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function i(){let u=[...t.names.map(a),...t.skips.map(a).map(d=>"-"+d)].join(",");return t.enable(""),u}function s(u){if(u[u.length-1]==="*")return!0;let d,h;for(d=0,h=t.skips.length;d<h;d++)if(t.skips[d].test(u))return!1;for(d=0,h=t.names.length;d<h;d++)if(t.names[d].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var id=IA(),bA=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function xA(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function vA(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+od(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var EA=console.debug??console.log??(()=>{});function SA(r){try{r?id?.setItem("debug",r):id?.removeItem("debug")}catch{}}function AA(){let r;try{r=id?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function IA(){try{return localStorage}catch{}}function TA(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var lg=X2({formatArgs:vA,save:SA,load:AA,useColors:xA,setupFormatters:TA,colors:bA,storage:id,log:EA});var nr=lg;nr.formatters.b=r=>r==null?"undefined":Ee.baseEncode(r);nr.formatters.t=r=>r==null?"undefined":ct.baseEncode(r);nr.formatters.m=r=>r==null?"undefined":nt.baseEncode(r);nr.formatters.p=r=>r==null?"undefined":r.toString();nr.formatters.c=r=>r==null?"undefined":r.toString();nr.formatters.k=r=>r==null?"undefined":r.toString();nr.formatters.a=r=>r==null?"undefined":r.toString();nr.formatters.e=r=>r==null?"undefined":ug(r.stack)??ug(r.message)??r.toString();function _A(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 ko(){return{forComponent(r){return pr(r)}}}function pr(r){let e=_A(`${r}:trace`);return nr.enabled(`${r}:trace`)&&nr.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=nr(`${r}:trace`)),Object.assign(nr(r),{error:nr(`${r}:error`),trace:e})}function ug(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Z2=ur(fg(),1);var lc=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},J2=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},hg=r=>globalThis.DOMException===void 0?new J2(r):new DOMException(r),pg=r=>{let e=r.reason===void 0?hg("This operation was aborted."):r.reason;return e instanceof Error?e:hg(e)};function Zr(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,a,l=new Promise((u,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:f}=e;f.aborted&&d(pg(f)),a=()=>{d(pg(f))},f.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,d);return}let h=new lc;s=i.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(f){d(f)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?d(o):(h.message=o??`Promise timed out after ${t} milliseconds`,d(h))},t),(async()=>{try{u(await r)}catch(f){d(f)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},l}function ep(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var uc=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=ep(this.#e,n,(i,s)=>s.priority-i.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 In=class extends Z2.default{#e;#t;#r=0;#o;#a;#l=0;#i;#u;#n;#m;#s=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:uc,...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#b(){return this.#t||this.#r<this.#o}get#x(){return this.#s<this.#d}#v(){this.#s--,this.#f(),this.emit("next")}#E(){this.#w(),this.#y(),this.#u=void 0}get#S(){let e=Date.now();if(this.#i===void 0){let t=this.#l-e;if(t<0)this.#r=this.#e?this.#s:0;else return this.#u===void 0&&(this.#u=setTimeout(()=>{this.#E()},t)),!0}return!1}#f(){if(this.#n.size===0)return this.#i&&clearInterval(this.#i),this.#i=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#c){let e=!this.#S;if(this.#b&&this.#x){let t=this.#n.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#i!==void 0||(this.#i=setInterval(()=>{this.#w()},this.#a),this.#l=Date.now()+this.#a)}#w(){this.#r===0&&this.#s===0&&this.#i&&(clearInterval(this.#i),this.#i=void 0),this.#r=this.#e?this.#s: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#A(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.#s++,this.#r++;try{t.signal?.throwIfAborted();let i=e({signal:t.signal});t.timeout&&(i=Zr(Promise.resolve(i),{milliseconds:t.timeout})),t.signal&&(i=Promise.race([i,this.#A(t.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof lc&&!t.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#v()}},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.#s===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.#s}get isPaused(){return this.#c}};function ad(r){let e=[mr.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var tp=60;function cd(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:mr[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:mr[e.type],TTL:e.TTL??e.ttl??tp,data:e.data instanceof Uint8Array?$(e.data):e.data}))}}var PA=4;function rp(r,e={}){let t=new In({concurrency:e.queryConcurrency??PA});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),ad(o.types).forEach(a=>{i.append("type",mr[a])}),o.onProgress?.(new G("dns:query",{detail:n}));let s=await t.add(async()=>{let a=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=cd(await a.json());return o.onProgress?.(new G("dns:response",{detail:c})),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function mg(){return[rp("https://cloudflare-dns.com/dns-query"),rp("https://dns.google/resolve")]}var wg=ur(yg(),1);var np=class{lru;constructor(e){this.lru=(0,wg.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return cd({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:mr[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??tp)*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 bg(r){return new np(r)}var RA=1e3,ld=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=bg(e.cacheSize??RA),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["."]=mg())}async query(e,t={}){let n=ad(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new G("dns:cache",{detail:o})),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new G("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var mr;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(mr||(mr={}));function ud(r={}){return new ld(r)}var DA=["string","number","bigint","symbol"],NA=["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 xg(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(DA.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(LA(r))return"Buffer";let t=BA(r);return t||"Object"}function LA(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function BA(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(NA.includes(e))return e}var v=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}};v.uint=new v(0,"uint",!0);v.negint=new v(1,"negint",!0);v.bytes=new v(2,"bytes",!0);v.string=new v(3,"string",!0);v.array=new v(4,"array",!1);v.map=new v(5,"map",!1);v.tag=new v(6,"tag",!1);v.float=new v(7,"float",!0);v.false=new v(7,"false",!0);v.true=new v(7,"true",!0);v.null=new v(7,"null",!0);v.undefined=new v(7,"undefined",!0);v.break=new v(7,"break",!0);var U=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 Ts=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",OA=new TextDecoder,MA=new TextEncoder;function dd(r){return Ts&&globalThis.Buffer.isBuffer(r)}function dc(r){return r instanceof Uint8Array?dd(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Ag=Ts?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):Eg(r,e,t):(r,e,t)=>t-e>64?OA.decode(r.subarray(e,t)):Eg(r,e,t),fd=Ts?r=>r.length>64?globalThis.Buffer.from(r):vg(r):r=>r.length>64?MA.encode(r):vg(r),Tn=r=>Uint8Array.from(r),_s=Ts?(r,e,t)=>dd(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Ig=Ts?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),dc(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},Tg=Ts?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function _g(r,e){if(dd(r)&&dd(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 vg(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 Eg(r,e,t){let n=[];for(;e<t;){let o=r[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=t){let a,c,l,u;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[e+1],(a&192)===128&&(u=(o&31)<<6|a&63,u>127&&(i=u));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(u=(o&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(i=u))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return op(n)}var Sg=4096;function op(r){let e=r.length;if(e<=Sg)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Sg));return t}var UA=256,fc=class{constructor(e=UA){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=Tg(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=_s(n,0,this.cursor)}else t=Ig(this.chunks,this.cursor);return e&&this.reset(),t}};var Z="CBOR decode error:",Yn="CBOR encode error:",hc=[];hc[23]=1;hc[24]=2;hc[25]=3;hc[26]=5;hc[27]=9;function Xn(r,e,t){if(r.length-e<t)throw new Error(`${Z} not enough data for type`)}var mt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function gr(r,e,t){Xn(r,e,1);let n=r[e];if(t.strict===!0&&n<mt[0])throw new Error(`${Z} integer encoded in more bytes than necessary (strict decode)`);return n}function yr(r,e,t){Xn(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<mt[1])throw new Error(`${Z} integer encoded in more bytes than necessary (strict decode)`);return n}function wr(r,e,t){Xn(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<mt[2])throw new Error(`${Z} integer encoded in more bytes than necessary (strict decode)`);return n}function br(r,e,t){Xn(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],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<mt[3])throw new Error(`${Z} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${Z} integers outside of the safe integer range are not supported`)}function kg(r,e,t,n){return new U(v.uint,gr(r,e+1,n),2)}function Cg(r,e,t,n){return new U(v.uint,yr(r,e+1,n),3)}function Pg(r,e,t,n){return new U(v.uint,wr(r,e+1,n),5)}function Rg(r,e,t,n){return new U(v.uint,br(r,e+1,n),9)}function Pr(r,e){return vt(r,0,e.value)}function vt(r,e,t){if(t<mt[0]){let n=Number(t);r.push([e|n])}else if(t<mt[1]){let n=Number(t);r.push([e|24,n])}else if(t<mt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<mt[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<mt[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${Z} encountered BigInt larger than allowable range`)}}Pr.encodedSize=function(e){return vt.encodedSize(e.value)};vt.encodedSize=function(e){return e<mt[0]?1:e<mt[1]?2:e<mt[2]?3:e<mt[3]?5:9};Pr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Dg(r,e,t,n){return new U(v.negint,-1-gr(r,e+1,n),2)}function Ng(r,e,t,n){return new U(v.negint,-1-yr(r,e+1,n),3)}function Lg(r,e,t,n){return new U(v.negint,-1-wr(r,e+1,n),5)}var ip=BigInt(-1),Bg=BigInt(1);function Og(r,e,t,n){let o=br(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new U(v.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${Z} integers outside of the safe integer range are not supported`);return new U(v.negint,ip-BigInt(o),9)}function hd(r,e){let t=e.value,n=typeof t=="bigint"?t*ip-Bg:t*-1-1;vt(r,e.type.majorEncoded,n)}hd.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*ip-Bg:t*-1-1;return n<mt[0]?1:n<mt[1]?2:n<mt[2]?3:n<mt[3]?5:9};hd.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function pc(r,e,t,n){Xn(r,e,t+n);let o=_s(r,e+t,e+t+n);return new U(v.bytes,o,t+n)}function Mg(r,e,t,n){return pc(r,e,1,t)}function Ug(r,e,t,n){return pc(r,e,2,gr(r,e+1,n))}function Fg(r,e,t,n){return pc(r,e,3,yr(r,e+1,n))}function Vg(r,e,t,n){return pc(r,e,5,wr(r,e+1,n))}function $g(r,e,t,n){let o=br(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Z} 64-bit integer bytes lengths not supported`);return pc(r,e,9,o)}function pd(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===v.string?fd(r.value):r.value),r.encodedBytes}function ks(r,e){let t=pd(e);vt(r,e.type.majorEncoded,t.length),r.push(t)}ks.encodedSize=function(e){let t=pd(e);return vt.encodedSize(t.length)+t.length};ks.compareTokens=function(e,t){return VA(pd(e),pd(t))};function VA(r,e){return r.length<e.length?-1:r.length>e.length?1:_g(r,e)}function mc(r,e,t,n,o){let i=t+n;Xn(r,e,i);let s=new U(v.string,Ag(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=_s(r,e+t,e+i)),s}function Kg(r,e,t,n){return mc(r,e,1,t,n)}function Hg(r,e,t,n){return mc(r,e,2,gr(r,e+1,n),n)}function qg(r,e,t,n){return mc(r,e,3,yr(r,e+1,n),n)}function zg(r,e,t,n){return mc(r,e,5,wr(r,e+1,n),n)}function Wg(r,e,t,n){let o=br(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Z} 64-bit integer string lengths not supported`);return mc(r,e,9,o,n)}var Gg=ks;function Cs(r,e,t,n){return new U(v.array,n,t)}function Qg(r,e,t,n){return Cs(r,e,1,t)}function Yg(r,e,t,n){return Cs(r,e,2,gr(r,e+1,n))}function Xg(r,e,t,n){return Cs(r,e,3,yr(r,e+1,n))}function jg(r,e,t,n){return Cs(r,e,5,wr(r,e+1,n))}function Zg(r,e,t,n){let o=br(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Z} 64-bit integer array lengths not supported`);return Cs(r,e,9,o)}function Jg(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Z} indefinite length items not allowed`);return Cs(r,e,1,1/0)}function md(r,e){vt(r,v.array.majorEncoded,e.value)}md.compareTokens=Pr.compareTokens;md.encodedSize=function(e){return vt.encodedSize(e.value)};function Ps(r,e,t,n){return new U(v.map,n,t)}function e5(r,e,t,n){return Ps(r,e,1,t)}function t5(r,e,t,n){return Ps(r,e,2,gr(r,e+1,n))}function r5(r,e,t,n){return Ps(r,e,3,yr(r,e+1,n))}function n5(r,e,t,n){return Ps(r,e,5,wr(r,e+1,n))}function o5(r,e,t,n){let o=br(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Z} 64-bit integer map lengths not supported`);return Ps(r,e,9,o)}function i5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Z} indefinite length items not allowed`);return Ps(r,e,1,1/0)}function gd(r,e){vt(r,v.map.majorEncoded,e.value)}gd.compareTokens=Pr.compareTokens;gd.encodedSize=function(e){return vt.encodedSize(e.value)};function s5(r,e,t,n){return new U(v.tag,t,1)}function a5(r,e,t,n){return new U(v.tag,gr(r,e+1,n),2)}function c5(r,e,t,n){return new U(v.tag,yr(r,e+1,n),3)}function l5(r,e,t,n){return new U(v.tag,wr(r,e+1,n),5)}function u5(r,e,t,n){return new U(v.tag,br(r,e+1,n),9)}function yd(r,e){vt(r,v.tag.majorEncoded,e.value)}yd.compareTokens=Pr.compareTokens;yd.encodedSize=function(e){return vt.encodedSize(e.value)};var WA=20,GA=21,QA=22,YA=23;function d5(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Z} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new U(v.null,null,1):new U(v.undefined,void 0,1)}function f5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Z} indefinite length items not allowed`);return new U(v.break,void 0,1)}function sp(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Z} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Z} Infinity values are not supported`)}return new U(v.float,r,e)}function h5(r,e,t,n){return sp(ap(r,e+1),3,n)}function p5(r,e,t,n){return sp(cp(r,e+1),5,n)}function m5(r,e,t,n){return sp(b5(r,e+1),9,n)}function wd(r,e,t){let n=e.value;if(n===!1)r.push([v.float.majorEncoded|WA]);else if(n===!0)r.push([v.float.majorEncoded|GA]);else if(n===null)r.push([v.float.majorEncoded|QA]);else if(n===void 0)r.push([v.float.majorEncoded|YA]);else{let o,i=!1;(!t||t.float64!==!0)&&(y5(n),o=ap(Jr,1),n===o||Number.isNaN(n)?(Jr[0]=249,r.push(Jr.slice(0,3)),i=!0):(w5(n),o=cp(Jr,1),n===o&&(Jr[0]=250,r.push(Jr.slice(0,5)),i=!0))),i||(XA(n),o=b5(Jr,1),Jr[0]=251,r.push(Jr.slice(0,9)))}}wd.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=ap(Jr,1);if(n===o||Number.isNaN(n))return 3;if(w5(n),o=cp(Jr,1),n===o)return 5}return 9};var g5=new ArrayBuffer(9),Rr=new DataView(g5,1),Jr=new Uint8Array(g5,0);function y5(r){if(r===1/0)Rr.setUint16(0,31744,!1);else if(r===-1/0)Rr.setUint16(0,64512,!1);else if(Number.isNaN(r))Rr.setUint16(0,32256,!1);else{Rr.setFloat32(0,r);let e=Rr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Rr.setUint16(0,31744,!1);else if(t===0)Rr.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Rr.setUint16(0,0):o<-14?Rr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Rr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function ap(r,e){if(r.length-e<2)throw new Error(`${Z} 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,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function w5(r){Rr.setFloat32(0,r,!1)}function cp(r,e){if(r.length-e<4)throw new Error(`${Z} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function XA(r){Rr.setFloat64(0,r,!1)}function b5(r,e){if(r.length-e<8)throw new Error(`${Z} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}wd.compareTokens=Pr.compareTokens;function Se(r,e,t){throw new Error(`${Z} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function bd(r){return()=>{throw new Error(`${Z} ${r}`)}}var K=[];for(let r=0;r<=23;r++)K[r]=Se;K[24]=kg;K[25]=Cg;K[26]=Pg;K[27]=Rg;K[28]=Se;K[29]=Se;K[30]=Se;K[31]=Se;for(let r=32;r<=55;r++)K[r]=Se;K[56]=Dg;K[57]=Ng;K[58]=Lg;K[59]=Og;K[60]=Se;K[61]=Se;K[62]=Se;K[63]=Se;for(let r=64;r<=87;r++)K[r]=Mg;K[88]=Ug;K[89]=Fg;K[90]=Vg;K[91]=$g;K[92]=Se;K[93]=Se;K[94]=Se;K[95]=bd("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)K[r]=Kg;K[120]=Hg;K[121]=qg;K[122]=zg;K[123]=Wg;K[124]=Se;K[125]=Se;K[126]=Se;K[127]=bd("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)K[r]=Qg;K[152]=Yg;K[153]=Xg;K[154]=jg;K[155]=Zg;K[156]=Se;K[157]=Se;K[158]=Se;K[159]=Jg;for(let r=160;r<=183;r++)K[r]=e5;K[184]=t5;K[185]=r5;K[186]=n5;K[187]=o5;K[188]=Se;K[189]=Se;K[190]=Se;K[191]=i5;for(let r=192;r<=215;r++)K[r]=s5;K[216]=a5;K[217]=c5;K[218]=l5;K[219]=u5;K[220]=Se;K[221]=Se;K[222]=Se;K[223]=Se;for(let r=224;r<=243;r++)K[r]=bd("simple values are not supported");K[244]=Se;K[245]=Se;K[246]=Se;K[247]=d5;K[248]=bd("simple values are not supported");K[249]=h5;K[250]=p5;K[251]=m5;K[252]=Se;K[253]=Se;K[254]=Se;K[255]=f5;var en=[];for(let r=0;r<24;r++)en[r]=new U(v.uint,r,1);for(let r=-1;r>=-24;r--)en[31-r]=new U(v.negint,r,1);en[64]=new U(v.bytes,new Uint8Array(0),1);en[96]=new U(v.string,"",1);en[128]=new U(v.array,0,1);en[160]=new U(v.map,0,1);en[244]=new U(v.false,!1,1);en[245]=new U(v.true,!0,1);en[246]=new U(v.null,null,1);function x5(r){switch(r.type){case v.false:return Tn([244]);case v.true:return Tn([245]);case v.null:return Tn([246]);case v.bytes:return r.value.length?void 0:Tn([64]);case v.string:return r.value===""?Tn([96]):void 0;case v.array:return r.value===0?Tn([128]):void 0;case v.map:return r.value===0?Tn([160]):void 0;case v.uint:return r.value<24?Tn([Number(r.value)]):void 0;case v.negint:if(r.value>=-24)return Tn([31-Number(r.value)])}}var ZA={float64:!1,mapSorter:tI,quickEncodeToken:x5};function JA(){let r=[];return r[v.uint.major]=Pr,r[v.negint.major]=hd,r[v.bytes.major]=ks,r[v.string.major]=Gg,r[v.array.major]=md,r[v.map.major]=gd,r[v.tag.major]=yd,r[v.float.major]=wd,r}var v5=JA(),lp=new fc,vd=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(`${Yn} object contains circular references`);return new r(t,e)}},Co={null:new U(v.null,null),undefined:new U(v.undefined,void 0),true:new U(v.true,!0),false:new U(v.false,!1),emptyArray:new U(v.array,0),emptyMap:new U(v.map,0)},Po={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new U(v.float,r):r>=0?new U(v.uint,r):new U(v.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new U(v.uint,r):new U(v.negint,r)},Uint8Array(r,e,t,n){return new U(v.bytes,r)},string(r,e,t,n){return new U(v.string,r)},boolean(r,e,t,n){return r?Co.true:Co.false},null(r,e,t,n){return Co.null},undefined(r,e,t,n){return Co.undefined},ArrayBuffer(r,e,t,n){return new U(v.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new U(v.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Co.emptyArray,new U(v.break)]:Co.emptyArray;n=vd.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=xd(s,t,n);return t.addBreakTokens?[new U(v.array,r.length),o,new U(v.break)]:[new U(v.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return t.addBreakTokens===!0?[Co.emptyMap,new U(v.break)]:Co.emptyMap;n=vd.createCheck(n,r);let a=[],c=0;for(let l of i)a[c++]=[xd(l,t,n),xd(o?r.get(l):r[l],t,n)];return eI(a,t),t.addBreakTokens?[new U(v.map,s),a,new U(v.break)]:[new U(v.map,s),a]}};Po.Map=Po.Object;Po.Buffer=Po.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Po[`${r}Array`]=Po.DataView;function xd(r,e={},t){let n=xg(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Po[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=Po[n];if(!i)throw new Error(`${Yn} unsupported type: ${n}`);return i(r,n,e,t)}function eI(r,e){e.mapSorter&&r.sort(e.mapSorter)}function tI(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,i=v5[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function E5(r,e,t,n){if(Array.isArray(e))for(let o of e)E5(r,o,t,n);else t[e.type.major](r,e,n)}function up(r,e,t){let n=xd(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,t),a=new fc(s);if(i(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return dc(a.chunks[0])}}return lp.reset(),E5(lp,n,e,t),lp.toBytes(!0)}function Ro(r,e){return e=Object.assign({},ZA,e),up(r,v5,e)}var rI={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Ed=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=en[e];if(t===void 0){let n=K[e];if(!n)throw new Error(`${Z} 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}},gc=Symbol.for("DONE"),Sd=Symbol.for("BREAK");function nI(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=Rs(e,t);if(i===Sd){if(r.value===1/0)break;throw new Error(`${Z} got unexpected break to lengthed array`)}if(i===gc)throw new Error(`${Z} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function oI(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=Rs(e,t);if(a===Sd){if(r.value===1/0)break;throw new Error(`${Z} got unexpected break to lengthed map`)}if(a===gc)throw new Error(`${Z} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${Z} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${Z} found repeat map key "${a}"`);let c=Rs(e,t);if(c===gc)throw new Error(`${Z} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(a,c):o[a]=c}return n?i:o}function Rs(r,e){if(r.done())return gc;let t=r.next();if(t.type===v.break)return Sd;if(t.type.terminal)return t.value;if(t.type===v.array)return nI(t,r,e);if(t.type===v.map)return oI(t,r,e);if(t.type===v.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=Rs(r,e);return e.tags[t.value](n)}throw new Error(`${Z} tag not supported (${t.value})`)}throw new Error("unsupported")}function dp(r,e){if(!(r instanceof Uint8Array))throw new Error(`${Z} data to decode must be a Uint8Array`);e=Object.assign({},rI,e);let t=e.tokenizer||new Ed(r,e),n=Rs(t,e);if(n===gc)throw new Error(`${Z} did not find any content to decode`);if(n===Sd)throw new Error(`${Z} got unexpected break`);return[n,r.subarray(t.pos())]}function xr(r,e){let[t,n]=dp(r,e);if(n.length>0)throw new Error(`${Z} too many terminals, data makes no sense`);return t}var jn="/",S5=new TextEncoder().encode(jn),Ad=S5[0],Ne=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]!==Ad)throw new Error("Invalid key")}toString(e="utf8"){return $(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(jn))}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]!==Ad){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ad,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ad;)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 i=t[o],s=n[o];if(i<s)return!0;if(i>s)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(jn).slice(1)}type(){return iI(this.baseNamespace())}name(){return sI(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(jn)||(e+=jn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(jn):new r(e.slice(0,-1).join(jn))}child(e){return this.toString()===jn?e:e.toString()===jn?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(),...aI(e.map(t=>t.namespaces()))])}};function iI(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function sI(r){let e=r.split(":");return e[e.length-1]}function aI(r){return[].concat(...r)}function Id({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*cI(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],i=j.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*hp(n,o))}else{let t=j.asCID(e);t!=null?yield[r.join("/"),t]:yield*hp(e,r)}}function*hp(r,e){if(r==null||r instanceof Uint8Array)return;let t=j.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let i=[...e,n];yield*cI(i,o)}}function*lI(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&j.asCID(n)==null&&(yield*pp(n,o))}else yield*pp(e,r)}function*pp(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let o=[...e,t];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&j.asCID(n)==null&&(yield*lI(o,n))}}function uI(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=j.asCID(t);if(i!=null)return{value:i,remaining:e.slice(n+1).join("/")}}return{value:t}}var mp=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:Id(),bytes:Id(),value:Id(),asBlock:Id()})}links(){return hp(this.value,[])}tree(){return pp(this.value,[])}get(e="/"){return uI(this.value,e.split("/").filter(Boolean))}};function A5({bytes:r,cid:e,value:t,codec:n}){let o=t!==void 0?t:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new mp({cid:e,bytes:r,value:o})}var _5="/pin/",I5="/pinned-block/",gp=yn,T5=1;function Td(r){return r.version===0&&(r=r.toV1()),new Ne(`${_5}${r.toString(gp)}`)}var _d=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=Td(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 i=new Vt({concurrency:T5});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>oe(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Ro(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),i=await this.blockstore.get(e,n),s=A5({bytes:i,cid:e,codec:o});yield e;for await(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new Ne(`${I5}${gp.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=xr(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Ro(i),n),n.onProgress?.(new G("helia:pin:add",e))}}async*rm(e,t={}){let n=Td(e),o=await this.datastore.get(n,t),i=xr(o);await this.datastore.delete(n,t);let s=new Vt({concurrency:T5});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>oe(l,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:_5+(e.cid!=null?`${e.cid.toString(yn)}`:"")},e)){let o=j.parse(t.toString().substring(5),yn),i=xr(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new Ne(`${I5}${gp.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=Td(e),o=await this.datastore.get(n,t);return xr(o)}async setMetadata(e,t,n){let o=Td(e),i=await this.datastore.get(o,n),s=xr(i);s.metadata=t??{},await this.datastore.put(o,Ro(s),n)}};var yp=1,wp=5;var yc=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Do=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},wc=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},bc=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var dI=5,kd=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??dI,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await yt(...this.routers)}async stop(){await Ct(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Do("No content routers available");let n=new wt({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of Kt(n.toGenerator(),...bi(this.routers,"findProviders").map(i=>i.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,t);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer %p",o.id,i),null}},{peerId:o.id,signal:t.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer %p",o.id,i)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new Do("No content routers available");await Promise.all(bi(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(bi(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(bi(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(bi(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new Do("No peer routers available");let n=this,o=Kt(...bi(this.routers,"findPeer").map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i;throw new Oe("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Do("No peer routers available");for await(let n of Kt(...bi(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function bi(r,e){return r.filter(t=>t[e]!=null)}var No={},Ds=r=>{r.addEventListener("message",e=>{Ds.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Ds.dispatchEvent("message",r,e)})};Ds.addEventListener=(r,e)=>{No[r]==null&&(No[r]=[]),No[r].push(e)};Ds.removeEventListener=(r,e)=>{No[r]!=null&&(No[r]=No[r].filter(t=>t===e))};Ds.dispatchEvent=function(r,e,t){No[r]!=null&&No[r].forEach(n=>n(e,t))};var bp=Ds;var xp="lock:worker:request-read",vp="lock:worker:release-read",Ep="lock:master:grant-read",Sp="lock:worker:request-write",Ap="lock:worker:release-write",Ip="lock:master:grant-write";var k5=(r=21)=>Math.random().toString().substring(2);var C5=(r,e,t,n,o)=>(i,s)=>{if(s.data.type!==t)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{i.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=u=>{if(u?.data==null)return;let d={type:u.data.type,name:u.data.name,identifier:u.data.identifier};d.type===n&&d.identifier===a.identifier&&(i.removeEventListener("message",l),c())};i.addEventListener("message",l)})}}}))},P5=(r,e,t,n)=>async()=>{let o=k5();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(i=>{let s=a=>{if(a?.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",s),i(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",s)})},fI={singleProcess:!1},R5=r=>{if(r=Object.assign({},fI,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return bp.addEventListener("message",C5(t,"requestReadLock",xp,vp,Ep)),bp.addEventListener("message",C5(t,"requestWriteLock",Sp,Ap,Ip)),t}return{isWorker:!0,readLock:t=>P5(t,xp,Ep,vp),writeLock:t=>P5(t,Sp,Ip,Ap)}};var xi={},Lo;async function Tp(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>Zr((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var hI=(r,e)=>{if(Lo.isWorker===!0)return{readLock:Lo.readLock(r,e),writeLock:Lo.writeLock(r,e)};let t=new In({concurrency:1}),n;return{async readLock(){if(n!=null)return Tp(n,e);n=new In({concurrency:e.concurrency,autoStart:!1});let o=n,i=Tp(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,Tp(t,e)}}},pI={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function vi(r){let e=Object.assign({},pI,r);return Lo==null&&(Lo=R5(e),Lo.isWorker!==!0&&(Lo.addEventListener("requestReadLock",t=>{xi[t.data.name]!=null&&xi[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),Lo.addEventListener("requestWriteLock",async t=>{xi[t.data.name]!=null&&xi[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),xi[e.name]==null&&(xi[e.name]=hI(e.name,e)),xi[e.name]}var Cd=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=vi({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await yt(this.child),this.started=!0}async stop(){await Ct(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 i of e){if(await o.pins.isPinned(i))throw new Error("CID was pinned");yield i}}(),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 _p=new Ne("/version"),D5=1;async function N5(r){if(!await r.has(_p)){await r.put(_p,M(`${D5}`));return}let e=await r.get(_p),t=$(e);if(parseInt(t,10)!==D5)throw new Error("Unknown datastore version, a datastore migration may be required")}var Pp={};Ye(Pp,{code:()=>Cp,decode:()=>SI,decodeOptions:()=>xI,encode:()=>EI,encodeOptions:()=>wI,name:()=>vI,toByteView:()=>B5});var L5=42;function B5(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function mI(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=j.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new U(v.tag,L5),new U(v.bytes,t)]}function gI(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function yI(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 kp={float64:!0,typeEncoders:{Object:mI,undefined:gI,number:yI}},wI={...kp,typeEncoders:{...kp.typeEncoders}};function bI(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return j.decode(r.subarray(1))}var Pd={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Pd.tags[L5]=bI;var xI={...Pd,tags:Pd.tags.slice()},vI="dag-cbor",Cp=113,EI=r=>Ro(r,kp),SI=r=>xr(B5(r),Pd);var Mp={};Ye(Mp,{code:()=>Op,decode:()=>M5,encode:()=>O5,format:()=>LI,name:()=>NI,parse:()=>OI,stringify:()=>LI});var Rp=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===v.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===v.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[v.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[v.negint.major](e,t){this[v.uint.major](e,t)}[v.bytes.major](e,t){throw new Error(`${Yn} unsupported type: Uint8Array`)}[v.string.major](e,t){this.prefix(e);let n=fd(JSON.stringify(t.value));e.push(n.length>32?dc(n):n)}[v.array.major](e,t){this.prefix(e),this.inRecursive.push({type:v.array,elements:0}),e.push([91])}[v.map.major](e,t){this.prefix(e),this.inRecursive.push({type:v.map,elements:0}),e.push([123])}[v.tag.major](e,t){}[v.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===v.array)e.push([93]);else if(s.type===v.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(`${Yn} 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=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function AI(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Yn} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==v.string||n.type!==v.string)throw new Error(`${Yn} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Yn} unexpected duplicate map keys, this is not supported`)}var II={addBreakTokens:!0,mapSorter:AI};function Dp(r,e){return e=Object.assign({},II,e),up(r,new Rp,e)}var Ns=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(`${Z} 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(`${Z} 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 U(v.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(`${Z} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${Z} 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 i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new U(v.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new U(s>=0?v.uint:v.negint,s,this._pos-e):new U(s>=0?v.uint:v.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${Z} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new U(v.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${Z} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){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(`${Z} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${Z} unexpected unicode sequence at position ${this._pos}`);let c,l,u,d;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(d=(i&31)<<6|c&63,d>127&&(s=d));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(d=(i&15)<<12|(c&63)<<6|l&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(d=(i&15)<<18|(c&63)<<12|(l&63)<<6|u&63,d>65535&&d<1114112&&(s=d))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${Z} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);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(`${Z} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new U(v.string,op(t),this._pos-e);default:if(i<32)throw new Error(`${Z} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${Z} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new U(v.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new U(v.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new U(v.null,null,4);case 102:return this.expect([102,97,108,115,101]),new U(v.false,!1,5);case 116:return this.expect([116,114,117,101]),new U(v.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(`${Z} 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 U(v.break,void 0,1);if(this.ch()!==44)throw new Error(`${Z} 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 U(v.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 U(v.break,void 0,1);if(this.ch()!==44)throw new Error(`${Z} 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 U(v.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${Z} 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(`${Z} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Np(r,e){return e=Object.assign({tokenizer:new Ns(r,e)},e),xr(r,e)}function _I(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function kI(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=j.asCID(r);if(!e)return null;let t=e.toString();return[new U(v.map,1/0,1),new U(v.string,"/",1),new U(v.string,t,t.length),new U(v.break,void 0,1)]}function Rd(r){let e=nt.encode(r).slice(1);return[new U(v.map,1/0,1),new U(v.string,"/",1),new U(v.map,1/0,1),new U(v.string,"bytes",5),new U(v.string,e,e.length),new U(v.break,void 0,1),new U(v.break,void 0,1)]}function tn(r){return Rd(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function CI(r){return Rd(new Uint8Array(r))}function PI(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function RI(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 DI={typeEncoders:{Object:kI,Buffer:Rd,Uint8Array:Rd,Int8Array:tn,Uint16Array:tn,Int16Array:tn,Uint32Array:tn,Int32Array:tn,Float32Array:tn,Float64Array:tn,Uint8ClampedArray:tn,BigInt64Array:tn,BigUint64Array:tn,DataView:tn,ArrayBuffer:CI,undefined:PI,number:RI}},Lp=class extends Ns{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===v.map){let t=this._next();if(t.type===v.string&&t.value==="/"){let n=this._next();if(n.type===v.string){if(this._next().type!==v.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new U(v.tag,42,0)}if(n.type===v.map){let o=this._next();if(o.type===v.string&&o.value==="bytes"){let i=this._next();if(i.type===v.string){for(let a=0;a<2;a++)if(this._next().type!==v.break)throw new Error("Invalid encoded Bytes form");let s=nt.decode(`m${i.value}`);return new U(v.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Bp={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Bp.tags[42]=j.parse;var NI="dag-json",Op=297,O5=r=>Dp(r,DI),M5=r=>{let e=_I(r),t=Object.assign(Bp,{tokenizer:new Lp(e,Bp)});return Np(e,t)},LI=r=>BI.decode(O5(r));var BI=new TextDecoder,OI=r=>M5(MI.encode(r)),MI=new TextEncoder;var Hp={};Ye(Hp,{code:()=>Kp,createLink:()=>G5,createNode:()=>W5,decode:()=>XI,encode:()=>YI,name:()=>QI,prepare:()=>Vp,validate:()=>$p});var UI=new TextDecoder;function Up(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 Dd(r,e){let t;[t,e]=Up(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 U5(r,e){let t;return[t,e]=Up(r,e),[t&7,t>>3,e]}function FI(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=U5(r,n),i===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]=Dd(r,n)}else if(i===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 s;[s,n]=Dd(r,n),e.Name=UI.decode(s)}else if(i===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]=Up(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function F5(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=U5(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=Dd(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]=Dd(r,t),n.push(FI(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 s={};return i&&(s.Data=i),s.Links=n||[],s}var $5=new TextEncoder,V5=2**32,VI=2**31;function $I(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=xc(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=$5.encode(r.Name);t-=n.length,e.set(n,t),t=xc(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=xc(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function K5(r){let e=HI(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=xc(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=$I(r.Links[o],t.subarray(0,n));n-=i,n=xc(t,n,i)-1,t[n]=18}return t}function KI(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Ls(t)}if(typeof r.Name=="string"){let t=$5.encode(r.Name).length;e+=1+t+Ls(t)}return typeof r.Tsize=="number"&&(e+=1+Ls(r.Tsize)),e}function HI(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Ls(t)}if(r.Links)for(let t of r.Links){let n=KI(t);e+=1+n+Ls(n)}return e}function xc(r,e,t){e-=Ls(t);let n=e;for(;t>=VI;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Ls(r){return r%2===0&&r++,Math.floor((qI(r)+6)/7)}function qI(r){let e=0;return r>=V5&&(r=Math.floor(r/V5),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+zI[r]}var zI=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var WI=["Data","Links"],GI=["Hash","Name","Tsize"],Fp=new TextEncoder;function q5(r,e){if(r===e)return 0;let t=r.Name?Fp.encode(r.Name):[],n=e.Name?Fp.encode(e.Name):[],o=t.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(t[s]!==n[s]){o=t[s],i=n[s];break}return o<i?-1:i<o?1:0}function H5(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function z5(r){if(typeof r.asCID=="object"){let t=j.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=j.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=j.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=j.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function Vp(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=Fp.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(z5),e.Links.sort(q5);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function $p(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!H5(r,WI))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!H5(t,GI))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&q5(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function W5(r,e=[]){return Vp({Data:r,Links:e})}function G5(r,e,t){return z5({Hash:t,Name:r,Tsize:e})}function Q5(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var QI="dag-pb",Kp=112;function YI(r){$p(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),K5(e)}function XI(r){let e=Q5(r),t=F5(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=j.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function Bs(r){return r?.then!=null}function Y5(r=[],e){let t={[Kp]:Hp,[ei]:is,[Cp]:Pp,[Op]:Mp,[F0]:Ll};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Bs(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new bc(`Could not load codec for ${n}`)}}function X5(r=[],e){let t={[lt.code]:lt,[Ol.code]:Ol,[Zt.code]:Zt};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let i=e(n);Bs(i)?o=await i:o=i,t[o.code]=o}if(o!=null)return o;throw new wc(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var Dr=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var Zn=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 Nd=0,Ld=class extends Zn{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===Nd||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===Nd)return e.multihash.digest;if(this.child==null)throw new Dr;return this.child.get(e)}has(e){return e.multihash.code===Nd?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==Nd&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function jI(r){return r[Symbol.asyncIterator]!=null}function ZI(r,e){let t=0;if(jI(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=ns(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=e(o,t++);if(typeof s.then=="function")return async function*(){await s&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){s===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var rn=ZI;function JI(r){return r[Symbol.asyncIterator]!=null}function j5(r){return r?.then!=null}function eT(r,e){let t=0;if(JI(r))return async function*(){for await(let c of r){let l=e(c,t++);j5(l)&&await l,yield c}}();let n=ns(r),{value:o,done:i}=n.next();if(i===!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++);j5(l)&&await l,yield c}}();let a=e;return function*(){yield o;for(let c of n)a(c,t++),yield c}()}var Ei=eT;var Bd=class{child;getHasher;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Ld(e.blockstore),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new G("blocks:put:duplicate",e)),e):(n.onProgress?.(new G("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new G("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=rn(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new G("blocks:put-many:duplicate",i)),!s}),o=Ei(n,async({cid:i,block:s})=>{t.onProgress?.(new G("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(i,s,t)))});t.onProgress?.(new G("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)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new G("blocks:get:providers:get",e));let o=await Z5(e,this.components.blockBrokers,n,{...t,log:this.log});return t.onProgress?.(new G("blocks:get:blockstore:put",e)),await this.child.put(e,o,t),t.onProgress?.(new G("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(e,o,t))),o}return t.onProgress?.(new G("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new G("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Ei(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let o=await this.getHasher(n.multihash.code);t.onProgress?.(new G("blocks:get-many:providers:get",n));let i=await Z5(n,this.components.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new G("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,t),t.onProgress?.(new G("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,i,t)))}}))}async delete(e,t={}){t.onProgress?.(new G("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new G("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 G("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},Od=class extends Bd{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await yt(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await Ct(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 qp({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},qp=class extends Bd{closeController;constructor(e,t){super(e),this.closeController=new AbortController,F(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=le([this.closeController.signal,n.signal]);F(1/0,o);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=le([this.closeController.signal,t.signal]);F(1/0,n);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=le([this.closeController.signal,t.signal]);F(1/0,n);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=le([this.closeController.signal,t.signal]);F(1/0,n);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=le([this.closeController.signal,t.signal]);F(1/0,n);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=le([this.closeController.signal,t.signal]);F(1/0,n);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=le([this.closeController.signal,t.signal]);F(1/0,n);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=le([this.closeController.signal,e.signal]);F(1/0,t);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function tT(r){return typeof r.retrieve=="function"}var rT=(r,e)=>{if(e==null)throw new P(`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`);return async t=>{let n,o=e.digest(t);if(Bs(o)?n=await o:n=o,!oe(n.digest,r.multihash.digest))throw new co("Hash of downloaded block did not match multihash from passed CID")}};async function Z5(r,e,t,n){let o=rT(r,t),i=new AbortController,s=le([i.signal,n.signal]);F(1/0,i.signal,s);let a=[];for(let c of e)tT(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:s,validateFn:async d=>{await o(d),l=!0}});return l||await o(u),u}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{i.abort(),s.clear()}}var Si=class extends ye{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),F(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=rr(this.maxProviders)}async retrieve(e,t={}){let n=nt.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let i=ee();if(this.requests.set(n,i.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 s=!1,a=new Vt({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=>{s=!0,i.resolve(l.detail.result)}),a.addEventListener("idle",()=>{s||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 u=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(u)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c",e,l),i.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(u=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,u)})};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 i.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=ee(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let s of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new yc(`Found ${i} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",e,s.errors??s),o.reject(s)}),o.promise}};var Md=class{blockstore;datastore;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??ko(),this.log=this.logger.forComponent("helia"),this.getHasher=X5(e.hashers,e.loadHasher),this.getCodec=Y5(e.codecs,e.loadCodec),this.dns=e.dns??ud(),this.metrics=e.metrics;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new kd(t,{routers:(e.routers??[]).flatMap(o=>{let i=[o];return o[hn]!=null&&i.push(o[hn]),o[pn]!=null&&i.push(o[pn]),i}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new Od(t);this.pins=new _d(e.datastore,n,this.getCodec),this.blockstore=new Cd(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await N5(this.datastore),await yt(this.blockstore,this.datastore,this.routing)}async stop(){await Ct(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 Rt(o.deleteMany(async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new G("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new G("helia:gc:error",s))}}()))}finally{t()}this.log("gc finished")}};var zp=class extends Si{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.toMultihash().bytes}equals(e,t){return e.equals(t)}};function J5(r,e){return new zp(r,e)}var Ud=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 Wp=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 Fd(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Wp({name:e,metrics:t}):n=new Map,n}function nT(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=$t(r);e.push(t),r=r.slice(me(t))}return e}var e7=nT;var Vd=class extends ye{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),F(1/0,this),this.peers=ac({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=Fd({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=$(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??Je.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,o)),o.wantType===Je.WantHave&&t.wantType===Je.WantBlock&&(o.wantType=Je.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===Je.WantBlock?(await fr(this,"block",t?.signal,{filter:a=>oe(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await fr(this,"presence",t?.signal,{filter:s=>oe(e.multihash.digest,s.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=ee(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new Qn;for(let[i,s]of this.wants.entries())t.has(i)||s.cancel||(n.add(i),o.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:s.priority,wantType:s.wantType,cancel:s.cancel,sendDontHave:s.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o);for(let i of n)t.add(i)}catch(i){this.log.error("error sending full wantlist to new peer",i)}})).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=$(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new Qn;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:Je.WantHave,priority:1}),await this.network.sendMessage(t,o),(await fr(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&oe(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:Je.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new Qn;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:Je.WantBlock,priority:1}),await this.network.sendMessage(t,o),(await fr(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&oe(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=$(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 i=e7(o.prefix),s=i[0],a=i[1],c=i[2],l=c===lt.code?lt:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let u=l.digest(o.data);u.then!=null&&(u=await u);let d=j.create(s===0?0:1,a,u);this.log("received block from %p for %c",e,d),this.safeDispatchEvent("block",{detail:{sender:e,cid:d,block:o.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:d,has:!0,block:o.data}});let h=$(d.multihash.bytes,"base64"),f=this.wants.get(h);f!=null&&(f.cancel=!0,n=!0)}for(let{cid:o,type:i}of t.blockPresences){let s=j.decode(o);this.log("received %s from %p for %c",i,e,s),this.safeDispatchEvent("presence",{detail:{sender:e,cid:s,has:i===Ar.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new Qn(!0);for(let[o,i]of this.wants.entries())i.cancel||(t.add(o),n.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:1,wantType:Je.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 $d=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 Ud(e),this.network=new Hl(e,t),this.peerWantLists=new rd({...e,network:this.network},t),this.wantList=new Vd({...e,network:this.network},t)}createSession(e={}){return J5({wantList:this.wantList,network:this.network,logger:this.logger},e)}async want(e,t={}){let n=new AbortController,o=le([n.signal,t.signal]);F(1/0,n.signal,o),this.network.findAndConnect(e,{...t,signal:o}).catch(i=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,i)});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 t7=(r,e={})=>new $d(r,e);var Gp=class{bitswap;started;constructor(e,t={}){let{getHasher:n}=e;this.bitswap=t7(e,{hashLoader:{getHasher:async o=>n(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,i)=>{await this.bitswap.notify(n,o,i)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function Qp(r={}){return e=>new Gp(e,r)}var Kd=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 i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let h=Number.parseInt(d,e);if(!Number.isNaN(h))return h});if(u===void 0)break;if(i*=e,i+=u,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}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 s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&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 i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var r7=45,oT=15,Os=new Kd;function Hd(r){if(!(r.length>oT))return Os.new(r).parseWith(()=>Os.readIPv4Addr())}function qd(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>r7))return Os.new(r).parseWith(()=>Os.readIPv6Addr())}function Ai(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>r7))return Os.new(r).parseWith(()=>Os.readIPAddr())}function nn(r){return!!Hd(r)}function Ms(r){return!!qd(r)}function zd(r){return!!Ai(r)}var o7=ur(n7(),1),iT=["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"],sT=iT.map(r=>new o7.Netmask(r));function Yp(r){for(let e of sT)if(e.contains(r))return!0;return!1}function aT(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function cT(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Yp(o)}function lT(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function uT(r){let e=r.split(":"),t=e[e.length-1];return Yp(t)}function dT(r){return/^::$/.test(r)||/^::1$/.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 vr(r){return nn(r)?Yp(r):aT(r)?cT(r):lT(r)?uT(r):Ms(r)?dT(r):void 0}var fT=r=>r.toString().split("/").slice(1),Us=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),pe=r=>({match:e=>Us(t=>t===r).match(e),pattern:r}),Ii=()=>({match:r=>Us(e=>typeof e=="string").match(r),pattern:"{string}"}),Ec=()=>({match:r=>Us(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Ce=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Ee.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Sc=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{B0.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),_e=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Mt=(...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(", ")})`}),ge=(...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 Pe(...r){function e(o){let i=fT(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function t(o){return e(o)!==!1}function n(o){let i=e(o);return i===!1?!1:i.length===0}return{matchers:r,matches:t,exactMatch:n}}var Gd=ge(pe("dns4"),Ii()),Qd=ge(pe("dns6"),Ii()),Yd=ge(pe("dnsaddr"),Ii()),jp=ge(pe("dns"),Ii()),LH=Pe(Gd,_e(Ce())),BH=Pe(Qd,_e(Ce())),OH=Pe(Yd,_e(Ce())),Ac=Pe(Mt(jp,Yd,Gd,Qd),_e(Ce())),i7=ge(pe("ip4"),Us(nn)),s7=ge(pe("ip6"),Us(Ms)),Zp=Mt(i7,s7),Jn=Mt(Zp,jp,Gd,Qd,Yd),a7=Pe(Mt(Zp,ge(Mt(jp,Yd,Gd,Qd),_e(Ce())))),MH=Pe(i7),UH=Pe(s7),c7=Pe(Zp),Jp=ge(Jn,pe("tcp"),Ec()),Ic=ge(Jn,pe("udp"),Ec()),Tc=Pe(ge(Jp,_e(Ce()))),FH=Pe(Ic),em=ge(Ic,pe("quic"),_e(Ce())),Xd=ge(Ic,pe("quic-v1"),_e(Ce())),hT=Mt(em,Xd),VH=Pe(em),$H=Pe(Xd),Xp=Mt(Jn,Jp,Ic,em,Xd),l7=Mt(ge(Xp,pe("ws"),_e(Ce()))),Ti=Pe(l7),u7=Mt(ge(Xp,pe("wss"),_e(Ce())),ge(Xp,pe("tls"),_e(ge(pe("sni"),Ii())),pe("ws"),_e(Ce()))),_c=Pe(u7),d7=ge(Ic,pe("webrtc-direct"),_e(Sc()),_e(Sc()),_e(Ce())),kc=Pe(d7),f7=ge(Xd,pe("webtransport"),_e(Sc()),_e(Sc()),_e(Ce())),tm=Pe(f7),Wd=Mt(l7,u7,ge(Jp,_e(Ce())),ge(hT,_e(Ce())),ge(Jn,_e(Ce())),d7,f7,Ce()),jd=Pe(Wd),pT=ge(Wd,pe("p2p-circuit"),Ce()),or=Pe(pT),mT=Mt(ge(Wd,pe("p2p-circuit"),pe("webrtc"),_e(Ce())),ge(Wd,pe("webrtc"),_e(Ce())),ge(pe("webrtc"),_e(Ce()))),Cc=Pe(mT),gT=Mt(ge(Jn,pe("tcp"),Ec(),pe("http"),_e(Ce())),ge(Jn,pe("http"),_e(Ce()))),h7=Pe(gT),yT=Mt(ge(Jn,pe("tcp"),Mt(ge(pe("443"),pe("http")),ge(Ec(),pe("https"))),_e(Ce())),ge(Jn,pe("tls"),pe("http"),_e(Ce())),ge(Jn,pe("https"),_e(Ce()))),p7=Pe(yT),wT=Mt(ge(pe("memory"),Ii(),_e(Ce()))),KH=Pe(wT);function m7(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function g7(r,e,t,n){let o=0;for(let i of r)if(!(o<t)){if(o>n)break;if(i!==e[o])return!1;o++}return!0}function rm(r){switch(r.length){case _i:return r.join(".");case ki:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function y7(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;n&128;)e++,n=n<<1;if(n&128)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function w7(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var _i=4,ki=16,QH=parseInt("0xFFFF",16),bT=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Pc(r,e){e.length===ki&&r.length===_i&&m7(e,0,11)&&(e=e.slice(12)),e.length===_i&&r.length===ki&&g7(r,bT,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function b7(r,e){if(typeof e=="string"&&(e=Ai(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function nm(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=_i,o=Hd(e);if(o==null&&(n=ki,o=qd(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let i=parseInt(t,10);if(Number.isNaN(i)||String(i).length!==t.length||i<0||i>n*8)throw new Error("Failed to parse given CIDR: "+r);let s=om(i,8*n);return{network:Pc(o,s),mask:s}}function om(r,e){if(e!==8*_i&&e!==8*ki)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var Ci=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=nm(e));else{let n=Ai(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let i=Ai(t);if(i==null)throw new Error("Failed to parse mask");this.mask=i}else this.mask=om(o,8*n.length);this.network=Pc(n,this.mask)}}contains(e){return b7({network:this.network,mask:this.mask},e)}toString(){let e=y7(this.mask),t=e!==-1?String(e):w7(this.mask);return rm(this.network)+"/"+t}};function x7(r,e){return new Ci(r).contains(e)}var v7=nn,xT=Ms,im=function(r){let e=0;if(r=r.toString().trim(),v7(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(xT(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=v7(t[n]),s;i&&(s=im(t[n]),t[n]=$(s.slice(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,$(s.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 i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let i=parseInt(t[n],16);o[e++]=i>>8&255,o[e++]=i&255}return o}throw new Error("invalid ip address")},E7=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 i=0;i<t;i++)o.push(r[e+i]);return o.join(".")}if(t===16){let o=[];for(let i=0;i<t;i+=2)o.push(n.getUint16(e+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Fs={},sm={},ET=[[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"],[481,-1,"http-path"],[777,-1,"memory"]];ET.forEach(r=>{let e=ST(...r);sm[e.code]=e,Fs[e.name]=e});function ST(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function J(r){if(typeof r=="number"){if(sm[r]!=null)return sm[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Fs[r]!=null)return Fs[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var AT=J("ip4"),IT=J("ip6"),TT=J("ipcidr");function um(r,e){switch(J(r).code){case 4:case 41:return kT(e);case 42:return lm(e);case 43:return $(e,"base10");case 6:case 273:case 33:case 132:return I7(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return lm(e);case 421:return DT(e);case 444:return A7(e);case 445:return A7(e);case 466:return RT(e);case 481:return globalThis.encodeURIComponent(lm(e));default:return $(e,"base16")}}function dm(r,e){switch(J(r).code){case 4:return S7(e);case 41:return S7(e);case 42:return cm(e);case 43:return M(e,"base10");case 6:case 273:case 33:case 132:return hm(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return cm(e);case 421:return CT(e);case 444:return NT(e);case 445:return LT(e);case 466:return PT(e);case 481:return cm(globalThis.decodeURIComponent(e));default:return M(e,"base16")}}function fm(r){let e,t;if(r.stringTuples().forEach(([n,o])=>{(n===AT.code||n===IT.code)&&(t=o),n===TT.code&&(e=o)}),e==null||t==null)throw new Error("Invalid multiaddr");return new Ci(t,e)}var am=Object.values(ri).map(r=>r.decoder),_T=function(){let r=am[0].or(am[1]);return am.slice(2).forEach(e=>r=r.or(e)),r}();function S7(r){if(!zd(r))throw new Error("invalid ip address");return im(r)}function kT(r){let e=E7(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!zd(e))throw new Error("invalid ip address");return e}function hm(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function I7(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function cm(r){let e=M(r),t=Uint8Array.from(Ke(e.length));return Re([t,e],t.length+e.length)}function lm(r){let e=$t(r);if(r=r.slice(me(e)),r.length!==e)throw new Error("inconsistent lengths");return $(r)}function CT(r){let e;r[0]==="Q"||r[0]==="1"?e=Ie(Ee.decode(`z${r}`)).bytes:e=j.parse(r).multihash.bytes;let t=Uint8Array.from(Ke(e.length));return Re([t,e],t.length+e.length)}function PT(r){let e=_T.decode(r),t=Uint8Array.from(Ke(e.length));return Re([t,e],t.length+e.length)}function RT(r){let e=$t(r),t=r.slice(me(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+$(t,"base64url")}function DT(r){let e=$t(r),t=r.slice(me(e));if(t.length!==e)throw new Error("inconsistent lengths");return $(t,"base58btc")}function NT(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=ct.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=hm(n);return Re([t,o],t.length+o.length)}function LT(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=ct.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=hm(n);return Re([t,o],t.length+o.length)}function A7(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=$(e,"base32"),o=I7(t);return`${n}:${o}`}function T7(r){r=pm(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 i=0;i<o.length;i++){let s=o[i],a=J(s);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(i++,i>=o.length)throw k7("invalid address: "+r);if(a.path===!0){n=pm(o.slice(i).join("/")),e.push([a.code,dm(a.code,n)]),t.push([a.code,n]);break}let c=dm(a.code,o[i]);e.push([a.code,c]),t.push([a.code,um(a.code,c)])}return{string:_7(t),bytes:gm(e),tuples:e,stringTuples:t,path:n}}function mm(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let i=$t(r,o),s=me(i),a=J(i),c=BT(a,r.slice(o+s));if(c===0){e.push([i]),t.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw k7("Invalid address Uint8Array: "+$(r,"base16"));e.push([i,l]);let u=um(i,l);if(t.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:_7(t),tuples:e,stringTuples:t,path:n}}function _7(r){let e=[];return r.map(t=>{let n=J(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),pm(e.join("/"))}function gm(r){return Re(r.map(e=>{let t=J(e[0]),n=Uint8Array.from(Ke(t.code));return e.length>1&&e[1]!=null&&(n=Re([n,e[1]])),n}))}function BT(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=$t(e instanceof Uint8Array?e:Uint8Array.from(e));return t+me(t)}}function pm(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function k7(r){return new Error("Error parsing address: "+r)}var OT=Symbol.for("nodejs.util.inspect.custom"),wm=Symbol.for("@multiformats/js-multiaddr/multiaddr"),MT=[J("dns").code,J("dns4").code,J("dns6").code,J("dnsaddr").code],ym=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},Zd=class r{bytes;#e;#t;#r;#o;[wm]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=mm(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=T7(e)}else if(Bo(e))t=mm(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,i="",s=J("tcp"),a=J("udp"),c=J("ip4"),l=J("ip6"),u=J("dns6"),d=J("ip6zone");for(let[f,p]of this.stringTuples())f===d.code&&(i=`%${p??""}`),MT.includes(f)&&(t=s.name,o=443,n=`${p??""}${i}`,e=f===u.code?6:4),(f===s.code||f===a.code)&&(t=J(f).name,o=parseInt(p??"")),(f===c.code||f===l.code)&&(t=J(f).name,n=`${p??""}${i}`,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({},J(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>J(e).name)}tuples(){return this.#t.map(([e,t])=>t==null?[e]:[e,t])}stringTuples(){return this.#r.map(([e,t])=>t==null?[e]:[e,t])}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(gm(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===Fs.p2p.code&&e.push([n,o]),n===Fs["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?$(Ee.decode(`z${n}`),"base58btc"):$(j.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#o}equals(e){return oe(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(i=>i.resolvable);if(t==null)return[this];let n=Vs.get(t.name);if(n==null)throw new ym(`no available resolver for ${t.name}`);return(await n(this,e)).map(i=>q(i))}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)}[OT](){return`Multiaddr(${this.#e})`}};var Vs=new Map;function Bo(r){return!!r?.[wm]}function q(r){return new Zd(r)}var UT=[J("tcp").code,J("dns").code,J("dnsaddr").code,J("dns4").code,J("dns6").code];function C7(r){return D7("sni",r)?.[1]}function P7(r){let e=D7("tcp",r)?.[1];return e==null?"":`:${e}`}function D7(r,e){let t;try{t=J(r).code}catch{return}for(let[n,o]of e)if(n===t&&o!=null)return[n,o]}function R7(r){return r.some(([e,t])=>e===J("tls").code)}function on(r,e,t){let n=N7[J(r).name];if(n==null)throw new Error(`Can't interpret protocol ${J(r).name}`);let o=n(e,t);return r===J("ip6").code?`[${o}]`:o}var N7={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${on(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${on(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==null)throw new Error("Unexpected end of multiaddr");return`${on(t[0],t[1]??"",e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${on(t[0],t[1]??"",e)}`},http:(r,e)=>{let t=R7(e),n=C7(e),o=P7(e);if(t&&n!=null)return`https://${n}${o}`;let i=t?"https://":"http://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=on(s[0],s[1]??"",e);return a=a.replace("tcp://",""),`${i}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=on(t[0],t[1]??"",e),o=decodeURIComponent(r);return`${n}/${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return on(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return on(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=on(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=R7(e),n=C7(e),o=P7(e);if(t&&n!=null)return`wss://${n}${o}`;let i=t?"wss://":"ws://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=on(s[0],s[1]??"",e);return a=a.replace("tcp://",""),`${i}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=on(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`}};function Jd(r,e){let n=q(r).stringTuples(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let i=J(o[0]),s=N7[i.name];if(s==null)throw new Error(`No interpreter found for ${i.name}`);let a=s(o[1]??"",n);return e?.assumeHttp!==!1&&UT.includes(o[0])&&(a=a.replace(/^.*:\/\//,""),o[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://")||a.startsWith("ws://")||a.startsWith("wss://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var e1=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 nt.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),i=new AbortController,s=()=>{i.abort()};t?.addEventListener("abort",s);try{let a=this.#a.get(o);return a==null&&(this.#e++,a=fetch(n.toString(),{signal:i.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",s),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 FT(r,e,t){return r.filter(n=>{if(p7.matches(n)||e&&h7.matches(n))return t||Ac.matches(n)?!0:vr(n.toOptions().host)===!1;if(!e&&t){let{host:o}=n.toOptions();if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*t1(r,e,t,n,o,i){for await(let s of e.findProviders(r,i)){let a=FT(s.multiaddrs,n,o);if(a.length===0)continue;let c=Jd(a[0]);yield new e1(c,t)}}var bm=class extends Si{routing;allowInsecure;allowLocal;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??r1,this.allowLocal=t.allowLocal??n1}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*t1(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 L7(r,e){return new bm(r,e)}var o1=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??r1,this.allowLocal=t.allowLocal??n1}async retrieve(e,t={}){let n=[];for await(let o of t1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)){this.log("getting block for %c from %s",e,o.url);try{let i=await o.getRawBlock(e,t.signal);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(i)}catch(s){this.log.error("failed to validate block for %c from %s",e,o.url,s);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s",e,o.url,i),i instanceof Error?n.push(i):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 L7({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure})}};var r1=!1,n1=!1;function xm(r={}){return e=>new o1(e,r)}async function*i1(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 zT=ur(s1(),1);var sn=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},a1=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},$s=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},c1=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},l1=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},u1=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},Rc=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var ir;(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,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.value!=null&&(i.uint32(10),i.bytes(o.value)),o.signatureV1!=null&&(i.uint32(18),i.bytes(o.signatureV1)),o.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(o.validityType,i)),o.validity!=null&&(i.uint32(34),i.bytes(o.validity)),o.sequence!=null&&(i.uint32(40),i.uint64(o.sequence)),o.ttl!=null&&(i.uint32(48),i.uint64(o.ttl)),o.pubKey!=null&&(i.uint32(58),i.bytes(o.pubKey)),o.signatureV2!=null&&(i.uint32(66),i.bytes(o.signatureV2)),o.data!=null&&(i.uint32(74),i.bytes(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>re(o,r.codec()),r.decode=(o,i)=>te(o,r.codec(),i)})(ir||(ir={}));var VT=pr("ipns:utils"),B7=M("/ipns/");var $T=0,KT=18;function O7(r){let e;if(r.pubKey!=null)try{e=tt(r.pubKey)}catch(t){throw VT.error(t),t}if(e!=null)return e}function M7(r){let e=M("ipns-signature:");return Re([e,r])}function Dc(r){return"signatureV1"in r?ir.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}):ir.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function _n(r){let e=ir.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 new sn("Missing data or signatureV2");let t=U7(e.data),n=HT(t.Value),o=$(t.Validity);if(e.value!=null&&e.signatureV1!=null)return qT(e),{value:n,validityType:ir.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:ir.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")}function Nc(r){return Re([B7,r.bytes])}function Ks(r){let e=Ie(r.slice(B7.length));if(!d1(e,$T)&&!d1(e,KT))throw new co("Multihash in IPNS key was not identity or sha2-256");return e}function U7(r){let e=xr(r);if(e.ValidityType===0)e.ValidityType=ir.ValidityType.EOL;else throw new $s("The validity type is unsupported");return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e}function HT(r){let e=$(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${j.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${j.parse(e).toV1().toString()}`}catch{}throw new l1("Value must be a valid content path starting with /")}function qT(r){if(r.data==null)throw new u1("Record data is missing");let e=U7(r.data);if(!oe(e.Value,r.value??new Uint8Array(0)))throw new sn('Field "value" did not match between protobuf and CBOR');if(!oe(e.Validity,r.validity??new Uint8Array(0)))throw new sn('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new sn('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new sn('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new sn('Field "ttl" did not match between protobuf and CBOR')}function d1(r,e){return r.code===e}var Oz=pr("ipns"),Mz=60*60*1e9,WT="/ipns/",Uz=WT.length;var F7=ur(s1(),1);var f1=pr("ipns:validator"),GT=1024*10,QT=async(r,e)=>{let t=_n(e),n;try{let o=M7(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw f1.error("record signature verification failed"),new sn("Record signature verification failed");if(t.validityType===ir.ValidityType.EOL){if(F7.default.fromString(t.validity).toDate().getTime()<Date.now())throw f1.error("record has expired"),new a1("record has expired")}else if(t.validityType!=null)throw f1.error("the validity type is unsupported"),new $s("The validity type is unsupported");f1("ipns record for %s is valid",t.value)};async function h1(r,e){if(e.byteLength>GT)throw new c1("The record is too large");let t=Ks(r),n;d1(t,0)&&(n=Yu(t));let o=_n(e),i=O7(o)??n;if(i==null)throw new Rc("Could not extract public key from IPNS record or routing key");let s=Nc(i.toMultihash());if(!oe(r,s))throw new Rc("Embedded public key did not match routing key");await QT(i,e)}var p1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*Lc(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let i of r){if(typeof i=="string"&&(i=new TextEncoder().encode(i)),rs(i)&&(i=i.subarray()),o+=n.decode(i,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new p1("Incoming message too long");let s=o.split(t);o=s.pop()??"";for(let a=0;a<s.length;a++)yield JSON.parse(s[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var Hs=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},Pi=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function YT(r){return r[Symbol.asyncIterator]!=null}function XT(r){if(YT(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var V7=XT;var $7=M("/ipns/");function K7(r){return oe(r.subarray(0,$7.byteLength),$7)}var m1=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*Xt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!K7(e))return;let o=Ks(e),i=j.createV1(114,o),s=_n(t);await this.client.putIPNS(i,s,n)}async get(e,t){if(!K7(e))throw new Oe("Not found");let n=Ks(e),o=j.createV1(114,n);try{let i=await this.client.getIPNS(o,t);return Dc(i)}catch(i){throw i.name==="BadResponseError"?new Oe("Not found"):i}}},g1=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await V7(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new Oe("Not found")}async*getClosestPeers(e,t={}){}};var gt=pr("delegated-routing-v1-http-api-client"),y1={concurrentRequests:4,timeout:3e4,cacheTTL:5*60*1e3,cacheName:"delegated-routing-v1-cache"},w1=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,F(1/0,this.shutDownController.signal),this.httpQueue=new In({concurrency:t.concurrentRequests??y1.concurrentRequests}),this.inFlightRequests=new Map,this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??y1.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new m1(this),this.peerRouting=new g1(this),this.cacheName=t.cacheName??y1.cacheName,this.cacheTTL=t.cacheTTL??y1.cacheTTL}get[hn](){return this.contentRouting}get[pn](){return this.peerRouting}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&>("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){gt("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=le([this.shutDownController.signal,n,t.signal]);F(1/0,n,o);let i=ee(),s=ee();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/providers/${e.toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(l.status===404)throw new Oe("No matching records found");if(l.status===422)throw new Hs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Pi("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let d=await l.json();for(let h of d.Providers){let f=this.#e(h);f!=null&&(yield f)}}else for await(let d of Lc(i1(l.body))){let h=this.#e(d);h!=null&&(yield h)}}catch(a){gt.error("getProviders errored:",a)}finally{o.clear(),s.resolve(),gt("getProviders finished: %c",e)}}async*getPeers(e,t={}){gt("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=le([this.shutDownController.signal,n,t.signal]);F(1/0,n,o);let i=ee(),s=ee();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(l.status===404)throw new Oe("No matching records found");if(l.status===422)throw new Hs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Pi("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let d=await l.json();for(let h of d.Peers){let f=this.#e(h);f!=null&&(yield f)}}else for await(let d of Lc(i1(l.body))){let h=this.#e(d);h!=null&&(yield h)}}catch(a){gt.error("getPeers errored:",a)}finally{o.clear(),s.resolve(),gt("getPeers finished: %c",e)}}async getIPNS(e,t={}){gt("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),o=le([this.shutDownController.signal,n,t.signal]);F(1/0,n,o);let i=ee(),s=ee();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${e}`;try{await i.promise;let c={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o},l=await this.#r(a,c);if(gt("getIPNS GET %s %d",a,l.status),l.status===404)throw new Oe("No matching records found");if(l.status===422)throw new Hs("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Pi("GET ipns response had no body");let u=await l.arrayBuffer(),d=new Uint8Array(u,0,u.byteLength);return t.validate!==!1&&await h1(Nc(e.multihash),d),_n(d)}catch(c){throw gt.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),s.resolve(),gt("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){gt("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),i=le([this.shutDownController.signal,o,n.signal]);F(1/0,o,i);let s=ee(),a=ee();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e}`;try{await s.promise;let l=Dc(t),u={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i},d=await this.#r(c,u);if(gt("putIPNS PUT %s %d",c,d.status),d.status!==200)throw new Pi("PUT ipns response had status other than 200")}catch(l){throw gt.error("putIPNS PUT %s error:",c,l.stack),l}finally{i.clear(),a.resolve(),gt("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(q)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:Fe(e.ID),Addrs:n,Protocols:t}}catch(t){gt.error("could not conform record to peer schema",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#r(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return gt("returning cached response for %s",o),c;await this.cache?.delete(e)}}let i=this.inFlightRequests.get(o);if(i!=null){let c=await i;return gt("deduplicating outgoing request for %s",o),c.clone()}let s=fetch(e,t).then(async c=>{if(this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,u=new Headers(c.headers);u.set("x-cache-expires",l.toString());let d=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:u});await this.cache.put(e,d)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,s),await s}};function H7(r,e={}){return new w1(new URL(r),e)}function Em(){return{filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}var q7="[a-fA-F\\d:]",Oo=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${q7})|(?<=${q7})(?=\\s|$))`:"",an="(?: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}",it="[a-fA-F\\d]{1,4}",b1=`
|
|
8
8
|
(?:
|
|
9
9
|
(?:${it}:){7}(?:${it}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
10
10
|
(?:${it}:){6}(?:${an}|:${it}|:)| // 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
|
|
@@ -35,7 +35,7 @@ a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host\r
|
|
|
35
35
|
a=ice-ufrag:`+e+`
|
|
36
36
|
`).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
37
37
|
a=ice-pwd:`+e+`
|
|
38
|
-
`),r}var ub=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),db=r=>[...Array(r)].map(()=>ub.at(Math.floor(Math.random()*ub.length))).join("");var hP=1e4,Uce=J("webrtc-direct").code,lb=J("certhash").code,wh=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"})})}[so]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Ae]=["@libp2p/transport"];async dial(e,t){let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){throw new uh("WebRTCTransport.createListener")}listenFilter(e){return e.filter(kc.exactMatch)}dialFilter(e){return this.listenFilter(e)}async _connect(e,t){let n=new AbortController,o=n.signal,i,s=e.getPeerId();s!=null&&(i=Fe(s));let a=Y3(yh(e)),c=await Hi.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:X3(a.code)}),l=new Hi({...await nl(this.init.rtcConfiguration),certificates:[c]});try{let u=new Promise((E,S)=>{let T=l.createDataChannel("",{negotiated:!0,id:0}),V=setTimeout(()=>{let L=`Data channel was never opened: state: ${T.readyState}`;this.log.error(L),this.metrics?.dialerEvents.increment({open_error:!0}),S(new ol("data",L))},hP);T.onopen=L=>{clearTimeout(V),E(T)},T.onerror=L=>{clearTimeout(V);let B=`Error opening a data channel for handshaking: ${L.target?.toString()??"not specified"}`;this.log.error(B),this.metrics?.dialerEvents.increment({unknown_error:!0}),S(new ol("data",B))}}),d="libp2p+webrtc+v1/"+db(32),h=await l.createOffer(),f=cb(h,d);await l.setLocalDescription(f);let p=ab(e,d);await l.setRemoteDescription(p);let m=await u,g=this.generateNoisePrologue(l,a.code,e),y=N1({prologueBytes:g})(this.components),b=pa({channel:m,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),w={...b,sink:b.sink.bind(b),source:async function*(){for await(let E of b.source)for(let S of E)yield S}()},x=new Ki(this.components,{peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),_=rl?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(_,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":x.close().catch(E=>{this.log.error("error closing connection",E)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let k=new Go(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await y.secureInbound(w,{signal:o,remotePeer:i}),await t.upgrader.upgradeOutbound(x,{skipProtection:!0,skipEncryption:!0,muxerFactory:k})}catch(u){throw l.close(),u}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw new P("no local certificate");let o=sb(e,{log:this.log});if(o==null)throw new P("no local fingerprint found");let i=o.trim().toLowerCase().replaceAll(":",""),s=M(i,"hex"),a=jt(t,s),c=Q3.decode(yh(n)),l=M("libp2p-webrtc-noise:");return Re([l,a.bytes,c])}};function fb(r){return e=>new wh(e,r)}function hb(r){return e=>new gh(e,r)}var pb=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",i)}function o(){n(),e()}function i(s){n(),t(s.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",o),r.addEventListener("error",i)})};var mb=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let o of n){try{await pb(r)}catch(i){if(i.message==="socket closed")break;throw i}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(o)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((o,i)=>{r.addEventListener("close",s=>{if(s.wasClean||s.code===1006)o();else{let a=Object.assign(new Error("ws error"),{event:s});i(a)}}),setTimeout(()=>{r.close()})})});var bb=ur(yb(),1);function wb(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var xb=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((i,s)=>{if(n){i();return}if(o!=null){s(o);return}let a=u=>{r.removeEventListener("open",c),r.removeEventListener("error",l),u()},c=()=>{a(i)},l=u=>{a(()=>{s(u.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let i=new bb.EventIterator(({push:s,stop:a,fail:c})=>{let l=d=>{let h=null;typeof d.data=="string"&&(h=M(d.data)),wb(d.data)&&(h=new Uint8Array(d.data)),d.data instanceof Uint8Array&&(h=d.data),h!=null&&s(h)},u=d=>{c(d.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",u),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",u),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let s of i)yield wb(s)?new Uint8Array(s):s}(),n=r.readyState===1,o;return r.addEventListener("open",()=>{n=!0,o=null}),r.addEventListener("close",()=>{n=!1,o=null}),r.addEventListener("error",i=>{n||(o=i.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var vb=(r,e)=>{e=e??{};let t=xb(r),n=e.remoteAddress,o=e.remotePort;if(r.url!=null)try{let s=new URL(r.url);n=s.hostname,o=parseInt(s.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:mb(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(s=>{r.addEventListener("close",()=>{s()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:o,socket:r}};var Eb=WebSocket;var mP={"http:":"ws:","https:":"wss:"},Sb="ws:",Ab=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??Sb}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??Sb,o=e.host,i=e.port!=null&&o?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${o}${i}${r}`}let t=new URL(r);for(let[n,o]of Object.entries(mP))t.protocol===n&&(t.protocol=o);return t};function Ib(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=Ab(r,t),o=new Eb(n.toString(),e.websocket);return vb(o,e)}function Tb(r){return r.filter(e=>_c.exactMatch(e)||Ti.exactMatch(e))}function _b(){throw new Error("WebSocket Servers can not be created in the browser!")}function kb(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),o=t.metrics,i=t.metricPrefix??"",s={log:n,async sink(a){try{await r.sink(async function*(){for await(let c of a)c instanceof Uint8Array?yield c:yield c.subarray()}())}catch(c){c.type!=="aborted"&&n.error(c)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(a={}){let c=Date.now();if(a.signal==null){let u=AbortSignal.timeout(500);a={...a,signal:u}}let l=()=>{let{host:u,port:d}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",u,d,Date.now()-c),this.abort(new Ft("Socket close timeout"))};a.signal?.addEventListener("abort",l);try{await r.close()}catch(u){n.error("error closing WebSocket gracefully",u),this.abort(u)}finally{a.signal?.removeEventListener("abort",l),s.timeline.close=Date.now()}},abort(a){let{host:c,port:l}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",c,l,a),r.destroy(),s.timeline.close=Date.now(),o?.increment({[`${i}error`]:!0})}};return r.socket.addEventListener("close",()=>{o?.increment({[`${i}close`]:!0}),s.timeline.close==null&&(s.timeline.close=Date.now())},{once:!0}),s}var J3=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[so]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Ae]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),o=kb(n,e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",o.remoteAddr);let i=await t.upgrader.upgradeOutbound(o,t);return this.log("outbound connection %s upgraded",o.remoteAddr),i}async _connect(e,t){t?.signal?.throwIfAborted();let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let o=ee(),i=Ib(Jd(e),this.init);i.socket.addEventListener("error",()=>{let s=new Zi(`Could not connect to ${e.toString()}`);this.log.error("connection error:",s),this.metrics?.dialerEvents.increment({error:!0}),o.reject(s)});try{t.onProgress?.(new G("websockets:open-connection")),await at(Promise.race([i.connected(),o.promise]),t.signal)}catch(s){throw t.signal?.aborted===!0&&this.metrics?.dialerEvents.increment({abort:!0}),i.close().catch(a=>{this.log.error("error closing raw socket",a)}),s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),i}createListener(e){return _b({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):Tb(e)}dialFilter(e){return this.listenFilter(e)}};function Cb(r={}){return e=>new J3(e,r)}var e4=ur(s1(),1);function Pb(r,e){let t=e.map((n,o)=>({record:_n(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===ir.ValidityType.EOL&&o.record.validityType===ir.ValidityType.EOL){let a=e4.default.fromString(n.record.validity).toDate(),c=e4.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 vh="2.5.0",Eh="js-libp2p";var Db="5.2.0-2666d64",Nb="helia";var Lb={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function Sh(r={}){let e=`${Nb}/${Db} ${Eh}/${vh} UserAgent=${globalThis.navigator.userAgent}`;return{privateKey:r.privateKey,dns:r.dns,addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[b3(),hb(),fb(),Cb()],connectionEncrypters:[N1()],streamMuxers:[U9(),Kw()],peerDiscovery:[ey(Lb)],services:{autoNAT:H9(),dcutr:wy(),delegatedRouting:()=>H7("https://delegated-ipfs.dev",Em()),dht:hw({clientMode:!0,validators:{ipns:h1},selectors:{ipns:Pb}}),identify:Ly({agentVersion:e}),identifyPush:By({agentVersion:e}),keychain:th(r.keychain),ping:Ww()}}}async function t4(r,e={}){let t=th(e)({datastore:r,logger:ko()}),n=new Ne("/pkcs8/self"),o;return await r.has(n)?o=await t.exportKey("self"):(o=await Qu(e.keyType??"Ed25519"),await t.importKey("self",o)),o}var yP=32,{code:wP}=J("dnsaddr"),r4=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},zi=async function(e,t={}){let n=t.maxRecursiveDepth??yP;if(n===0)throw new r4("Max recursive depth reached");let[,o]=e.stringTuples().find(([l])=>l===wP)??[],s=await(t?.dns??ud()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[mr.TXT]}),a=e.getPeerId(),c=[];for(let l of s.Answer){let u=l.data.replace(/["']/g,"").trim().split("=")[1];if(u==null||a!=null&&!u.includes(a))continue;let d=q(u);if(u.startsWith("/dnsaddr")){let h=await d.resolve({...t,maxRecursiveDepth:n-1});c.push(...h.map(f=>f.toString()))}else c.push(d.toString())}return c};var bP={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:zi}},transportManager:{faultTolerance:io.FATAL_ALL}};async function Bb(r){let e=la(bP,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new P("Private network is enforced, but no protector was provided");return e}var ma;(function(r){let e;(function(o){let i;o.codec=()=>(i==null&&(i=ne((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&s.value.byteLength>0&&(a.uint32(18),a.bytes(s.value)),c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={key:"",value:ae(0)},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{l.key=s.string();break}case 2:{l.value=s.bytes();break}default:{s.skipType(d&7);break}}}return l})),i),o.encode=s=>re(s,o.codec()),o.decode=(s,a)=>te(s,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let i;o.codec=()=>(i==null&&(i=ne((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&(a.uint32(18),Ih.codec().encode(s.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={key:""},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{l.key=s.string();break}case 2:{l.value=Ih.codec().decode(s,s.uint32(),{limits:c.limits?.value});break}default:{s.skipType(d&7);break}}}return l})),i),o.encode=s=>re(s,o.codec()),o.decode=(s,a)=>te(s,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ne((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.addresses!=null)for(let a of o.addresses)i.uint32(10),Ah.codec().encode(a,i);if(o.protocols!=null)for(let a of o.protocols)i.uint32(18),i.string(a);if(o.publicKey!=null&&(i.uint32(34),i.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(i.uint32(42),i.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())i.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},i);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())i.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},i);s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{if(s.limits?.addresses!=null&&a.addresses.length===s.limits.addresses)throw new Me('Decode error - map field "addresses" had too many elements');a.addresses.push(Ah.codec().decode(o,o.uint32(),{limits:s.limits?.addresses$}));break}case 2:{if(s.limits?.protocols!=null&&a.protocols.length===s.limits.protocols)throw new Me('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(s.limits?.metadata!=null&&a.metadata.size===s.limits.metadata)throw new ka('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(s.limits?.tags!=null&&a.tags.size===s.limits.tags)throw new ka('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:s.limits?.tags$value}});a.tags.set(u.key,u.value);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>re(o,r.codec()),r.decode=(o,i)=>te(o,r.codec(),i)})(ma||(ma={}));var Ah;(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,o={})=>{let i={multiaddr:ae(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.multiaddr=t.bytes();break}case 2:{i.isCertified=t.bool();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(Ah||(Ah={}));var Ih;(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,o={})=>{let i={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.value=t.uint32();break}case 2:{i.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(Ih||(Ih={}));function ga(r,e){let t=ma.decode(e);if(t.publicKey!=null&&r.publicKey==null){let i=tt(t.publicKey);r=Sn(i)}let n=new Map,o=BigInt(Date.now());for(let[i,s]of t.tags.entries())s.expiry!=null&&s.expiry<o||n.set(i,s);return{...t,id:r,addresses:t.addresses.map(({multiaddr:i,isCertified:s})=>({multiaddr:q(i),isCertified:s??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var n4="/peers/";function ya(r){if(!pl(r)||r.type==null)throw new P("Invalid PeerId");let e=r.toCID().toString();return new Ne(`${n4}${e}`)}async function Ob(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=q(o.multiaddr)),!Bo(o.multiaddr))throw new P("Multiaddr was invalid");if(!await e(r,o.multiaddr))continue;let i=o.isCertified??!1,s=o.multiaddr.toString(),a=n.get(s);a!=null?o.isCertified=a.isCertified||i:n.set(s,{multiaddr:o.multiaddr,isCertified:i})}return[...n.values()].sort((o,i)=>o.multiaddr.toString().localeCompare(i.multiaddr.toString())).map(({isCertified:o,multiaddr:i})=>({isCertified:o,multiaddr:i.bytes}))}async function _h(r,e,t,n){if(e==null)throw new P("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new P("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new P("peer id did not match existing peer id");let i=o?.addresses??[],s=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)&&(i=[],e.multiaddrs!=null&&i.push(...e.multiaddrs.map(h=>({isCertified:!1,multiaddr:h}))),e.addresses!=null&&i.push(...e.addresses)),e.protocols!=null&&(s=new Set(e.protocols)),e.metadata!=null){let h=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Th(h,{validate:Mb})}if(e.tags!=null){let h=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Th(h,{validate:Ub,map:Fb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&i.push(...e.multiaddrs.map(h=>({isCertified:!1,multiaddr:h}))),e.addresses!=null&&i.push(...e.addresses),e.protocols!=null&&(s=new Set([...s,...e.protocols])),e.metadata!=null){let h=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,p]of h)p==null?a.delete(f):a.set(f,p);a=Th([...a.entries()],{validate:Mb})}if(e.tags!=null){let h=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[p,m]of h)m==null?f.delete(p):f.set(p,m);c=Th([...f.entries()],{validate:Ub,map:Fb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Lt(o.id.publicKey):e.publicKey!=null?u=Lt(e.publicKey):r.publicKey!=null&&(u=Lt(r.publicKey));let d={addresses:await Ob(r,n.addressFilter??(async()=>!0),i),protocols:[...s.values()].sort((h,f)=>h.localeCompare(f)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return r.type!=="RSA"&&delete d.publicKey,d}function Th(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(([i],[s])=>i.localeCompare(s)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function Mb(r,e){if(typeof r!="string")throw new P("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new P("Metadata value must be a Uint8Array")}function Ub(r,e){if(typeof r!="string")throw new P("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new P("Tag value must be an integer");if(e.value<0||e.value>100)throw new P("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new P("Tag ttl must be an integer");if(e.ttl<0)throw new P("Tag ttl must be between greater than 0")}}function Fb(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 kh(r,e){let t=r.toString().split("/")[2],n=j.parse(t,ct),o=An(n);return ga(o,e)}function xP(r){return r==null?{}:{prefix:n4,filters:(r.filters??[]).map(e=>({key:t,value:n})=>e(kh(t,n))),orders:(r.orders??[]).map(e=>(t,n)=>e(kh(t.key,t.value),kh(n.key,n.value)))}}var Ch=class{peerId;datastore;lock;addressFilter;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=vi({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(ya(e))}async delete(e){if(this.peerId.equals(e))throw new P("Cannot delete self peer");await this.datastore.delete(ya(e))}async load(e){let t=await this.datastore.get(ya(e));return ga(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),i=await _h(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,i,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),i=await _h(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,i,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),i=await _h(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,i,n,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(xP(e??{}))){let o=kh(t,n);o.id.equals(this.peerId)||(yield o)}}async#e(e){try{let t=await this.datastore.get(ya(e)),n=ga(e,t);return{existingBuf:t,existingPeer:n}}catch(t){t.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",t)}return{}}async#t(e,t,n,o){let i=ma.encode(t);return n!=null&&oe(i,n)?{peer:ga(e,i),previous:o,updated:!1}:(await this.datastore.put(ya(e),i),{peer:ga(e,i),previous:o,updated:!0})}};var o4=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 Ch(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";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 Ri(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 Er.openAndCertify(e,Gt.DOMAIN),o=An(n.publicKey.toCID());if(t?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,o),!1;let i=Gt.createFromProtobuf(n.payload),s;try{s=await this.get(o)}catch(a){if(a.name!=="NotFoundError")throw a}if(s?.peerRecordEnvelope!=null){let a=await Er.createFromProtobuf(s.peerRecordEnvelope),c=Gt.createFromProtobuf(a.payload);if(c.seqNumber>=i.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!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 Vb(r,e={}){return new o4(r,e)}function $b(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Kb=864e13;var vP=448,i4=449,EP=53,SP=54,AP=55,IP=56,Ph=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=new Map}has(e){let t=this.findHost(e);for(let n of this.mappings.values())if(n.domain===t)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=vr(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?Kb-Date.now():0,lastVerified:o?Kb-Date.now():void 0})})}remove(e){let t=this.findHost(e),n=!1;for(let[o,i]of this.mappings.entries())i.domain===t&&(this.log("removing %s to %s DNS mapping %e",o,i.domain,new Error("where")),this.mappings.delete(o),n=n||i.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let i=e[n].multiaddr.stringTuples(),s=i[0][1];if(s!=null)for(let[a,c]of this.mappings.entries()){if(s!==a)continue;this.maybeAddSNITuple(i,c.domain)&&(e.splice(n,1),n--,t.push({multiaddr:q(`/${i.map(u=>[J(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(let n=0;n<e.length;n++)if(e[n][0]===vP&&e[n+1]?.[0]!==i4)return e.splice(n+1,0,[i4,t]),!0;return!1}confirm(e,t){let n=this.findHost(e),o=!1;for(let[i,s]of this.mappings.entries())s.domain===n&&(this.log("marking %s to %s DNS mapping as verified",i,s.domain),o=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return o}unconfirm(e,t){let n=this.findHost(e),o=!1;for(let[i,s]of this.mappings.entries())s.domain===n&&(this.log("removing verification of %s to %s DNS mapping",i,s.domain),o=o||s.verified,s.verified=!1,s.expires=Date.now()+t);return o}findHost(e){for(let t of e.stringTuples())if(t[0]===i4||t[0]===EP||t[0]===SP||t[0]===AP||t[0]===IP)return t[1]}};var s4=4,a4=41,c4=6,TP=273,Rh=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=new Map}has(e){let t=e.stringTuples();for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t[0][1])return!0;return!1}add(e,t,n,o=t,i="tcp"){let s=`${e}-${t}-${i}`,a=this.mappings.get(s)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:nn(n)?4:6,protocol:i,verified:!1,expires:0};a.push(c),this.mappings.set(s,a)}remove(e){let t=e.stringTuples(),n=t[0][1]??"",o=t[1][0]===c4?"tcp":"udp",i=parseInt(t[1][1]??"0"),s=!1;for(let[a,c]of this.mappings.entries()){for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===n&&u.externalPort===i&&u.protocol===o&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,i,o),s=s||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return s}getAll(e){let t=[];for(let{multiaddr:n}of e){let o=n.stringTuples(),i;if((o[0][0]===s4||o[0][0]===a4)&&o[1][0]===c4?i=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===s4||o[0][0]===a4)&&o[1][0]===TP&&(i=`${o[0][1]}-${o[1][1]}-udp`),i==null)continue;let s=this.mappings.get(i);if(s!=null)for(let a of s)o[0][0]=a.externalFamily===4?s4:a4,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,t.push({multiaddr:q(`/${o.map(c=>[J(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}confirm(e,t){let o=e.stringTuples()[0][1],i=!1;for(let s of this.mappings.values())for(let a of s)a.externalIp===o&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),i=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return i}unconfirm(e,t){let n=e.stringTuples(),o=n[0][1]??"",i=n[1][0]===c4?"tcp":"udp",s=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===o&&u.externalPort===s&&u.protocol===i&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,o,s,i),a=a||u.verified,u.verified=!1,u.expires=Date.now()+t)}return a}};function Hb(r){try{let[[e,t]]=r.stringTuples();if(t==null)return!1;if(e===4)return t.startsWith("169.254.");if(e===41)return t.toLowerCase().startsWith("fe80")}catch{}return!1}var _P={maxObservedAddresses:10},Dh=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=t.maxObservedAddresses??_P.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Br(e)||Hb(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:q(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},i=o.verified;return o.verified=!0,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),i}};var kP={maxObservedAddresses:10},Nh=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=t.maxObservedAddresses??kP.maxObservedAddresses}get(e,t){if(Br(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!1,expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},i=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),i}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},i=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),i}toKey(e){let t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}};var qb=6e4,zb={maxObservedAddresses:10,addressVerificationTTL:qb*10,addressVerificationRetry:qb*5},CP=r=>r;function l4(r,e){let t=r.getPeerId();return t!=null&&Fe(t).equals(e)&&(r=r.decapsulate(q(`/p2p/${e.toString()}`))),r}var Lh=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:i=[]}=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.appendAnnounce=new Set(i.map(s=>s.toString())),this.observed=new Dh(e,t),this.dnsMappings=new Ph(e,t),this.ipMappings=new Rh(e,t),this.transportAddresses=new Nh(e,t),this.announceFilter=t.announceFilter??CP,this.observedAddressFilter=rr(1024),this.addressVerificationTTL=t.addressVerificationTTL??zb.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??zb.addressVerificationRetry,this._updatePeerStoreAddresses=$b(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().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=>q(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>q(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>q(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=e.stringTuples(),n=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=l4(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=l4(e,this.components.peerId);let n=!0;(t?.type==="observed"||this.observed.has(e))&&(n=this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)),(t?.type==="transport"||this.transportAddresses.has(e))&&(n=this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&(n=this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&(n=this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=l4(e,this.components.peerId);let n=!1;this.observed.has(e)&&(n=this.observed.remove(e)),this.transportAddresses.has(e)&&(n=this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)),this.dnsMappings.has(e)&&(n=this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)),this.ipMappings.has(e)&&(n=this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=q(n);return o.protos().pop()?.path===!0||o.getPeerId()===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return e.map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];return t=t.concat(this.components.transportManager.getAddrs().map(n=>this.transportAddresses.get(n,this.addressVerificationTTL))),t=t.concat(this.getAppendAnnounceAddrs().map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(q(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,i="tcp"){this.ipMappings.add(e,t,n,o,i),this.observed.removePrefixed(`/ip${nn(n)?4:6}/${n}/${i}/${o}`)}removePublicAddressMapping(e,t,n,o=t,i="tcp"){this.ipMappings.remove(q(`/ip${nn(n)?4:6}/${n}/${i}/${o}`))&&this._updatePeerStoreAddresses()}};var Wb;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Wb||(Wb={}));var Bh=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Oh=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},wa=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},al=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Mh=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Uh=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Fh=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},cl=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Wi=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Vh=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},$h=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Gi=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Qi=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Kh=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var u4=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=ko())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>vl(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")}},RP=["metrics","connectionProtector","dns"],DP=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Gb(r={}){let e=new u4(r);return new Proxy(e,{get(n,o,i){if(typeof o=="string"&&!DP.includes(o)){let s=e.components[o];if(s==null&&!RP.includes(o))throw new Bh(`${o} not set`);return s}return Reflect.get(n,o,i)},set(n,o,i){return typeof o=="string"?e.components[o]=i:Reflect.set(n,o,i),!0}})}function Qb(r){let e={};for(let t of Object.values(r.components))for(let n of NP(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of LP(t))if(e[n]!==!0)throw new Oh(`Service "${BP(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function NP(r){return Array.isArray(r?.[Ae])?r[Ae]:[]}function LP(r){return Array.isArray(r?.[dr])?r[dr]:[]}function BP(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var OP=4,MP=41;function Yb(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{if(Ti.matches(e))return!1;let t=e.stringTuples();return t[0][0]===OP||t[0][0]===MP?!!vr(`${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 Hh(r){if(pl(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:Fe(t),r.forEach(n=>{if(!Bo(n))throw new ao("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(e!=null)throw new P("Multiaddrs must all have the same peer id or have no peer id")}else{let i=Fe(o);if(e?.equals(i)!==!0)throw new P("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var UP=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Xb(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??UP;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var jb="last-dial-failure",Zb="last-dial-success";var qh=100,zh=50;async function Jb(r,e){let t=!1;for(let o of Vs.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}function ll(r){try{let e;if(typeof r=="string"?e=q(r):e=r,!e.protoNames().includes("ipcidr")){let n=e.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(n)}return fm(e)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var FP={maxConnections:qh,allow:[]},Wh=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??FP.maxConnections,this.allow=(t.allow??[]).map(n=>ll(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}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 pt;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((u,d)=>u+d.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(e,n),i=Math.max(t-this.maxConnections,0),s=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>l.contains(a.remoteAddr.nodeAddress().address))||s.push(a),s.length===i)break;await Promise.all(s.map(async a=>{await Xb(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:s})}sortConnections(e,t){return e.sort((n,o)=>{let i=n.timeline.open,s=o.timeline.open;return i<s?1:i>s?-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 i=t.get(n.remotePeer)??0,s=t.get(o.remotePeer)??0;return i>s?1:i<s?-1:0})}};var Gh=class extends Vt{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function VP(r,e){let t=Tc.exactMatch(r.multiaddr),n=Tc.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=_c.exactMatch(r.multiaddr),i=_c.exactMatch(e.multiaddr);if(o&&!i)return-1;if(!o&&i)return 1;let s=Ti.exactMatch(r.multiaddr),a=Ti.exactMatch(e.multiaddr);if(s&&!a)return-1;if(!s&&a)return 1;let c=Cc.exactMatch(r.multiaddr),l=Cc.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=kc.exactMatch(r.multiaddr),d=kc.exactMatch(e.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;let h=tm.exactMatch(r.multiaddr),f=tm.exactMatch(e.multiaddr);return h&&!f?-1:!h&&f?1:0}function $P(r,e){let t=Br(r.multiaddr),n=Br(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function KP(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function HP(r,e){let t=or.exactMatch(r.multiaddr),n=or.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function ex(r){return r.sort(VP).sort(KP).sort(HP).sort($P)}var Qh={maxParallelDials:zh,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:zi}},Yh=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Qh.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Qh.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Qh.dialTimeout,this.connections=t.connections??new pt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,F(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))Vs.set(n,o);this.queue=new Gh({concurrency:t.maxParallelDials??Qh.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==Ft.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,F(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Hh(e),i=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(i?.status==="open")return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new G("dial-queue:already-connected")),i;let s=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(s!=null){this.log("joining existing dial target for %p",n);for(let a of o)s.options.multiaddrs.add(a.toString());return t.onProgress?.(new G("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Nn("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new G("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new G("dial-queue:start-dial"));let c=le([this.shutDownController.signal,a.signal]);F(1/0,c);let l;try{l=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new G("dial-queue:calculated-addresses",l)),l.map(({multiaddr:u})=>u.toString()).forEach(u=>{a?.multiaddrs.add(u)})}catch(u){throw c.clear(),u}try{let u=0,d=[];for(let h of l){if(u===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",u,n),new Nn("Peer had more than maxPeerAddrsToDial");u++;try{let f=await this.components.transportManager.dial(h.multiaddr,{...a,signal:c});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(f.remotePeer,{multiaddrs:[f.remoteAddr],metadata:{[Zb]:M(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}return f}catch(f){if(this.log.error("dial failed to %a",h.multiaddr,f),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[jb]: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 Ur(f.message);d.push(f)}}throw d.length===1?d[0]:new AggregateError(d,"All multiaddr dials failed")}finally{c.clear()}},{peerId:n,priority:t.priority??p4,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(d=>({multiaddr:q(d),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Nn("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new cl("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let d=await this.components.peerStore.get(e);o.push(...d.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:h})=>h.toString()))}catch(d){if(d.name!=="NotFoundError")throw d}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let d=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:h})=>h.toString())),o.push(...d.multiaddrs.map(h=>({multiaddr:h,isCertified:!1})))}catch(d){d.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,d)}}}let i=(await Promise.all(o.map(async d=>{let h=await Jb(d.multiaddr,{dns:this.components.dns,...n,log:this.log});return h.length===1&&h[0].equals(d.multiaddr)?d:h.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let d=`/p2p/${e.toString()}`;i=i.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(d),isCertified:h.isCertified}:h)}let s=i.filter(d=>{if(this.components.transportManager.dialTransportForMultiaddr(d.multiaddr)==null)return!1;let h=d.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),a=new Map;for(let d of s){let h=d.multiaddr.toString(),f=a.get(h);if(f!=null){f.isCertified=f.isCertified||d.isCertified||!1;continue}a.set(h,d)}let c=[...a.values()];if(c.length===0)throw new Wi("The dial request has no valid addresses");let l=[];for(let d of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(d.multiaddr)||l.push(d);let u=this.addressSorter==null?ex(l):l.sort(this.addressSorter);if(u.length===0)throw new cl("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:d})=>d.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:d})=>d.toString())),u}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.runOnLimitedConnection===!1?n.find(o=>!or.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var ax=ur(ix(),1);var zP=Object.prototype.toString,WP=r=>zP.call(r)==="[object Error]",GP=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function m4(r){return r&&WP(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:GP.has(r.message):!1}var g4=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},sx=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function y4(r,e){return new Promise((t,n)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let o=ax.default.operation(e),i=()=>{o.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",i,{once:!0});let s=()=>{e.signal?.removeEventListener("abort",i),o.stop()};o.attempt(async a=>{try{let c=await r(a);s(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof g4)throw c.originalError;if(c instanceof TypeError&&!m4(c))throw c;if(sx(c,a,e),await e.shouldRetry(c)||(o.stop(),n(c)),await e.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(l){sx(l,a,e),s(),n(l)}}})})}var Xh=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new wt({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);cx(t)&&(this.queue.has(e)||this.queue.add(async n=>{await y4(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(i){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,i),i}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(i=>{i.startsWith(oo)&&(o[i]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>cx(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function cx(r){for(let e of r.tags.keys())if(e.startsWith(oo))return!0;return!1}var p4=50,w4={maxConnections:qh,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},jh=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??w4.maxConnections,this.maxConnections<1)throw new P("Connection Manager maxConnections must be greater than 0");this.connections=new pt,this.started=!1,this.peerId=e.peerId,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.allow=(t.allow??[]).map(n=>ll(n)),this.deny=(t.deny??[]).map(n=>ll(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??w4.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ha({points:t.inboundConnectionThreshold??w4.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Wh({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:t.allow?.map(n=>q(n))}),this.dialQueue=new Yh(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??zh,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:zi},connections:this.connections}),this.reconnectQueue=new Xh({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;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 i=`${o.direction} ${o.protocol??"unnegotiated"}`;e[i]=(e[i]??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 i={};for(let s of o.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;i[a]=(i[a]??0)+1}for(let[s,a]of Object.entries(i))e[s]=e[s]??[],e[s].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((s,a)=>s-a);let i=Math.floor(o.length*.9);t[n]=o[i]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await yt(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Ct(this.reconnectQueue,this.dialQueue,this.connectionPruner);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")}getMaxConnections(){return this.maxConnections}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}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),i=this.connections.get(n)??[];i.push(t),this.connections.set(n,i),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,i=(this.connections.get(n)??[]).filter(s=>s.id!==t.id);this.connections.set(n,i),i.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),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.started)throw new Fr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n}=Hh(e);if(this.peerId.equals(n))throw new Ji("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),t.onProgress?.(new G("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??p4});if(o.status!=="open")throw new ji("Remote closed connection during opening");let i=this.connections.get(o.remotePeer);i==null&&(i=[],this.connections.set(o.remotePeer,i));let s=!1;for(let a of i)if(a.id===o.id&&(s=!0),t.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new ao("Duplicate multiaddr connection")),a;return s||i.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(i){o.abort(i)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>o.contains(e.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>o.contains(e.remoteAddr.nodeAddress().address)))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=>q(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var XP=1e4,jP="1.0.0",ZP="ping",JP="ipfs",lx=32,eR=!0,Zh=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??JP}/${ZP}/${jP}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??XP,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??eR,this.timeout=new dn({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Ae]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,F(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),i=Ni(o);t=Date.now(),await Promise.all([i.write(qt(lx),{signal:n}),i.read(lx,{signal:n})]),e.rtt=Date.now()-t,await i.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var Jh=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:$(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:$(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";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 wa("No content routers available");let n=this,o=new zt;for await(let i of Kt(...n.routers.map(s=>s.findProviders(e,t))))i!=null&&(i.multiaddrs.length>0&&await this.components.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),!o.has(i.id)&&(o.add(i.id),yield i))}async provide(e,t={}){if(this.routers.length===0)throw new wa("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new wa("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Fr;await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Fr;return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var e0=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??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:$(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new al("No peer routers available");if(e.toString()===this.peerId.toString())throw new Mh("Should not try to find self");let n=this,o=Kt(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),i;throw new Oe}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new al("No peer routers available");let n=this,o=rr(1024);for await(let i of un(async function*(){let s=Kt(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of s)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}}()))i!=null&&(i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),!o.has(i.id.toMultihash().bytes)&&(o.add(i.id.toMultihash().bytes),yield i))}};var t0=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,F(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,F(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=le([this.shutdownController.signal,e?.signal]);F(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ee(),yield(await fr(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,F(1/0,this.walkController.signal);let e=le([this.walkController.signal,this.shutdownController.signal]);F(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=qt(32),i=Date.now();for await(let s of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-i,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:s}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await at(this.needNext.promise,e)),i=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).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 b4=32,x4=64,r0=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)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new Uh(`No handler registered for protocol ${e}`);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 Fh(`Handler already registered for protocol ${e}`);let o=la.bind({ignoreUndefined:!0})({maxInboundStreams:b4,maxOutboundStreams:x4},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 P("invalid topology");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 i=this.topologies.get(o);if(i!=null)for(let s of i.values())s.filter?.has(t)!==!1&&(s.filter?.remove(t),s.onDisconnect?.(t))}}).catch(n=>{n.name!=="NotFoundError"&&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(i=>!t.protocols.includes(i));for(let i of o){let s=this.topologies.get(i);if(s!=null)for(let a of s.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 i of t){let s=this.topologies.get(i);if(s!=null)for(let a of s.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var n0=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=Fd({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??io.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new P("Transport must have a valid tag");if(this.transports.has(t))throw new P(`There is already a transport with the tag ${t}`);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 Kh(`No transport available for address ${String(e)}`);return t?.onProgress?.(new G("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}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 Fr("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 i=o.listenFilter(e),s=[];for(let l of i){this.log("creating listener for %s on %a",n,l);let u=o.createListener({upgrader:this.components.upgrader}),d=this.listeners.get(n)??[];d==null&&(d=[],this.listeners.set(n,d)),d.push(u),u.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:u})}),u.addEventListener("close",()=>{let h=d.findIndex(f=>f===u);d.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:u})}),s.push(u.listen(l))}if(s.length===0){t.push(n);continue}if((await Promise.allSettled(s)).find(l=>l.status==="fulfilled")==null&&this.faultTolerance!==io.NO_FATAL)throw new Wi(`Transport (${n}) could not listen on any available address`)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===io.FATAL_ALL)throw new Wi(n);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 _t="/multistream/1.0.0";var tR=M(`
|
|
38
|
+
`),r}var ub=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),db=r=>[...Array(r)].map(()=>ub.at(Math.floor(Math.random()*ub.length))).join("");var hP=1e4,Uce=J("webrtc-direct").code,lb=J("certhash").code,wh=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"})})}[so]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Ae]=["@libp2p/transport"];async dial(e,t){let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){throw new uh("WebRTCTransport.createListener")}listenFilter(e){return e.filter(kc.exactMatch)}dialFilter(e){return this.listenFilter(e)}async _connect(e,t){let n=new AbortController,o=n.signal,i,s=e.getPeerId();s!=null&&(i=Fe(s));let a=Y3(yh(e)),c=await Hi.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:X3(a.code)}),l=new Hi({...await nl(this.init.rtcConfiguration),certificates:[c]});try{let u=new Promise((E,S)=>{let T=l.createDataChannel("",{negotiated:!0,id:0}),V=setTimeout(()=>{let L=`Data channel was never opened: state: ${T.readyState}`;this.log.error(L),this.metrics?.dialerEvents.increment({open_error:!0}),S(new ol("data",L))},hP);T.onopen=L=>{clearTimeout(V),E(T)},T.onerror=L=>{clearTimeout(V);let B=`Error opening a data channel for handshaking: ${L.target?.toString()??"not specified"}`;this.log.error(B),this.metrics?.dialerEvents.increment({unknown_error:!0}),S(new ol("data",B))}}),d="libp2p+webrtc+v1/"+db(32),h=await l.createOffer(),f=cb(h,d);await l.setLocalDescription(f);let p=ab(e,d);await l.setRemoteDescription(p);let m=await u,g=this.generateNoisePrologue(l,a.code,e),y=N1({prologueBytes:g})(this.components),b=pa({channel:m,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),w={...b,sink:b.sink.bind(b),source:async function*(){for await(let E of b.source)for(let S of E)yield S}()},x=new Ki(this.components,{peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),_=rl?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(_,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":x.close().catch(E=>{this.log.error("error closing connection",E)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let k=new Go(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await y.secureInbound(w,{signal:o,remotePeer:i}),await t.upgrader.upgradeOutbound(x,{skipProtection:!0,skipEncryption:!0,muxerFactory:k})}catch(u){throw l.close(),u}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw new P("no local certificate");let o=sb(e,{log:this.log});if(o==null)throw new P("no local fingerprint found");let i=o.trim().toLowerCase().replaceAll(":",""),s=M(i,"hex"),a=jt(t,s),c=Q3.decode(yh(n)),l=M("libp2p-webrtc-noise:");return Re([l,a.bytes,c])}};function fb(r){return e=>new wh(e,r)}function hb(r){return e=>new gh(e,r)}var pb=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",i)}function o(){n(),e()}function i(s){n(),t(s.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",o),r.addEventListener("error",i)})};var mb=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let o of n){try{await pb(r)}catch(i){if(i.message==="socket closed")break;throw i}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(o)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((o,i)=>{r.addEventListener("close",s=>{if(s.wasClean||s.code===1006)o();else{let a=Object.assign(new Error("ws error"),{event:s});i(a)}}),setTimeout(()=>{r.close()})})});var bb=ur(yb(),1);function wb(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var xb=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((i,s)=>{if(n){i();return}if(o!=null){s(o);return}let a=u=>{r.removeEventListener("open",c),r.removeEventListener("error",l),u()},c=()=>{a(i)},l=u=>{a(()=>{s(u.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let i=new bb.EventIterator(({push:s,stop:a,fail:c})=>{let l=d=>{let h=null;typeof d.data=="string"&&(h=M(d.data)),wb(d.data)&&(h=new Uint8Array(d.data)),d.data instanceof Uint8Array&&(h=d.data),h!=null&&s(h)},u=d=>{c(d.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",u),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",u),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let s of i)yield wb(s)?new Uint8Array(s):s}(),n=r.readyState===1,o;return r.addEventListener("open",()=>{n=!0,o=null}),r.addEventListener("close",()=>{n=!1,o=null}),r.addEventListener("error",i=>{n||(o=i.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var vb=(r,e)=>{e=e??{};let t=xb(r),n=e.remoteAddress,o=e.remotePort;if(r.url!=null)try{let s=new URL(r.url);n=s.hostname,o=parseInt(s.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:mb(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(s=>{r.addEventListener("close",()=>{s()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:o,socket:r}};var Eb=WebSocket;var mP={"http:":"ws:","https:":"wss:"},Sb="ws:",Ab=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??Sb}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??Sb,o=e.host,i=e.port!=null&&o?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${o}${i}${r}`}let t=new URL(r);for(let[n,o]of Object.entries(mP))t.protocol===n&&(t.protocol=o);return t};function Ib(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=Ab(r,t),o=new Eb(n.toString(),e.websocket);return vb(o,e)}function Tb(r){return r.filter(e=>_c.exactMatch(e)||Ti.exactMatch(e))}function _b(){throw new Error("WebSocket Servers can not be created in the browser!")}function kb(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),o=t.metrics,i=t.metricPrefix??"",s={log:n,async sink(a){try{await r.sink(async function*(){for await(let c of a)c instanceof Uint8Array?yield c:yield c.subarray()}())}catch(c){c.type!=="aborted"&&n.error(c)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(a={}){let c=Date.now();if(a.signal==null){let u=AbortSignal.timeout(500);a={...a,signal:u}}let l=()=>{let{host:u,port:d}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",u,d,Date.now()-c),this.abort(new Ft("Socket close timeout"))};a.signal?.addEventListener("abort",l);try{await r.close()}catch(u){n.error("error closing WebSocket gracefully",u),this.abort(u)}finally{a.signal?.removeEventListener("abort",l),s.timeline.close=Date.now()}},abort(a){let{host:c,port:l}=s.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",c,l,a),r.destroy(),s.timeline.close=Date.now(),o?.increment({[`${i}error`]:!0})}};return r.socket.addEventListener("close",()=>{o?.increment({[`${i}close`]:!0}),s.timeline.close==null&&(s.timeline.close=Date.now())},{once:!0}),s}var J3=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[so]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Ae]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),o=kb(n,e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",o.remoteAddr);let i=await t.upgrader.upgradeOutbound(o,t);return this.log("outbound connection %s upgraded",o.remoteAddr),i}async _connect(e,t){t?.signal?.throwIfAborted();let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let o=ee(),i=Ib(Jd(e),this.init);i.socket.addEventListener("error",()=>{let s=new Zi(`Could not connect to ${e.toString()}`);this.log.error("connection error:",s),this.metrics?.dialerEvents.increment({error:!0}),o.reject(s)});try{t.onProgress?.(new G("websockets:open-connection")),await at(Promise.race([i.connected(),o.promise]),t.signal)}catch(s){throw t.signal?.aborted===!0&&this.metrics?.dialerEvents.increment({abort:!0}),i.close().catch(a=>{this.log.error("error closing raw socket",a)}),s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),i}createListener(e){return _b({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):Tb(e)}dialFilter(e){return this.listenFilter(e)}};function Cb(r={}){return e=>new J3(e,r)}var e4=ur(s1(),1);function Pb(r,e){let t=e.map((n,o)=>({record:_n(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===ir.ValidityType.EOL&&o.record.validityType===ir.ValidityType.EOL){let a=e4.default.fromString(n.record.validity).toDate(),c=e4.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 vh="2.5.0",Eh="js-libp2p";var Db="5.2.0-c7024de",Nb="helia";var Lb={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function Sh(r={}){let e=`${Nb}/${Db} ${Eh}/${vh} UserAgent=${globalThis.navigator.userAgent}`;return{privateKey:r.privateKey,dns:r.dns,addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[b3(),hb(),fb(),Cb()],connectionEncrypters:[N1()],streamMuxers:[U9(),Kw()],peerDiscovery:[ey(Lb)],services:{autoNAT:H9(),dcutr:wy(),delegatedRouting:()=>H7("https://delegated-ipfs.dev",Em()),dht:hw({clientMode:!0,validators:{ipns:h1},selectors:{ipns:Pb}}),identify:Ly({agentVersion:e}),identifyPush:By({agentVersion:e}),keychain:th(r.keychain),ping:Ww()}}}async function t4(r,e={}){let t=th(e)({datastore:r,logger:ko()}),n=new Ne("/pkcs8/self"),o;return await r.has(n)?o=await t.exportKey("self"):(o=await Qu(e.keyType??"Ed25519"),await t.importKey("self",o)),o}var yP=32,{code:wP}=J("dnsaddr"),r4=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}},zi=async function(e,t={}){let n=t.maxRecursiveDepth??yP;if(n===0)throw new r4("Max recursive depth reached");let[,o]=e.stringTuples().find(([l])=>l===wP)??[],s=await(t?.dns??ud()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[mr.TXT]}),a=e.getPeerId(),c=[];for(let l of s.Answer){let u=l.data.replace(/["']/g,"").trim().split("=")[1];if(u==null||a!=null&&!u.includes(a))continue;let d=q(u);if(u.startsWith("/dnsaddr")){let h=await d.resolve({...t,maxRecursiveDepth:n-1});c.push(...h.map(f=>f.toString()))}else c.push(d.toString())}return c};var bP={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:zi}},transportManager:{faultTolerance:io.FATAL_ALL}};async function Bb(r){let e=la(bP,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new P("Private network is enforced, but no protector was provided");return e}var ma;(function(r){let e;(function(o){let i;o.codec=()=>(i==null&&(i=ne((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&s.value.byteLength>0&&(a.uint32(18),a.bytes(s.value)),c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={key:"",value:ae(0)},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{l.key=s.string();break}case 2:{l.value=s.bytes();break}default:{s.skipType(d&7);break}}}return l})),i),o.encode=s=>re(s,o.codec()),o.decode=(s,a)=>te(s,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let i;o.codec=()=>(i==null&&(i=ne((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&(a.uint32(18),Ih.codec().encode(s.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={key:""},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let d=s.uint32();switch(d>>>3){case 1:{l.key=s.string();break}case 2:{l.value=Ih.codec().decode(s,s.uint32(),{limits:c.limits?.value});break}default:{s.skipType(d&7);break}}}return l})),i),o.encode=s=>re(s,o.codec()),o.decode=(s,a)=>te(s,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ne((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.addresses!=null)for(let a of o.addresses)i.uint32(10),Ah.codec().encode(a,i);if(o.protocols!=null)for(let a of o.protocols)i.uint32(18),i.string(a);if(o.publicKey!=null&&(i.uint32(34),i.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(i.uint32(42),i.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())i.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},i);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())i.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},i);s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{if(s.limits?.addresses!=null&&a.addresses.length===s.limits.addresses)throw new Me('Decode error - map field "addresses" had too many elements');a.addresses.push(Ah.codec().decode(o,o.uint32(),{limits:s.limits?.addresses$}));break}case 2:{if(s.limits?.protocols!=null&&a.protocols.length===s.limits.protocols)throw new Me('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(s.limits?.metadata!=null&&a.metadata.size===s.limits.metadata)throw new ka('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(s.limits?.tags!=null&&a.tags.size===s.limits.tags)throw new ka('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:s.limits?.tags$value}});a.tags.set(u.key,u.value);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>re(o,r.codec()),r.decode=(o,i)=>te(o,r.codec(),i)})(ma||(ma={}));var Ah;(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,o={})=>{let i={multiaddr:ae(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.multiaddr=t.bytes();break}case 2:{i.isCertified=t.bool();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(Ah||(Ah={}));var Ih;(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,o={})=>{let i={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.value=t.uint32();break}case 2:{i.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(Ih||(Ih={}));function ga(r,e){let t=ma.decode(e);if(t.publicKey!=null&&r.publicKey==null){let i=tt(t.publicKey);r=Sn(i)}let n=new Map,o=BigInt(Date.now());for(let[i,s]of t.tags.entries())s.expiry!=null&&s.expiry<o||n.set(i,s);return{...t,id:r,addresses:t.addresses.map(({multiaddr:i,isCertified:s})=>({multiaddr:q(i),isCertified:s??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var n4="/peers/";function ya(r){if(!pl(r)||r.type==null)throw new P("Invalid PeerId");let e=r.toCID().toString();return new Ne(`${n4}${e}`)}async function Ob(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=q(o.multiaddr)),!Bo(o.multiaddr))throw new P("Multiaddr was invalid");if(!await e(r,o.multiaddr))continue;let i=o.isCertified??!1,s=o.multiaddr.toString(),a=n.get(s);a!=null?o.isCertified=a.isCertified||i:n.set(s,{multiaddr:o.multiaddr,isCertified:i})}return[...n.values()].sort((o,i)=>o.multiaddr.toString().localeCompare(i.multiaddr.toString())).map(({isCertified:o,multiaddr:i})=>({isCertified:o,multiaddr:i.bytes}))}async function _h(r,e,t,n){if(e==null)throw new P("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new P("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new P("peer id did not match existing peer id");let i=o?.addresses??[],s=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)&&(i=[],e.multiaddrs!=null&&i.push(...e.multiaddrs.map(h=>({isCertified:!1,multiaddr:h}))),e.addresses!=null&&i.push(...e.addresses)),e.protocols!=null&&(s=new Set(e.protocols)),e.metadata!=null){let h=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Th(h,{validate:Mb})}if(e.tags!=null){let h=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Th(h,{validate:Ub,map:Fb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&i.push(...e.multiaddrs.map(h=>({isCertified:!1,multiaddr:h}))),e.addresses!=null&&i.push(...e.addresses),e.protocols!=null&&(s=new Set([...s,...e.protocols])),e.metadata!=null){let h=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[f,p]of h)p==null?a.delete(f):a.set(f,p);a=Th([...a.entries()],{validate:Mb})}if(e.tags!=null){let h=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),f=new Map(c);for(let[p,m]of h)m==null?f.delete(p):f.set(p,m);c=Th([...f.entries()],{validate:Ub,map:Fb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Lt(o.id.publicKey):e.publicKey!=null?u=Lt(e.publicKey):r.publicKey!=null&&(u=Lt(r.publicKey));let d={addresses:await Ob(r,n.addressFilter??(async()=>!0),i),protocols:[...s.values()].sort((h,f)=>h.localeCompare(f)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return r.type!=="RSA"&&delete d.publicKey,d}function Th(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(([i],[s])=>i.localeCompare(s)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function Mb(r,e){if(typeof r!="string")throw new P("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new P("Metadata value must be a Uint8Array")}function Ub(r,e){if(typeof r!="string")throw new P("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new P("Tag value must be an integer");if(e.value<0||e.value>100)throw new P("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new P("Tag ttl must be an integer");if(e.ttl<0)throw new P("Tag ttl must be between greater than 0")}}function Fb(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 kh(r,e){let t=r.toString().split("/")[2],n=j.parse(t,ct),o=An(n);return ga(o,e)}function xP(r){return r==null?{}:{prefix:n4,filters:(r.filters??[]).map(e=>({key:t,value:n})=>e(kh(t,n))),orders:(r.orders??[]).map(e=>(t,n)=>e(kh(t.key,t.value),kh(n.key,n.value)))}}var Ch=class{peerId;datastore;lock;addressFilter;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=vi({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(ya(e))}async delete(e){if(this.peerId.equals(e))throw new P("Cannot delete self peer");await this.datastore.delete(ya(e))}async load(e){let t=await this.datastore.get(ya(e));return ga(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),i=await _h(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,i,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),i=await _h(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,i,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),i=await _h(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,i,n,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(xP(e??{}))){let o=kh(t,n);o.id.equals(this.peerId)||(yield o)}}async#e(e){try{let t=await this.datastore.get(ya(e)),n=ga(e,t);return{existingBuf:t,existingPeer:n}}catch(t){t.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",t)}return{}}async#t(e,t,n,o){let i=ma.encode(t);return n!=null&&oe(i,n)?{peer:ga(e,i),previous:o,updated:!1}:(await this.datastore.put(ya(e),i),{peer:ga(e,i),previous:o,updated:!0})}};var o4=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 Ch(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";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 Ri(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 Er.openAndCertify(e,Gt.DOMAIN),o=An(n.publicKey.toCID());if(t?.equals(o)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,o),!1;let i=Gt.createFromProtobuf(n.payload),s;try{s=await this.get(o)}catch(a){if(a.name!=="NotFoundError")throw a}if(s?.peerRecordEnvelope!=null){let a=await Er.createFromProtobuf(s.peerRecordEnvelope),c=Gt.createFromProtobuf(a.payload);if(c.seqNumber>=i.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,i.seqNumber),!1}return await this.patch(i.peerId,{peerRecordEnvelope:e,addresses:i.multiaddrs.map(a=>({isCertified:!0,multiaddr:a}))}),!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 Vb(r,e={}){return new o4(r,e)}function $b(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Kb=864e13;var vP=448,i4=449,EP=53,SP=54,AP=55,IP=56,Ph=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=new Map}has(e){let t=this.findHost(e);for(let n of this.mappings.values())if(n.domain===t)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=vr(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?Kb-Date.now():0,lastVerified:o?Kb-Date.now():void 0})})}remove(e){let t=this.findHost(e),n=!1;for(let[o,i]of this.mappings.entries())i.domain===t&&(this.log("removing %s to %s DNS mapping %e",o,i.domain,new Error("where")),this.mappings.delete(o),n=n||i.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let i=e[n].multiaddr.stringTuples(),s=i[0][1];if(s!=null)for(let[a,c]of this.mappings.entries()){if(s!==a)continue;this.maybeAddSNITuple(i,c.domain)&&(e.splice(n,1),n--,t.push({multiaddr:q(`/${i.map(u=>[J(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(let n=0;n<e.length;n++)if(e[n][0]===vP&&e[n+1]?.[0]!==i4)return e.splice(n+1,0,[i4,t]),!0;return!1}confirm(e,t){let n=this.findHost(e),o=!1;for(let[i,s]of this.mappings.entries())s.domain===n&&(this.log("marking %s to %s DNS mapping as verified",i,s.domain),o=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return o}unconfirm(e,t){let n=this.findHost(e),o=!1;for(let[i,s]of this.mappings.entries())s.domain===n&&(this.log("removing verification of %s to %s DNS mapping",i,s.domain),o=o||s.verified,s.verified=!1,s.expires=Date.now()+t);return o}findHost(e){for(let t of e.stringTuples())if(t[0]===i4||t[0]===EP||t[0]===SP||t[0]===AP||t[0]===IP)return t[1]}};var s4=4,a4=41,c4=6,TP=273,Rh=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=new Map}has(e){let t=e.stringTuples();for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t[0][1])return!0;return!1}add(e,t,n,o=t,i="tcp"){let s=`${e}-${t}-${i}`,a=this.mappings.get(s)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:nn(n)?4:6,protocol:i,verified:!1,expires:0};a.push(c),this.mappings.set(s,a)}remove(e){let t=e.stringTuples(),n=t[0][1]??"",o=t[1][0]===c4?"tcp":"udp",i=parseInt(t[1][1]??"0"),s=!1;for(let[a,c]of this.mappings.entries()){for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===n&&u.externalPort===i&&u.protocol===o&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,i,o),s=s||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return s}getAll(e){let t=[];for(let{multiaddr:n}of e){let o=n.stringTuples(),i;if((o[0][0]===s4||o[0][0]===a4)&&o[1][0]===c4?i=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===s4||o[0][0]===a4)&&o[1][0]===TP&&(i=`${o[0][1]}-${o[1][1]}-udp`),i==null)continue;let s=this.mappings.get(i);if(s!=null)for(let a of s)o[0][0]=a.externalFamily===4?s4:a4,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,t.push({multiaddr:q(`/${o.map(c=>[J(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}confirm(e,t){let o=e.stringTuples()[0][1],i=!1;for(let s of this.mappings.values())for(let a of s)a.externalIp===o&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),i=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return i}unconfirm(e,t){let n=e.stringTuples(),o=n[0][1]??"",i=n[1][0]===c4?"tcp":"udp",s=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===o&&u.externalPort===s&&u.protocol===i&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,o,s,i),a=a||u.verified,u.verified=!1,u.expires=Date.now()+t)}return a}};function Hb(r){try{let[[e,t]]=r.stringTuples();if(t==null)return!1;if(e===4)return t.startsWith("169.254.");if(e===41)return t.toLowerCase().startsWith("fe80")}catch{}return!1}var _P={maxObservedAddresses:10},Dh=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=t.maxObservedAddresses??_P.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Br(e)||Hb(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:q(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},i=o.verified;return o.verified=!0,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),i}};var kP={maxObservedAddresses:10},Nh=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=t.maxObservedAddresses??kP.maxObservedAddresses}get(e,t){if(Br(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!1,expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},i=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),i}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},i=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),i}toKey(e){let t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}};var qb=6e4,zb={maxObservedAddresses:10,addressVerificationTTL:qb*10,addressVerificationRetry:qb*5},CP=r=>r;function l4(r,e){let t=r.getPeerId();return t!=null&&Fe(t).equals(e)&&(r=r.decapsulate(q(`/p2p/${e.toString()}`))),r}var Lh=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:i=[]}=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.appendAnnounce=new Set(i.map(s=>s.toString())),this.observed=new Dh(e,t),this.dnsMappings=new Ph(e,t),this.ipMappings=new Rh(e,t),this.transportAddresses=new Nh(e,t),this.announceFilter=t.announceFilter??CP,this.observedAddressFilter=rr(1024),this.addressVerificationTTL=t.addressVerificationTTL??zb.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??zb.addressVerificationRetry,this._updatePeerStoreAddresses=$b(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().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=>q(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>q(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>q(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=e.stringTuples(),n=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=l4(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=l4(e,this.components.peerId);let n=!0;(t?.type==="observed"||this.observed.has(e))&&(n=this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)),(t?.type==="transport"||this.transportAddresses.has(e))&&(n=this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&(n=this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&(n=this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=l4(e,this.components.peerId);let n=!1;this.observed.has(e)&&(n=this.observed.remove(e)),this.transportAddresses.has(e)&&(n=this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)),this.dnsMappings.has(e)&&(n=this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)),this.ipMappings.has(e)&&(n=this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=q(n);return o.protos().pop()?.path===!0||o.getPeerId()===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return e.map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];return t=t.concat(this.components.transportManager.getAddrs().map(n=>this.transportAddresses.get(n,this.addressVerificationTTL))),t=t.concat(this.getAppendAnnounceAddrs().map(n=>({multiaddr:n,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(q(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,i="tcp"){this.ipMappings.add(e,t,n,o,i),this.observed.removePrefixed(`/ip${nn(n)?4:6}/${n}/${i}/${o}`)}removePublicAddressMapping(e,t,n,o=t,i="tcp"){this.ipMappings.remove(q(`/ip${nn(n)?4:6}/${n}/${i}/${o}`))&&this._updatePeerStoreAddresses()}};var Wb;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(Wb||(Wb={}));var Bh=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Oh=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},wa=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},al=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Mh=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Uh=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Fh=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},cl=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Wi=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Vh=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},$h=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Gi=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Qi=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Kh=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}};var u4=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=ko())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>vl(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")}},RP=["metrics","connectionProtector","dns"],DP=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Gb(r={}){let e=new u4(r);return new Proxy(e,{get(n,o,i){if(typeof o=="string"&&!DP.includes(o)){let s=e.components[o];if(s==null&&!RP.includes(o))throw new Bh(`${o} not set`);return s}return Reflect.get(n,o,i)},set(n,o,i){return typeof o=="string"?e.components[o]=i:Reflect.set(n,o,i),!0}})}function Qb(r){let e={};for(let t of Object.values(r.components))for(let n of NP(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of LP(t))if(e[n]!==!0)throw new Oh(`Service "${BP(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function NP(r){return Array.isArray(r?.[Ae])?r[Ae]:[]}function LP(r){return Array.isArray(r?.[dr])?r[dr]:[]}function BP(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var OP=4,MP=41;function Yb(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{if(Ti.matches(e))return!1;let t=e.stringTuples();return t[0][0]===OP||t[0][0]===MP?!!vr(`${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 Hh(r){if(pl(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:Fe(t),r.forEach(n=>{if(!Bo(n))throw new ao("Invalid multiaddr");let o=n.getPeerId();if(o==null){if(e!=null)throw new P("Multiaddrs must all have the same peer id or have no peer id")}else{let i=Fe(o);if(e?.equals(i)!==!0)throw new P("Multiaddrs must all have the same peer id or have no peer id")}})}return{peerId:e,multiaddrs:r}}var UP=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function Xb(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??UP;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var jb="last-dial-failure",Zb="last-dial-success";var qh=100,zh=50;async function Jb(r,e){let t=!1;for(let o of Vs.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}function ll(r){try{let e;if(typeof r=="string"?e=q(r):e=r,!e.protoNames().includes("ipcidr")){let n=e.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(n)}return fm(e)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var FP={maxConnections:qh,allow:[]},Wh=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??FP.maxConnections,this.allow=(t.allow??[]).map(n=>ll(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}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 pt;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((u,d)=>u+d.value,0))}catch(l){l.name!=="NotFoundError"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(e,n),i=Math.max(t-this.maxConnections,0),s=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>l.contains(a.remoteAddr.nodeAddress().address))||s.push(a),s.length===i)break;await Promise.all(s.map(async a=>{await Xb(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:s})}sortConnections(e,t){return e.sort((n,o)=>{let i=n.timeline.open,s=o.timeline.open;return i<s?1:i>s?-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 i=t.get(n.remotePeer)??0,s=t.get(o.remotePeer)??0;return i>s?1:i<s?-1:0})}};var Gh=class extends Vt{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function VP(r,e){let t=Tc.exactMatch(r.multiaddr),n=Tc.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=_c.exactMatch(r.multiaddr),i=_c.exactMatch(e.multiaddr);if(o&&!i)return-1;if(!o&&i)return 1;let s=Ti.exactMatch(r.multiaddr),a=Ti.exactMatch(e.multiaddr);if(s&&!a)return-1;if(!s&&a)return 1;let c=Cc.exactMatch(r.multiaddr),l=Cc.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=kc.exactMatch(r.multiaddr),d=kc.exactMatch(e.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;let h=tm.exactMatch(r.multiaddr),f=tm.exactMatch(e.multiaddr);return h&&!f?-1:!h&&f?1:0}function $P(r,e){let t=Br(r.multiaddr),n=Br(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function KP(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function HP(r,e){let t=or.exactMatch(r.multiaddr),n=or.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function ex(r){return r.sort(VP).sort(KP).sort(HP).sort($P)}var Qh={maxParallelDials:zh,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:zi}},Yh=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Qh.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Qh.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Qh.dialTimeout,this.connections=t.connections??new pt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,F(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))Vs.set(n,o);this.queue=new Gh({concurrency:t.maxParallelDials??Qh.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{n.detail.name!==Ft.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,F(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=Hh(e),i=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(i?.status==="open")return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new G("dial-queue:already-connected")),i;let s=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(s!=null){this.log("joining existing dial target for %p",n);for(let a of o)s.options.multiaddrs.add(a.toString());return t.onProgress?.(new G("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Nn("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new G("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a?.onProgress?.(new G("dial-queue:start-dial"));let c=le([this.shutDownController.signal,a.signal]);F(1/0,c);let l;try{l=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),a?.onProgress?.(new G("dial-queue:calculated-addresses",l)),l.map(({multiaddr:u})=>u.toString()).forEach(u=>{a?.multiaddrs.add(u)})}catch(u){throw c.clear(),u}try{let u=0,d=[];for(let h of l){if(u===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",u,n),new Nn("Peer had more than maxPeerAddrsToDial");u++;try{let f=await this.components.transportManager.dial(h.multiaddr,{...a,signal:c});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(f.remotePeer,{multiaddrs:[f.remoteAddr],metadata:{[Zb]:M(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}return f}catch(f){if(this.log.error("dial failed to %a",h.multiaddr,f),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[jb]: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 Ur(f.message);d.push(f)}}throw d.length===1?d[0]:new AggregateError(d,"All multiaddr dials failed")}finally{c.clear()}},{peerId:n,priority:t.priority??p4,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(d=>({multiaddr:q(d),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Nn("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new cl("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let d=await this.components.peerStore.get(e);o.push(...d.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:h})=>h.toString()))}catch(d){if(d.name!=="NotFoundError")throw d}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let d=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:h})=>h.toString())),o.push(...d.multiaddrs.map(h=>({multiaddr:h,isCertified:!1})))}catch(d){d.name!=="NoPeerRoutersError"&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,d)}}}let i=(await Promise.all(o.map(async d=>{let h=await Jb(d.multiaddr,{dns:this.components.dns,...n,log:this.log});return h.length===1&&h[0].equals(d.multiaddr)?d:h.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let d=`/p2p/${e.toString()}`;i=i.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(d),isCertified:h.isCertified}:h)}let s=i.filter(d=>{if(this.components.transportManager.dialTransportForMultiaddr(d.multiaddr)==null)return!1;let h=d.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),a=new Map;for(let d of s){let h=d.multiaddr.toString(),f=a.get(h);if(f!=null){f.isCertified=f.isCertified||d.isCertified||!1;continue}a.set(h,d)}let c=[...a.values()];if(c.length===0)throw new Wi("The dial request has no valid addresses");let l=[];for(let d of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(d.multiaddr)||l.push(d);let u=this.addressSorter==null?ex(l):l.sort(this.addressSorter);if(u.length===0)throw new cl("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",i.map(({multiaddr:d})=>d.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:d})=>d.toString())),u}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.runOnLimitedConnection===!1?n.find(o=>!or.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var ax=ur(ix(),1);var zP=Object.prototype.toString,WP=r=>zP.call(r)==="[object Error]",GP=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function m4(r){return r&&WP(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:GP.has(r.message):!1}var g4=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},sx=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function y4(r,e){return new Promise((t,n)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let o=ax.default.operation(e),i=()=>{o.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",i,{once:!0});let s=()=>{e.signal?.removeEventListener("abort",i),o.stop()};o.attempt(async a=>{try{let c=await r(a);s(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof g4)throw c.originalError;if(c instanceof TypeError&&!m4(c))throw c;if(sx(c,a,e),await e.shouldRetry(c)||(o.stop(),n(c)),await e.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(l){sx(l,a,e),s(),n(l)}}})})}var Xh=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new wt({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);cx(t)&&(this.queue.has(e)||this.queue.add(async n=>{await y4(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(i){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,i),i}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(i=>{i.startsWith(oo)&&(o[i]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>cx(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function cx(r){for(let e of r.tags.keys())if(e.startsWith(oo))return!0;return!1}var p4=50,w4={maxConnections:qh,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},jh=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??w4.maxConnections,this.maxConnections<1)throw new P("Connection Manager maxConnections must be greater than 0");this.connections=new pt,this.started=!1,this.peerId=e.peerId,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.allow=(t.allow??[]).map(n=>ll(n)),this.deny=(t.deny??[]).map(n=>ll(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??w4.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new ha({points:t.inboundConnectionThreshold??w4.inboundConnectionThreshold,duration:1}),this.connectionPruner=new Wh({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:t.allow?.map(n=>q(n))}),this.dialQueue=new Yh(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??zh,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:zi},connections:this.connections}),this.reconnectQueue=new Xh({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;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 i=`${o.direction} ${o.protocol??"unnegotiated"}`;e[i]=(e[i]??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 i={};for(let s of o.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;i[a]=(i[a]??0)+1}for(let[s,a]of Object.entries(i))e[s]=e[s]??[],e[s].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((s,a)=>s-a);let i=Math.floor(o.length*.9);t[n]=o[i]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await yt(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Ct(this.reconnectQueue,this.dialQueue,this.connectionPruner);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")}getMaxConnections(){return this.maxConnections}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}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),i=this.connections.get(n)??[];i.push(t),this.connections.set(n,i),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,i=(this.connections.get(n)??[]).filter(s=>s.id!==t.id);this.connections.set(n,i),i.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),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.started)throw new Fr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n}=Hh(e);if(this.peerId.equals(n))throw new Ji("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),t.onProgress?.(new G("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??p4});if(o.status!=="open")throw new ji("Remote closed connection during opening");let i=this.connections.get(o.remotePeer);i==null&&(i=[],this.connections.set(o.remotePeer,i));let s=!1;for(let a of i)if(a.id===o.id&&(s=!0),t.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new ao("Duplicate multiaddr connection")),a;return s||i.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(i){o.abort(i)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>o.contains(e.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>o.contains(e.remoteAddr.nodeAddress().address)))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=>q(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var XP=1e4,jP="1.0.0",ZP="ping",JP="ipfs",lx=32,eR=!0,Zh=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??JP}/${ZP}/${jP}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??XP,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??eR,this.timeout=new dn({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Ae]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,F(1/0,this.abortController.signal),this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),i=Ni(o);t=Date.now(),await Promise.all([i.write(qt(lx),{signal:n}),i.read(lx,{signal:n})]),e.rtt=Date.now()-t,await i.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var Jh=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:$(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:$(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";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 wa("No content routers available");let n=this,o=new zt;for await(let i of Kt(...n.routers.map(s=>s.findProviders(e,t))))i!=null&&(i.multiaddrs.length>0&&await this.components.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),!o.has(i.id)&&(o.add(i.id),yield i))}async provide(e,t={}){if(this.routers.length===0)throw new wa("No content routers available");await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new wa("No content routers available");await Promise.all(this.routers.map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Fr;await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Fr;return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var e0=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??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:$(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new al("No peer routers available");if(e.toString()===this.peerId.toString())throw new Mh("Should not try to find self");let n=this,o=Kt(...this.routers.map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),i;throw new Oe}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new al("No peer routers available");let n=this,o=rr(1024);for await(let i of un(async function*(){let s=Kt(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of s)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}}()))i!=null&&(i.multiaddrs.length>0&&await this.peerStore.merge(i.id,{multiaddrs:i.multiaddrs}),!o.has(i.id.toMultihash().bytes)&&(o.add(i.id.toMultihash().bytes),yield i))}};var t0=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,F(1/0,this.shutdownController.signal)}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,F(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=le([this.shutdownController.signal,e?.signal]);F(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=ee(),yield(await fr(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,F(1/0,this.walkController.signal);let e=le([this.walkController.signal,this.shutdownController.signal]);F(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=qt(32),i=Date.now();for await(let s of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-i,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:s}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await at(this.needNext.promise,e)),i=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).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 b4=32,x4=64,r0=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)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new Uh(`No handler registered for protocol ${e}`);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 Fh(`Handler already registered for protocol ${e}`);let o=la.bind({ignoreUndefined:!0})({maxInboundStreams:b4,maxOutboundStreams:x4},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 P("invalid topology");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 i=this.topologies.get(o);if(i!=null)for(let s of i.values())s.filter?.has(t)!==!1&&(s.filter?.remove(t),s.onDisconnect?.(t))}}).catch(n=>{n.name!=="NotFoundError"&&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(i=>!t.protocols.includes(i));for(let i of o){let s=this.topologies.get(i);if(s!=null)for(let a of s.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 i of t){let s=this.topologies.get(i);if(s!=null)for(let a of s.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var n0=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=Fd({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??io.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new P("Transport must have a valid tag");if(this.transports.has(t))throw new P(`There is already a transport with the tag ${t}`);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 Kh(`No transport available for address ${String(e)}`);return t?.onProgress?.(new G("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}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 Fr("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 i=o.listenFilter(e),s=[];for(let l of i){this.log("creating listener for %s on %a",n,l);let u=o.createListener({upgrader:this.components.upgrader}),d=this.listeners.get(n)??[];d==null&&(d=[],this.listeners.set(n,d)),d.push(u),u.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:u})}),u.addEventListener("close",()=>{let h=d.findIndex(f=>f===u);d.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:u})}),s.push(u.listen(l))}if(s.length===0){t.push(n);continue}if((await Promise.allSettled(s)).find(l=>l.status==="fulfilled")==null&&this.faultTolerance!==io.NO_FATAL)throw new Wi(`Transport (${n}) could not listen on any available address`)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===io.FATAL_ALL)throw new Wi(n);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 _t="/multistream/1.0.0";var tR=M(`
|
|
39
39
|
`);async function Xi(r,e,t){await r.write(e,t)}async function ux(r,e,t){await r.writeV(e,t)}async function rR(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==tR[0])throw e.log.error("Invalid mss message - missing newline",t),new he("Missing newline");return t.sublist(0,-1)}async function Qo(r,e){let t=await rR(r,e);return $(t.subarray())}async function ul(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return nR(r,e[0],t);let n=kn(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"]',_t,o);let i=M(`${_t}
|
|
40
40
|
`),s=M(`${o}
|
|
41
41
|
`);await ux(n,[i,s],t),t.log.trace("select: reading multistream-select header");let a=await Qo(n,t);if(t.log.trace('select: read "%s"',a),a===_t&&(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 Xi(n,M(`${c}
|