@helia/http 3.1.4-1361bfa5 → 3.1.4-16d805e1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,33 +1,23 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaHttp = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var HeliaHttp=(()=>{var Is=Object.create;var we=Object.defineProperty;var As=Object.getOwnPropertyDescriptor;var Ps=Object.getOwnPropertyNames;var Ts=Object.getPrototypeOf,Ds=Object.prototype.hasOwnProperty;var be=(r,t)=>()=>{try{return t||r((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}},z=(r,t)=>{for(var e in t)we(r,e,{get:t[e],enumerable:!0})},Bn=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ps(t))!Ds.call(r,o)&&o!==e&&we(r,o,{get:()=>t[o],enumerable:!(n=As(t,o))||n.enumerable});return r};var Mn=(r,t,e)=>(e=r!=null?Is(Ts(r)):{},Bn(t||!r||!r.__esModule?we(e,"default",{value:r,enumerable:!0}):e,r)),ks=r=>Bn(we({},"__esModule",{value:!0}),r);var Ur=be(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.Netmask4Impl=void 0;Ot.ip2long=Rt;Ot.long2ip=Z;function Z(r){let t=(r&-16777216)>>>24,e=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[t,e,n,o].join(".")}var Ji=48,Xi=97,Yi=65;function Zi(r){let t=0,e=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,e=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,e=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)t=t*e+(r.charCodeAt(o)-Ji)>>>0;else if(e===16)if("a"<=r[o]&&r[o]<="f")t=t*e+(10+r.charCodeAt(o)-Xi)>>>0;else if("A"<=r[o]&&r[o]<="F")t=t*e+(10+r.charCodeAt(o)-Yi)>>>0;else break;else break;if(t>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[t,o]}function Rt(r){let t=[];for(let e=0;e<=3&&r.length!==0;e++){if(e>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=Zi(r);r=r.substring(o),t.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}}var $r=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(!n){let o=t.split("/",2);t=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=Rt(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(Rt(t)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+t)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Z(this.netLong),this.mask=Z(this.maskLong),this.hostmask=Z(~this.maskLong),this.first=this.bitmask<=30?Z(this.netLong+1):this.base,this.last=this.bitmask<=30?Z(this.netLong+this.size-2):Z(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Z(this.netLong+this.size-1):void 0}contains(t){return typeof t=="string"&&(t.indexOf("/")>0||t.split(".").length!==4)&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):(Rt(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(t=1){return new r(Z(this.netLong+this.size*t),this.mask)}forEach(t){let e=Rt(this.first),n=Rt(this.last),o=0;for(;e<=n;)t(Z(e),e,o),o++,e++}toString(){return this.base+"/"+this.bitmask}};Ot.Netmask4Impl=$r});var wo=be($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.Netmask6Impl=void 0;$t.ip6bigint=Mr;$t.bigint2ip6=vt;var ta=Ur(),Br=(1n<<128n)-1n;function Mr(r){let t=r.indexOf("%");t!==-1&&(r=r.substring(0,t));let e=r.lastIndexOf(":");if(e!==-1&&r.indexOf(".",e)!==-1){let n=r.substring(e+1),o=(0,ta.ip2long)(n),s=r.substring(0,e+1)+"0:0";return yo(s)&~0xffffffffn|BigInt(o)}return yo(r)}function yo(r){let t=r.indexOf("::"),e;if(t!==-1){let o=r.substring(0,t),s=r.substring(t+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");e=[...i,...Array(c).fill("0"),...a]}else e=r.split(":");if(e.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+e.length);let n=0n;for(let o=0;o<8;o++){let s=e[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function vt(r){if(r<0n||r>Br)throw new Error("Invalid IPv6 address value");let t=[];for(let i=0;i<8;i++)t.unshift(Number(r&0xffffn)),r>>=16n;let e=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)t[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(e=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(e=o,n=s),e!==-1&&e+n===8&&e>0)return t.slice(0,e).map(a=>a.toString(16)).join(":")+"::";if(e===0)return"::"+t.slice(n).map(a=>a.toString(16)).join(":");if(e>0){let i=t.slice(0,e).map(c=>c.toString(16)),a=t.slice(e+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return t.map(i=>i.toString(16)).join(":")}var zr=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(n==null){let o=t.indexOf("/");o!==-1?(n=parseInt(t.substring(o+1),10),t=t.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=Br>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=Mr(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=vt(this.netBigint),this.mask=vt(this.maskBigint),this.hostmask=vt(~this.maskBigint&Br),this.first=this.base,this.last=vt(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(t){return typeof t=="string"&&t.indexOf("/")>0&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.last):(Mr(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(vt(this.netBigint+e*BigInt(t)),this.bitmask)}forEach(t){let e=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;e<=o;)t(vt(e),Number(e),s),s++,e++}toString(){return this.base+"/"+this.bitmask}};$t.Netmask6Impl=zr});var bo=be(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.long2ip=ht.ip2long=ht.Netmask=void 0;var Te=Ur();Object.defineProperty(ht,"ip2long",{enumerable:!0,get:function(){return Te.ip2long}});Object.defineProperty(ht,"long2ip",{enumerable:!0,get:function(){return Te.long2ip}});var ea=wo(),Vr=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");(t.indexOf("/")!==-1?t.substring(0,t.indexOf("/")):t).indexOf(":")!==-1?this._impl=new ea.Netmask6Impl(t,e):this._impl=new Te.Netmask4Impl(t,e),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof Te.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(t){return typeof t=="string"&&(t.indexOf("/")>0?t=new r(t):t.indexOf(":")===-1&&t.split(".").length!==4&&(t=new r(t))),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):this._impl.contains(t)}next(t=1){let e=this._impl.next(t);return new r(e.base,e.bitmask)}forEach(t){this._impl.forEach(t)}toString(){return this._impl.toString()}};ht.Netmask=Vr});var hs=be((Wp,fs)=>{fs.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(s,i){e[s]=i,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(s){return e[s]!==void 0||n[s]!==void 0},remove:function(s){e[s]!==void 0&&(e[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=e[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){e[s]!==void 0?e[s]=i:o(s,i)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var el={};z(el,{withHTTP:()=>tl});var W=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var It=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var et=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}};function Fs(r){return typeof r?.handleEvent=="function"}function Ls(r){return(r!==!0&&r!==!1&&r?.once)??!1}var At=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){let o=Ls(n);super.addEventListener(t,i=>{if(o){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==e),this.#t.set(i.type,a))}Fs(e)?e.handleEvent(i):e(i)},n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:o})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function q(r=0){return new Uint8Array(r)}function Y(r=0){return new Uint8Array(r)}function Ns(r){return r?.buffer instanceof ArrayBuffer}function fr(r){if(Ns(r))return r;let t=r.slice();return new Uint8Array(t.buffer,0,t.byteLength)}function rt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=Y(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return fr(e)}function nt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var Vn=Symbol.for("@achingbrain/uint8arraylist");function zn(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Pt(r){return!!r?.[Vn]}var xe=class r{bufs;length;[Vn]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Pt(n)){e+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Pt(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=zn(this.bufs,t);return e.buf[e.index]}set(t,e){let n=zn(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Pt(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return rt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:rt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=n,s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let f=t>=a&&t<c,l=e>a&&e<=c;if(f&&l){if(t===a&&e===c){n.push(i);break}let h=t-a;n.push(i.subarray(h,h+(e-t)));break}if(f){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(l){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Pt(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,l;for(let h=e;h<=c;h+=l){l=0;for(let u=f;u>=0;u--){let p=this.get(h+u);if(n[u]!==p){l=Math.max(1,u-a[p]);break}}if(l===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=Y(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=q(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=q(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=q(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=Y(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=q(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=q(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=q(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=q(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=q(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!nt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var gr={};z(gr,{base10:()=>Vs});var ml=new Uint8Array(0);function qn(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ot(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return yt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return yt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function jn(r){return new TextEncoder().encode(r)}function Hn(r){return new TextDecoder().decode(r)}function Rs(r){return r?.buffer instanceof ArrayBuffer}function yt(r){return Rs(r)?r:r.slice()}function Os(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var x=0,g=0,w=0,S=m.length;w!==S&&m[w]===0;)w++,x++;for(var A=(S-w)*l+1>>>0,O=new Uint8Array(A);w!==S;){for(var F=m[w],tt=0,$=A-1;(F!==0||tt<g)&&$!==-1;$--,tt++)F+=256*O[$]>>>0,O[$]=F%a>>>0,F=F/a>>>0;if(F!==0)throw new Error("Non-zero carry");g=tt,w++}for(var H=A-g;H!==A&&O[H]===0;)H++;for(var gt=c.repeat(x);H<A;++H)gt+=r.charAt(O[H]);return gt}function u(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var x=0;if(m[x]!==" "){for(var g=0,w=0;m[x]===c;)g++,x++;for(var S=(m.length-x)*f+1>>>0,A=new Uint8Array(S);m[x];){var O=e[m.charCodeAt(x)];if(O===255)return;for(var F=0,tt=S-1;(O!==0||F<w)&&tt!==-1;tt--,F++)O+=a*A[tt]>>>0,A[tt]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");w=F,x++}if(m[x]!==" "){for(var $=S-w;$!==S&&A[$]===0;)$++;for(var H=new Uint8Array(g+(S-$)),gt=g;$!==S;)H[gt++]=A[$++];return H}}}function p(m){var x=u(m);if(x)return x;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:u,decode:p}}var $s=Os,Us=$s,Gn=Us;var hr=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},dr=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Kn(this,t)}},pr=class{decoders;constructor(t){this.decoders=t}or(t){return Kn(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Kn(r,t){return new pr({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var mr=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new hr(t,e,n),this.decoder=new dr(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Tt({name:r,prefix:t,encode:e,decode:n}){return new mr(r,t,e,n)}function lt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Gn(e,r);return Tt({prefix:t,name:r,encode:n,decode:s=>ot(o(s))})}function Bs(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let l=t[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Ms(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function zs(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function P({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=zs(n);return Tt({prefix:t,name:r,encode(s){return Ms(s,n,e)},decode(s){return Bs(s,o,e,r)}})}var Vs=lt({prefix:"9",name:"base10",alphabet:"0123456789"});var yr={};z(yr,{base16:()=>qs,base16upper:()=>js});var qs=P({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),js=P({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var wr={};z(wr,{base2:()=>Hs});var Hs=P({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var br={};z(br,{base256emoji:()=>Js});var Qn=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Ws=Qn.reduce((r,t,e)=>(r[e]=t,r),[]),Gs=Qn.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Ks(r){return r.reduce((t,e)=>(t+=Ws[e],t),"")}function Qs(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Gs[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Js=Tt({prefix:"\u{1F680}",name:"base256emoji",encode:Ks,decode:Qs});var xr={};z(xr,{base32:()=>G,base32hex:()=>ti,base32hexpad:()=>ri,base32hexpadupper:()=>ni,base32hexupper:()=>ei,base32pad:()=>Ys,base32padupper:()=>Zs,base32upper:()=>Xs,base32z:()=>oi});var G=P({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Xs=P({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ys=P({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Zs=P({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ti=P({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ei=P({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ri=P({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ni=P({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),oi=P({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var vr={};z(vr,{base36:()=>Jt,base36upper:()=>si});var Jt=lt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),si=lt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Er={};z(Er,{base58btc:()=>U,base58flickr:()=>ii});var U=lt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ii=lt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Cr={};z(Cr,{base64:()=>wt,base64pad:()=>ai,base64url:()=>_r,base64urlpad:()=>ci});var wt=P({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ai=P({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_r=P({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ci=P({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Sr={};z(Sr,{base8:()=>li});var li=P({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ir={};z(Ir,{identity:()=>ui});var ui=Tt({prefix:"\0",name:"identity",encode:r=>Hn(r),decode:r=>jn(r)});var kl=new TextEncoder,Fl=new TextDecoder;var Pr={};z(Pr,{identity:()=>Zt});var hi=Zn,Xn=128,di=127,pi=~di,mi=Math.pow(2,31);function Zn(r,t,e){t=t||[],e=e||0;for(var n=e;r>=mi;)t[e++]=r&255|Xn,r/=128;for(;r&pi;)t[e++]=r&255|Xn,r>>>=7;return t[e]=r|0,Zn.bytes=e-n+1,t}var gi=Ar,yi=128,Yn=127;function Ar(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ar.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&Yn)<<o:(i&Yn)*Math.pow(2,o),o+=7}while(i>=yi);return Ar.bytes=s-n,e}var wi=Math.pow(2,7),bi=Math.pow(2,14),xi=Math.pow(2,21),vi=Math.pow(2,28),Ei=Math.pow(2,35),_i=Math.pow(2,42),Ci=Math.pow(2,49),Si=Math.pow(2,56),Ii=Math.pow(2,63),Ai=function(r){return r<wi?1:r<bi?2:r<xi?3:r<vi?4:r<Ei?5:r<_i?6:r<Ci?7:r<Si?8:r<Ii?9:10},Pi={encode:hi,decode:gi,encodingLength:Ai},Ti=Pi,Xt=Ti;function Yt(r,t=0){return[Xt.decode(r,t),Xt.decode.bytes]}function Dt(r,t,e=0){return Xt.encode(r,t,e),t}function kt(r){return Xt.encodingLength(r)}function Lt(r,t){let e=t.byteLength,n=kt(r),o=n+kt(e),s=new Uint8Array(o+e);return Dt(r,s,0),Dt(e,s,n),s.set(t,o),new Ft(r,e,t,s)}function ut(r){let t=ot(r),[e,n]=Yt(t),[o,s]=Yt(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ft(e,o,i,t)}function to(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&qn(r.bytes,e.bytes)}}var Ft=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=yt(n),this.bytes=yt(o)}};var eo=0,Di="identity",ro=ot;function ki(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Lt(eo,ro(r))}var Zt={code:eo,name:Di,encode:ro,digest:ki};var kr={};z(kr,{sha256:()=>Li,sha512:()=>Ni});var Fi=20;function Dr({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new Tr(r,t,e,n,o)}var Tr=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??Fi,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?no(n,this.code,e?.truncate):n.then(o=>no(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function no(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Lt(t,r)}function so(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Li=Dr({name:"sha2-256",code:18,encode:so("SHA-256")}),Ni=Dr({name:"sha2-512",code:19,encode:so("SHA-512")});function io(r,t){let{bytes:e,version:n}=r;return n===0?Oi(e,Fr(r),t??U.encoder):$i(e,Fr(r),t??G.encoder)}var ao=new WeakMap;function Fr(r){let t=ao.get(r);if(t==null){let e=new Map;return ao.set(r,e),e}return t}var T=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=yt(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==te)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Ui)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Lt(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&to(t.multihash,n.multihash)}toString(t){return io(this,t)}toJSON(){return{"/":io(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??co(n,o,s.bytes))}else if(e[Bi]===!0){let{version:n,multihash:o,code:s}=e,i=ut(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==te)throw new Error(`Version 0 CID must use dag-pb (code: ${te}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=co(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,te,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=ot(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Ft(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,u]=Yt(t.subarray(e));return e+=u,h},o=n(),s=te;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),f=e+c,l=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(t,e){let[n,o]=Ri(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Fr(s).set(n,t),s}};function Ri(r,t){switch(r[0]){case"Q":{let e=t??U;return[U.prefix,e.decode(`${U.prefix}${r}`)]}case U.prefix:{let e=t??U;return[U.prefix,e.decode(r)]}case G.prefix:{let e=t??G;return[G.prefix,e.decode(r)]}case Jt.prefix:{let e=t??Jt;return[Jt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Oi(r,t,e){let{prefix:n}=e;if(n!==U.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function $i(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var te=112,Ui=18;function co(r,t,e){let n=kt(r),o=n+kt(t),s=new Uint8Array(o+e.byteLength);return Dt(r,s,0),Dt(t,s,n),s.set(e,o),s}var Bi=Symbol.for("@ipld/js-cid/CID");var ee={...Ir,...wr,...Sr,...gr,...yr,...xr,...vr,...Er,...Cr,...br},tu={...kr,...Pr};function uo(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var lo=uo("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Lr=uo("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=Y(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Mi={utf8:lo,"utf-8":lo,hex:ee.base16,latin1:Lr,ascii:Lr,binary:Lr,...ee},Ee=Mi;function C(r,t="utf8"){let e=Ee[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}var Nr={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},fo={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ho=new globalThis.TextEncoder;function zi(r,t){let e=Nr[t],n=fo[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function Vi(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Nr[t],o=fo[t],s=r;for(;s.length>0;){let i=ho.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function Rr(r,{size:t=32,utf8Buffer:e}={}){if(!Nr[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return Vi(r,t,e);r=ho.encode(r)}return zi(r,t)}var re={hash:r=>Number(Rr(r,{size:32})),hashV:(r,t)=>qi(re.hash(r,t))};function qi(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),C(t,"base16")}var Or=64,K=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Or)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=q(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?nt(this.fp,t.fp):!1}};function bt(r,t){return Math.floor(Math.random()*(t-r))+r}var xt=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof K))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof K))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof K))throw new TypeError("Invalid Fingerprint");let e=bt(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof K))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var ji=500,ne=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??re,this.seed=t.seed??bt(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=C(t));let e=new K(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new xt(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new xt(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[bt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new xt(this.bucketSize));for(let a=0;a<ji;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new xt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=C(t));let e=new K(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=C(t));let e=new K(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Hi={1:.5,2:.84,4:.95,8:.98};function Wi(r=.001){return r>.002?2:r>1e-5?4:8}function po(r,t=.001){let e=Wi(t),n=Hi[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Or);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var _e=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??re,this.seed=t.seed??bt(0,Math.pow(2,10)),this.filterSeries=[new ne({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=C(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new ne({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=C(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=C(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function Ce(r,t=.001,e){return new _e({...po(r,t),...e??{}})}function Gi(r){let t=r.getComponents(),e={},n=0;return t[n]?.name==="ip6zone"&&(e.zone=`${t[n].value}`,n++),t[n]?.name==="ip4"||t[n]?.name==="ip6"||t[n]?.name==="dns"||t[n]?.name==="dns4"||t[n]?.name==="dns6"?(e.type=t[n].name,e.host=t[n].value,n++):t[n]?.name==="dnsaddr"&&(e.type=t[n].name,e.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(e.protocol=t[n].name==="tcp"?"tcp":"udp",e.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(e.type==="ip4"?e.cidr=parseInt(`${t[n].value}`):e.type==="ip6"&&(e.cidr=`${t[n].value}`),n++),e.type==null||e.host==null?null:(t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e)}function Se(r){let t=Gi(r);if(t==null)throw new It(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t}var Ie=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let u=Number.parseInt(h,t);if(!Number.isNaN(u))return u});if(l===void 0)break;if(s*=t,s+=l,s>f||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Ki=45,Qi=15,Ae=new Ie;function mo(r){if(!(r.length>Qi))return Ae.new(r).parseWith(()=>Ae.readIPv4Addr())}function go(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Ki))return Ae.new(r).parseWith(()=>Ae.readIPv6Addr())}function Nt(r){return!!mo(r)}function Pe(r){return!!go(r)}var xo=Mn(bo(),1),ra=["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"],na=ra.map(r=>new xo.Netmask(r));function qr(r){for(let t of na)if(t.contains(r))return!0;return!1}function oa(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function sa(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return qr(o)}function ia(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function aa(r){let t=r.split(":"),e=t[t.length-1];return qr(e)}function ca(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 vo(r){if(Nt(r))return qr(r);if(oa(r))return sa(r);if(ia(r))return aa(r);if(Pe(r))return ca(r)}function Eo(r){try{let t=Se(r);switch(t.type){case"ip4":case"ip6":return vo(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}var la=Math.pow(2,7),ua=Math.pow(2,14),fa=Math.pow(2,21),jr=Math.pow(2,28),Hr=Math.pow(2,35),Wr=Math.pow(2,42),Gr=Math.pow(2,49),I=128,N=127;function Ut(r){if(r<la)return 1;if(r<ua)return 2;if(r<fa)return 3;if(r<jr)return 4;if(r<Hr)return 5;if(r<Wr)return 6;if(r<Gr)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Kr(r,t,e=0){switch(Ut(r)){case 8:t[e++]=r&255|I,r/=128;case 7:t[e++]=r&255|I,r/=128;case 6:t[e++]=r&255|I,r/=128;case 5:t[e++]=r&255|I,r/=128;case 4:t[e++]=r&255|I,r>>>=7;case 3:t[e++]=r&255|I,r>>>=7;case 2:t[e++]=r&255|I,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function ha(r,t){let e=r[t],n=0;if(n+=e&N,e<I||(e=r[t+1],n+=(e&N)<<7,e<I)||(e=r[t+2],n+=(e&N)<<14,e<I)||(e=r[t+3],n+=(e&N)<<21,e<I)||(e=r[t+4],n+=(e&N)*jr,e<I)||(e=r[t+5],n+=(e&N)*Hr,e<I)||(e=r[t+6],n+=(e&N)*Wr,e<I)||(e=r[t+7],n+=(e&N)*Gr,e<I))return n;throw new RangeError("Could not decode varint")}function da(r,t){let e=r.get(t),n=0;if(n+=e&N,e<I||(e=r.get(t+1),n+=(e&N)<<7,e<I)||(e=r.get(t+2),n+=(e&N)<<14,e<I)||(e=r.get(t+3),n+=(e&N)<<21,e<I)||(e=r.get(t+4),n+=(e&N)*jr,e<I)||(e=r.get(t+5),n+=(e&N)*Hr,e<I)||(e=r.get(t+6),n+=(e&N)*Wr,e<I)||(e=r.get(t+7),n+=(e&N)*Gr,e<I))return n;throw new RangeError("Could not decode varint")}function Qr(r,t=0){return r instanceof Uint8Array?ha(r,t):da(r,t)}function ma(r){return r.buffer instanceof ArrayBuffer}function oe(r){return ma(r)?r:r.slice()}function V(r,t="utf8"){let e=Ee[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var L=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},st=class extends Error{static name="ValidationError";name="ValidationError"},De=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},ke=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Xr(r){return t=>V(t,r)}function Yr(r){return t=>C(t,r)}function Bt(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Et(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function _o(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=C(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Et(n);return rt([e,o],e.length+o.length)}function Co(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=G.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Et(n);return rt([e,o],e.length+o.length)}function Zr(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=V(t,"base32"),o=Bt(e);return`${n}:${o}`}var tn=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new L("Invalid byte value in IP address");t[n]=o}),t},So=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Nt(e[n]),i;s&&(i=tn(e[n]),e[n]=V(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,V(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new L("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},Io=function(r){if(r.byteLength!==4)throw new L("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Ao=function(r){if(r.byteLength!==16)throw new L("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new L(`Invalid IPv6 address "${e}"`)}};function Po(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new L(`Invalid IPv6 address "${r}"`)}}var Jr=Object.values(ee).map(r=>r.decoder),ga=(function(){let r=Jr[0].or(Jr[1]);return Jr.slice(2).forEach(t=>r=r.or(t)),r})();function To(r){return ga.decode(r)}function Do(r){return t=>r.encoder.encode(t)}function ya(r){if(parseInt(r).toString()!==r)throw new st("Value must be an integer")}function wa(r){if(r<0)throw new st("Value must be a positive integer, or zero")}function ba(r){return t=>{if(t>r)throw new st(`Value must be smaller than or equal to ${r}`)}}function xa(...r){return t=>{for(let e of r)e(t)}}var se=xa(ya,wa,ba(65535));var k=-1,en=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new ke(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},it=new en,Na=[{code:4,name:"ip4",size:32,valueToBytes:tn,bytesToValue:Io,validate:r=>{if(!Nt(r))throw new st(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Et,bytesToValue:Bt,validate:se},{code:273,name:"udp",size:16,valueToBytes:Et,bytesToValue:Bt,validate:se},{code:33,name:"dccp",size:16,valueToBytes:Et,bytesToValue:Bt,validate:se},{code:41,name:"ip6",size:128,valueToBytes:So,bytesToValue:Ao,stringToValue:Po,validate:r=>{if(!Pe(r))throw new st(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:k},{code:43,name:"ipcidr",size:8,bytesToValue:Xr("base10"),valueToBytes:Yr("base10")},{code:53,name:"dns",size:k},{code:54,name:"dns4",size:k},{code:55,name:"dns6",size:k},{code:56,name:"dnsaddr",size:k},{code:132,name:"sctp",size:16,valueToBytes:Et,bytesToValue:Bt,validate:se},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:k,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:k,bytesToValue:Xr("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Yr("base58btc")(r):T.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Zr,valueToBytes:_o},{code:445,name:"onion3",size:296,bytesToValue:Zr,valueToBytes:Co},{code:446,name:"garlic64",size:k},{code:447,name:"garlic32",size:k},{code:448,name:"tls"},{code:449,name:"sni",size:k},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:k,bytesToValue:Do(_r),valueToBytes:To},{code:480,name:"http"},{code:481,name:"http-path",size:k,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:k}];Na.forEach(r=>{it.addProtocol(r)});function ko(r){let t=[],e=0;for(;e<r.length;){let n=Qr(r,e),o=it.getProtocol(n),s=Ut(n),i=Ra(o,r,e+s),a=0;i>0&&o.size===k&&(a=Ut(i));let c=s+a+i,f={code:n,name:o.name,bytes:oe(r.subarray(e,e+c))};if(i>0){let l=e+s+a,h=r.subarray(l,l+i);f.value=o.bytesToValue?.(h)??V(h)}t.push(f),e+=c}return t}function Fo(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=it.getProtocol(n.code),s=Ut(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??C(n.value),a=i.byteLength,o.size===k&&(c=Ut(a)));let f=new Uint8Array(s+c+a),l=0;Kr(n.code,f,l),l+=s,i!=null&&(o.size===k&&(Kr(a,f,l),l+=c),f.set(i,l)),n.bytes=f}e.push(n.bytes),t+=n.bytes.byteLength}return rt(e,t)}function Lo(r){if(r.charAt(0)!=="/")throw new L('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=it.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new L(`Component ${o} was missing value`);e="value"}else if(e==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new L(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}t.push(f),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new L("Incomplete multiaddr");return t}function No(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=it.getProtocol(t.code);if(e==null)throw new L(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function Ra(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Qr(t,e)}var Oa=Symbol.for("nodejs.util.inspect.custom"),pn=Symbol.for("@multiformats/multiaddr");function $a(r){if(r==null&&(r="/"),Ro(r))return r.getComponents();if(r instanceof Uint8Array)return ko(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Lo(r);if(Array.isArray(r))return r;throw new L("Must be a string, Uint8Array, Component[], or another Multiaddr")}var $e=class r{[pn]=!0;#t;#r;#e;constructor(t="/",e={}){this.#t=$a(t),e.validate!==!1&&Ua(this)}get bytes(){return this.#e==null&&(this.#e=Fo(this.#t)),this.#e}toString(){return this.#r==null&&(this.#r=No(this.#t)),this.#r}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new De(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}equals(t){return nt(this.bytes,t.bytes)}[Oa](){return`Multiaddr(${this.toString()})`}};function Ua(r){r.getComponents().forEach(t=>{let e=it.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function Ro(r){return!!r?.[pn]}function Vt(r){return new $e(r)}var E=r=>({match:t=>{let e=t[0];return e==null||e.code!==r||e.value!=null?!1:t.slice(1)}}),d=(r,t)=>({match:e=>{let n=e[0];return n?.code!==r||n.value==null||t!=null&&n.value!==t?!1:e.slice(1)}}),Oo=r=>({match:t=>r.match(t)===!1?t:!1}),y=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),R=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1}}),b=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function _(...r){function t(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var Ba=d(421),rh=_(Ba),Be=d(54),Me=d(55),ze=d(56),gn=d(53),nh=_(Be,y(d(421))),oh=_(Me,y(d(421))),sh=_(ze,y(d(421))),$o=_(R(gn,ze,Be,Me),y(d(421))),Uo=b(d(4),y(d(43))),Bo=b(y(d(42)),d(41),y(d(43))),yn=R(Uo,Bo),qt=R(yn,gn,Be,Me,ze),ih=_(R(yn,b(R(gn,ze,Be,Me),y(d(421))))),ah=_(Uo),ch=_(Bo),lh=_(yn),wn=b(qt,d(6)),fe=b(qt,d(273)),uh=_(b(wn,y(d(421)))),fh=_(fe),bn=b(fe,E(460),y(d(421))),Ve=b(fe,E(461),y(d(421))),Ma=R(bn,Ve),hh=_(bn),dh=_(Ve),mn=R(qt,wn,fe,bn,Ve),Mo=R(b(mn,E(477),y(d(421)))),ph=_(Mo),zo=R(b(mn,E(478),y(d(421))),b(mn,E(448),y(d(449)),E(477),y(d(421)))),mh=_(zo),Vo=b(fe,E(280),y(d(466)),y(d(466)),y(d(421))),gh=_(Vo),qo=b(Ve,E(465),y(d(466)),y(d(466)),y(d(421))),yh=_(qo),Ue=R(Mo,zo,b(wn,y(d(421))),b(Ma,y(d(421))),b(qt,y(d(421))),Vo,qo,d(421)),wh=_(Ue),za=b(y(Ue),E(290),Oo(E(281)),y(d(421))),bh=_(za),Va=R(b(Ue,E(290),E(281),y(d(421))),b(Ue,E(281),y(d(421))),b(E(281),y(d(421)))),xh=_(Va),qa=b(qt,R(b(d(6,"80")),b(d(6),E(480)),E(480)),y(d(481)),y(d(421))),jo=_(qa),ja=b(qt,R(b(d(6,"443")),b(d(6,"443"),E(480)),b(d(6),E(443)),b(d(6),E(448),E(480)),b(E(448),E(480)),E(448),E(443)),y(d(481)),y(d(421))),Ho=_(ja),Ha=R(b(d(777),y(d(421)))),vh=_(Ha),Wa=R(b(d(400),y(d(421)))),Eh=_(Wa);function at(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var qe=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},jt=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new qe(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new qe(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var xn=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function vn(r={}){return Ga(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Ga(r,t){t=t??{};let e=t.onEnd,n=new jt,o,s,i,a=at(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((g,w)=>{s=S=>{s=null,n.push(S);try{g(r(n))}catch(A){w(A)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=at()})}},f=g=>s!=null?s(g):(n.push(g),o),l=g=>(n=new jt,s!=null?s({error:g}):(n.push({error:g}),o)),h=g=>{if(i)return o;if(t?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:g})},u=g=>i?o:(i=!0,g!=null?l(g):f({done:!0})),p=()=>(n=new jt,u(),{done:!0}),m=g=>(u(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:m,push:h,end:u,get readableLength(){return n.size},onEmpty:async g=>{let w=g?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let S,A;w!=null&&(S=new Promise((O,F)=>{A=()=>{F(new xn)},w.addEventListener("abort",A)}));try{await Promise.race([a.promise,S])}finally{A!=null&&w!=null&&w?.removeEventListener("abort",A)}}},e==null)return o;let x=o;return o={[Symbol.asyncIterator](){return this},next(){return x.next()},throw(g){return x.throw(g),e!=null&&(e(g),e=void 0),{done:!0}},return(){return x.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(g){return x.end(g),e!=null&&(e(g),e=void 0),o},get readableLength(){return x.readableLength},onEmpty:g=>x.onEmpty(g)},o}var En=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},Wo=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function _n(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,l=new Promise((h,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){u(Wo(i));return}if(i&&(c=()=>{u(Wo(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,u),e===Number.POSITIVE_INFINITY)return;let p=new En;a=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(m){u(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?h():o instanceof Error?u(o):(p.message=o??`Promise timed out after ${e} milliseconds`,u(p))},e)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}var Ka=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function Qa(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:f,removeListener:l}=Ka(r),h=async(...p)=>{let m=e.multiArgs?p:p[0];if(e.filter)try{if(!await e.filter(m))return}catch(x){n(),i(x);return}c.push(m),e.count===c.length&&(n(),s(c))},u=(...p)=>{n(),i(e.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)l(p,h);for(let p of e.rejectionEvents)a.includes(p)||l(p,u)};for(let p of a)f(p,h);for(let p of e.rejectionEvents)a.includes(p)||f(p,u);e.signal&&e.signal.addEventListener("abort",()=>{u(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=_n(o,{milliseconds:e.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function je(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Qa(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Cn(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var He=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};function Ja(r){return r.reason}async function he(r,t,e){if(t==null)return r;let n=e?.translateError??Ja;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var We=class{deferred;signal;onProgress;constructor(t){this.signal=t?.signal,this.onProgress=t?.onProgress,this.deferred=at(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new W)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Xa(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ge=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(t,e){this.id=Xa(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new W),this.cleanup())}async join(t){let e=new We(t);return this.recipients.push(e),t?.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await he(this.fn({...this.options??{},signal:this.controller.signal,onProgress:e=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(e)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var Ht=class extends At{concurrency;maxSize;queue;pending;sort;paused;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=Cn(this.emitEmpty.bind(this),1),this.emitIdle=Cn(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new He;let n=new Ge(t,e);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new W)}),this.clear()}async onEmpty(t){this.size!==0&&await je(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await je(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await je(this,"idle",t)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=vn({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new W("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};function Wt(r){let t=new globalThis.AbortController;function e(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();t.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}function Ke(r,t){if(typeof r=="string")return Ya(r);if(typeof r=="number")return ec(r,t);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function Ya(r){if(typeof r!="string"||r.length===0||r.length>100)throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let t=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!t?.groups)return NaN;let{value:e,unit:n="ms"}=t.groups,o=parseFloat(e),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw new Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function Za(r){let t=Math.abs(r);return t>=315576e5?`${Math.round(r/315576e5)}y`:t>=26298e5?`${Math.round(r/26298e5)}mo`:t>=6048e5?`${Math.round(r/6048e5)}w`:t>=864e5?`${Math.round(r/864e5)}d`:t>=36e5?`${Math.round(r/36e5)}h`:t>=6e4?`${Math.round(r/6e4)}m`:t>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function tc(r){let t=Math.abs(r);return t>=315576e5?Ct(r,t,315576e5,"year"):t>=26298e5?Ct(r,t,26298e5,"month"):t>=6048e5?Ct(r,t,6048e5,"week"):t>=864e5?Ct(r,t,864e5,"day"):t>=36e5?Ct(r,t,36e5,"hour"):t>=6e4?Ct(r,t,6e4,"minute"):t>=1e3?Ct(r,t,1e3,"second"):`${r} ms`}function ec(r,t){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return t?.long?tc(r):Za(r)}function Ct(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function Sn(r){e.debug=e,e.default=e,e.coerce=c,e.disable=s,e.enable=o,e.enabled=i,e.humanize=Ke,e.destroy=f,Object.keys(r).forEach(l=>{e[l]=r[l]}),e.names=[],e.skips=[],e.formatters={};function t(l){let h=0;for(let u=0;u<l.length;u++)h=(h<<5)-h+l.charCodeAt(u),h|=0;return e.colors[Math.abs(h)%e.colors.length]}e.selectColor=t;function e(l,h){let u,p=null,m,x;function g(...w){if(!g.enabled)return;let S=g,A=Number(new Date),O=A-(u||A);S.diff=O,S.prev=u,S.curr=A,u=A,w[0]=e.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let F=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,($,H)=>{if($==="%%")return"%";F++;let gt=e.formatters[H];if(typeof gt=="function"){let Ss=w[F];$=gt.call(S,Ss),w.splice(F,1),F--}return $}),e.formatArgs.call(S,w),h?.onLog!=null&&h.onLog(...w),(S.log||e.log).apply(S,w)}return g.namespace=l,g.useColors=e.useColors(),g.color=e.selectColor(l),g.extend=n,g.destroy=e.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(m!==e.namespaces&&(m=e.namespaces,x=e.enabled(l)),x),set:w=>{p=w}}),typeof e.init=="function"&&e.init(g),g}function n(l,h){let u=e(this.namespace+(typeof h>"u"?":":h)+l);return u.log=this.log,u}function o(l){e.save(l),e.namespaces=l,e.names=[],e.skips=[];let h,u=(typeof l=="string"?l:"").split(/[\s,]+/),p=u.length;for(h=0;h<p;h++)u[h]&&(l=u[h].replace(/\*/g,".*?"),l[0]==="-"?e.skips.push(new RegExp("^"+l.substr(1)+"$")):e.names.push(new RegExp("^"+l+"$")))}function s(){let l=[...e.names.map(a),...e.skips.map(a).map(h=>"-"+h)].join(",");return e.enable(""),l}function i(l){if(l[l.length-1]==="*")return!0;let h,u;for(h=0,u=e.skips.length;h<u;h++)if(e.skips[h].test(l))return!1;for(h=0,u=e.names.length;h<u;h++)if(e.names[h].test(l))return!0;return!1}function a(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function c(l){return l instanceof Error?l.stack??l.message:l}function f(){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 e.setupFormatters(e.formatters),e.enable(e.load()),e}var Qe=cc(),rc=["#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 nc(){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 oc(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ke(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}var sc=console.debug??console.log??(()=>{});function ic(r){try{r?Qe?.setItem("debug",r):Qe?.removeItem("debug")}catch{}}function ac(){let r;try{r=Qe?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function cc(){try{return localStorage}catch{}}function lc(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var Ko=Sn({formatArgs:oc,save:ic,load:ac,useColors:nc,setupFormatters:lc,colors:rc,storage:Qe,log:sc});var B=Ko;B.formatters.b=r=>r==null?"undefined":U.baseEncode(r);B.formatters.t=r=>r==null?"undefined":G.baseEncode(r);B.formatters.m=r=>r==null?"undefined":wt.baseEncode(r);B.formatters.p=r=>r==null?"undefined":r.toString();B.formatters.c=r=>r==null?"undefined":r.toString();B.formatters.k=r=>r==null?"undefined":r.toString();B.formatters.a=r=>r==null?"undefined":r.toString();function Qo(r,t=""){let e=Jo(r.message),n=Jo(r.stack);return e!=null&&n!=null?n.includes(e)?`${n.split(`
3
- `).join(`
4
- ${t}`)}`:`${e}
5
- ${t}${n.split(`
6
- `).join(`
7
- ${t}`)}`:n!=null?`${n.split(`
8
- `).join(`
9
- ${t}`)}`:e!=null?`${e}`:`${r.toString()}`}function uc(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Xo(r,t=""){if(uc(r)){let e=Qo(r,t);return r.errors.length>0?(t=`${t} `,e+=`
10
- ${t}${r.errors.map(n=>`${Xo(n,`${t}`)}`).join(`
11
- ${t}`)}`):e+=`
12
- ${t}[Error list was empty]`,e.trim()}return Qo(r,t)}B.formatters.e=r=>r==null?"undefined":Xo(r);function fc(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t.useColors=()=>!1,t}function de(r,t){let e=fc(`${r}:trace`);return B.enabled(`${r}:trace`)&&B.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(e=B(`${r}:trace`,t)),Object.assign(B(r,t),{error:B(`${r}:error`,t),trace:e,newScope:n=>de(`${r}:${n}`,t)})}function Jo(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}async function*pe(r,t={}){let e=r.getReader();try{for(;;){let n=await e.read();if(n.done)return;yield n.value}}finally{t.preventCancel!==!0&&await e.cancel(),e.releaseLock()}}var Je=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*Gt(r,t={}){let e=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),Pt(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(t?.maxMessageLength??o.length))throw new Je("Incoming message too long");let i=o.split(e);o=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var St=class extends Error{static name="InvalidRequestError";constructor(t="Invalid request"){super(t),this.name="InvalidRequestError"}},j=class extends Error{static name="BadResponseError";constructor(t="Bad response"){super(t),this.name="BadResponseError"}};var Xe={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},Ye=class{url;started;httpQueue;shutDownController;timeout;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(t,e){this.log=t.logger.forComponent("delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new Ht({concurrency:e.concurrentRequests??Xe.concurrentRequests}),this.inFlightRequests=new Map,this.url=e.url instanceof URL?e.url:new URL(e.url),this.timeout=e.timeout??Xe.timeout,this.filterAddrs=e.filterAddrs,this.filterProtocols=e.filterProtocols,this.cacheName=e.cacheName??Xe.cacheName,this.cacheTTL=e.cacheTTL??Xe.cacheTTL}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&this.log("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(t,e={}){this.log("getProviders starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Wt([this.shutDownController.signal,n,e.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers(),a=0;this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let c=new URL(`${this.url}routing/v1/providers/${t}`);this.#r(c,e.filterAddrs,e.filterProtocols);let f=await this.#e(c.toString(),{headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:o});if(!f.ok){if(f.status===404)return;throw f.status===422?new St("Request does not conform to schema or semantic constraints"):new j(`Unexpected status code: ${f.status}`)}let l=f.headers.get("Content-Type");if(l==null)throw new j("No Content-Type header received");if(f.body==null){if(l!=="application/x-ndjson")throw new j("Routing response had no body");return}if(l.startsWith("application/json")){let u=(await f.json()).Providers??[];for(let p of u){let m=this.#t(p);m!=null&&(a++,yield m)}}else if(l.includes("application/x-ndjson"))for await(let h of Gt(pe(f.body))){let u=this.#t(h);u!=null&&(a++,yield u)}else throw new j(`Unsupported Content-Type: ${l}`)}finally{o.clear(),i.resolve(),this.log("getProviders finished found %d providers for %c",a,t)}}async*getPeers(t,e={}){this.log("getPeers starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Wt([this.shutDownController.signal,n,e.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.url}routing/v1/peers/${t}`);this.#r(a,e.filterAddrs,e.filterProtocols);let c=await this.#e(a.toString(),{headers:{Accept:"application/x-ndjson"},signal:o});if(c.status===404)return;if(c.status===422)throw new St("Request does not conform to schema or semantic constraints");if(c.body==null)throw new j("Routing response had no body");if(c.headers.get("Content-Type")?.startsWith("application/json")){let h=(await c.json()).Peers??[];for(let u of h){let p=this.#t(u);p!=null&&(yield p)}}else for await(let l of Gt(pe(c.body))){let h=this.#t(l);h!=null&&(yield h)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),i.resolve(),this.log("getPeers finished: %c",t)}}async*getClosestPeers(t,e={}){let n;if(T.asCID(t)===t||t instanceof T)n=t.toV1().toString();else throw new It("Key must be CID");this.log("getClosestPeers starts: %s",n);let o=AbortSignal.timeout(this.timeout),s=Wt([this.shutDownController.signal,o,e.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));try{await i.promise;let c=new URL(`${this.url}routing/v1/dht/closest/peers/${n}`);this.#r(c,e.filterAddrs,e.filterProtocols);let f=await this.#e(c.toString(),{headers:{Accept:"application/x-ndjson"},signal:s});if(f.status===404)return;if(f.status===422)throw new St("Request does not conform to schema or semantic constraints");if(f.body==null)throw new j("Routing response had no body");if(f.headers.get("Content-Type")?.startsWith("application/json")){let u=(await f.json()).Peers??[];for(let p of u){let m=this.#t(p);m!=null&&(yield m)}}else for await(let h of Gt(pe(f.body))){let u=this.#t(h);u!=null&&(yield u)}}catch(c){this.log.error("getClosestPeers errored - %e",c)}finally{s.clear(),a.resolve(),this.log("getClosestPeers finished: %s",n)}}async getIPNS(t,e={}){this.log("getIPNS starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Wt([this.shutDownController.signal,n,e.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.url}routing/v1/ipns/${t}`;try{await s.promise;let c=await this.#e(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(this.log("getIPNS GET %s %d",a,c.status),c.status===404)throw new et("No matching records found");if(c.status===422)throw new St("Request does not conform to schema or semantic constraints");if(!c.ok)throw new j(`Unexpected status code: ${c.status}`);let f=c.headers.get("Content-Type");if(f==null||!f.includes("application/vnd.ipfs.ipns-record"))throw new et("No matching records found");if(c.body==null)throw new j("GET ipns response had no body");let l=await c.arrayBuffer();return new Uint8Array(l,0,l.byteLength)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),i.resolve(),this.log("getIPNS finished: %c",t)}}async putIPNS(t,e,n={}){this.log("putIPNS starts: %c",t);let o=AbortSignal.timeout(this.timeout),s=Wt([this.shutDownController.signal,o,n.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${t}`;try{await i.promise;let f=await this.#e(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:oe(e),signal:s});if(this.log("putIPNS PUT %s %d",c,f.status),f.status!==200)throw new j("PUT ipns response had status other than 200")}catch(f){throw this.log.error("putIPNS PUT %s error - %e",c,f.stack),f}finally{s.clear(),a.resolve(),this.log("putIPNS finished: %c",t)}}#t(t){try{let e=[],n=t.Addrs?.map(Vt)??[];return t.Protocols!=null&&e.push(...t.Protocols),t.Protocol!=null&&(e.push(t.Protocol),delete t.Protocol),{...t,Schema:"peer",ID:T.createV1(114,dc(t.ID)),Addrs:n,Protocols:e}}catch(e){this.log.error("could not conform record to peer schema - %e",e)}}#r(t,e,n){if(e!=null||this.filterAddrs!=null){let o=e?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&t.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&t.searchParams.set("filter-protocols",o)}}async#e(t,e){let n=e.method??"GET",o=`${n}-${t}`;if(n==="GET"){let c=await this.cache?.match(t);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",o),this.logResponse(c),c;this.log("evicting cached response for %s",o),await this.cache?.delete(t)}else this.cache!=null&&this.log("cache miss for %s",o)}let s=this.inFlightRequests.get(o);if(s!=null){let c=await s;return this.log("deduplicating outgoing request for %s",o),c.clone()}this.log("outgoing request:"),this.logRequest(t,e);let i=fetch(t,e).then(async c=>{if(this.log("incoming response:"),this.logResponse(c),this.cache!=null&&c.ok&&n==="GET"){let f=Date.now()+this.cacheTTL,l=new Headers(c.headers);l.set("x-cache-expires",f.toString());let h=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:l});await this.cache.put(t,h)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(t,e){let n=new Headers(e.headers);this.log("%s %s HTTP/1.1",e.method??"GET",t);for(let[o,s]of n.entries())this.log("%s: %s",o,s)}logResponse(t){this.log("HTTP/1.1 %d %s",t.status,t.statusText);for(let[e,n]of t.headers.entries())this.log("%s: %s",e,n)}};function dc(r){let t=U.baseDecode(r);return ut(t)}function pc(r){return r[Symbol.asyncIterator]!=null}function mc(r){if(pc(r))return(async()=>{for await(let t of r)return t})();for(let t of r)return t}var Yo=mc;function gc(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var In=gc;function yc(r){return r[Symbol.asyncIterator]!=null}function wc(r,t){let e=0;if(yc(r))return(async function*(){for await(let c of r)yield t(c,e++)})();let n=In(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=t(o,e++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield t(c,e++)})();let a=t;return(function*(){yield i;for(let c of n)yield a(c,e++)})()}var Ze=wc;function Zo(r){return t=>new Ye(t,r)}var tr=C("/ipns/");function ts(r){return nt(r.subarray(0,tr.byteLength),tr)}var er=class{name="delegated-http-router";client;constructor(t,e){this.client=Zo(e)(t)}async provide(t,e){}async cancelReprovide(t,e){}async*findProviders(t,e){yield*Ze(this.client.getProviders(t,e),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols,routing:"delegated-http-routing"}))}async put(t,e,n){if(!ts(t))return;let o=ut(t.slice(tr.length)),s=T.createV1(114,o);await this.client.putIPNS(s,e,n)}async get(t,e){if(!ts(t))throw new et("Not found");let n=ut(t.slice(tr.length)),o=T.createV1(114,n);try{return await this.client.getIPNS(o,e)}catch(s){throw s.name==="BadResponseError"?new et("Not found"):s}}async findPeer(t,e){let n=await Yo(this.client.getPeers(t,e));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new et("Not found")}async*getClosestPeers(t,e){}toString(){return`DelegatedHTTPRouter(${this.client.url})`}};function es(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}function rs(r){return t=>new er(t,es(r))}var ns="[a-fA-F\\d:]",pt=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${ns})|(?<=${ns})(?=\\s|$))`:"",J="(?: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}",D="[a-fA-F\\d]{1,4}",rr=`
2
+ "use strict";var HeliaHttp=(()=>{var rs=Object.create;var fe=Object.defineProperty;var ns=Object.getOwnPropertyDescriptor;var os=Object.getOwnPropertyNames;var ss=Object.getPrototypeOf,is=Object.prototype.hasOwnProperty;var er=(r,t)=>()=>{try{return t||r((t={exports:{}}).exports,t),t.exports}catch(e){throw t=0,e}},F=(r,t)=>{for(var e in t)fe(r,e,{get:t[e],enumerable:!0})},Sn=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of os(t))!is.call(r,o)&&o!==e&&fe(r,o,{get:()=>t[o],enumerable:!(n=ns(t,o))||n.enumerable});return r};var as=(r,t,e)=>(e=r!=null?rs(ss(r)):{},Sn(t||!r||!r.__esModule?fe(e,"default",{value:r,enumerable:!0}):e,r)),cs=r=>Sn(fe({},"__esModule",{value:!0}),r);var Ar=er(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Netmask4Impl=void 0;Nt.ip2long=kt;Nt.long2ip=Y;function Y(r){let t=(r&-16777216)>>>24,e=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[t,e,n,o].join(".")}var Ti=48,Ai=97,Di=65;function Li(r){let t=0,e=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,e=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,e=8,n="7"));let s=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)t=t*e+(r.charCodeAt(o)-Ti)>>>0;else if(e===16)if("a"<=r[o]&&r[o]<="f")t=t*e+(10+r.charCodeAt(o)-Ai)>>>0;else if("A"<=r[o]&&r[o]<="F")t=t*e+(10+r.charCodeAt(o)-Di)>>>0;else break;else break;if(t>4294967295)throw new Error("too large");o++}if(o===s)throw new Error("empty octet");return[t,o]}function kt(r){let t=[];for(let e=0;e<=3&&r.length!==0;e++){if(e>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=Li(r);r=r.substring(o),t.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}}var Tr=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(!n){let o=t.split("/",2);t=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=kt(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(kt(t)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+t)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Y(this.netLong),this.mask=Y(this.maskLong),this.hostmask=Y(~this.maskLong),this.first=this.bitmask<=30?Y(this.netLong+1):this.base,this.last=this.bitmask<=30?Y(this.netLong+this.size-2):Y(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Y(this.netLong+this.size-1):void 0}contains(t){return typeof t=="string"&&(t.indexOf("/")>0||t.split(".").length!==4)&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):(kt(t)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(t=1){return new r(Y(this.netLong+this.size*t),this.mask)}forEach(t){let e=kt(this.first),n=kt(this.last),o=0;for(;e<=n;)t(Y(e),e,o),o++,e++}toString(){return this.base+"/"+this.bitmask}};Nt.Netmask4Impl=Tr});var eo=er(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.Netmask6Impl=void 0;Rt.ip6bigint=Lr;Rt.bigint2ip6=yt;var ki=Ar(),Dr=(1n<<128n)-1n;function Lr(r){let t=r.indexOf("%");t!==-1&&(r=r.substring(0,t));let e=r.lastIndexOf(":");if(e!==-1&&r.indexOf(".",e)!==-1){let n=r.substring(e+1),o=(0,ki.ip2long)(n),s=r.substring(0,e+1)+"0:0";return to(s)&~0xffffffffn|BigInt(o)}return to(r)}function to(r){let t=r.indexOf("::"),e;if(t!==-1){let o=r.substring(0,t),s=r.substring(t+2),i=o===""?[]:o.split(":"),a=s===""?[]:s.split(":"),c=8-i.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");e=[...i,...Array(c).fill("0"),...a]}else e=r.split(":");if(e.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+e.length);let n=0n;for(let o=0;o<8;o++){let s=e[o];if(s.length===0||s.length>4)throw new Error('Invalid IPv6: bad group "'+s+'"');let i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error('Invalid IPv6: bad group "'+s+'"');n=n<<16n|BigInt(i)}return n}function yt(r){if(r<0n||r>Dr)throw new Error("Invalid IPv6 address value");let t=[];for(let i=0;i<8;i++)t.unshift(Number(r&0xffffn)),r>>=16n;let e=-1,n=0,o=-1,s=0;for(let i=0;i<8;i++)t[i]===0?o===-1?(o=i,s=1):s++:(s>n&&s>=2&&(e=o,n=s),o=-1,s=0);if(s>n&&s>=2&&(e=o,n=s),e!==-1&&e+n===8&&e>0)return t.slice(0,e).map(a=>a.toString(16)).join(":")+"::";if(e===0)return"::"+t.slice(n).map(a=>a.toString(16)).join(":");if(e>0){let i=t.slice(0,e).map(c=>c.toString(16)),a=t.slice(e+n).map(c=>c.toString(16));return i.join(":")+"::"+a.join(":")}else return t.map(i=>i.toString(16)).join(":")}var kr=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");let n=e;if(n==null){let o=t.indexOf("/");o!==-1?(n=parseInt(t.substring(o+1),10),t=t.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=Dr>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=Lr(t)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+t)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=yt(this.netBigint),this.mask=yt(this.maskBigint),this.hostmask=yt(~this.maskBigint&Dr),this.first=this.base,this.last=yt(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(t){return typeof t=="string"&&t.indexOf("/")>0&&(t=new r(t)),t instanceof r?this.contains(t.base)&&this.contains(t.last):(Lr(t)&this.maskBigint)===this.netBigint}next(t=1){let e=1n<<BigInt(128-this.bitmask);return new r(yt(this.netBigint+e*BigInt(t)),this.bitmask)}forEach(t){let e=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,s=0;for(;e<=o;)t(yt(e),Number(e),s),s++,e++}toString(){return this.base+"/"+this.bitmask}};Rt.Netmask6Impl=kr});var ro=er(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.long2ip=ft.ip2long=ft.Netmask=void 0;var ve=Ar();Object.defineProperty(ft,"ip2long",{enumerable:!0,get:function(){return ve.ip2long}});Object.defineProperty(ft,"long2ip",{enumerable:!0,get:function(){return ve.long2ip}});var Ni=eo(),Nr=class r{constructor(t,e){if(typeof t!="string")throw new Error("Missing `net' parameter");(t.indexOf("/")!==-1?t.substring(0,t.indexOf("/")):t).indexOf(":")!==-1?this._impl=new Ni.Netmask6Impl(t,e):this._impl=new ve.Netmask4Impl(t,e),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof ve.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(t){return typeof t=="string"&&(t.indexOf("/")>0?t=new r(t):t.indexOf(":")===-1&&t.split(".").length!==4&&(t=new r(t))),t instanceof r?this.contains(t.base)&&this.contains(t.broadcast||t.last):this._impl.contains(t)}next(t=1){let e=this._impl.next(t);return new r(e.base,e.bitmask)}forEach(t){this._impl.forEach(t)}toString(){return this._impl.toString()}};ft.Netmask=Nr});var ic={};F(ic,{withHTTP:()=>sc});var V=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var _t=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var et=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}};function ls(r){return typeof r?.handleEvent=="function"}function us(r){return(r!==!0&&r!==!1&&r?.once)??!1}var It=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){let o=us(n);super.addEventListener(t,i=>{if(o){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==e),this.#t.set(i.type,a))}ls(e)?e.handleEvent(i):e(i)},n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:o})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function B(r=0){return new Uint8Array(r)}function J(r=0){return new Uint8Array(r)}function fs(r){return r?.buffer instanceof ArrayBuffer}function rr(r){if(fs(r))return r;let t=r.slice();return new Uint8Array(t.buffer,0,t.byteLength)}function rt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=J(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return rr(e)}function nt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var Cn=Symbol.for("@achingbrain/uint8arraylist");function Pn(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function St(r){return!!r?.[Cn]}var he=class r{bufs;length;[Cn]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(St(n)){e+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(St(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Pn(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Pn(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(St(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return rt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:rt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=n,s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,f=e>a&&e<=c;if(l&&f){if(t===a&&e===c){n.push(i);break}let h=t-a;n.push(i.subarray(h,h+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(f){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!St(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,f;for(let h=e;h<=c;h+=f){f=0;for(let u=l;u>=0;u--){let p=this.get(h+u);if(n[u]!==p){f=Math.max(1,u-a[p]);break}}if(f===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=J(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=B(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=B(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=B(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=J(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=B(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=B(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=B(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=B(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=B(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!nt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var ar={};F(ar,{base10:()=>ys});var xc=new Uint8Array(0);function Tn(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ot(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return pt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return pt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function An(r){return new TextEncoder().encode(r)}function Dn(r){return new TextDecoder().decode(r)}function hs(r){return r?.buffer instanceof ArrayBuffer}function pt(r){return hs(r)?r:r.slice()}function ds(r,t,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,e){var c=i.toLowerCase().charCodeAt(0),l=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),l!==a&&(n[l]=s)}}var f=r.length,h=r.charAt(0),u=Math.log(f)/Math.log(256),p=Math.log(256)/Math.log(f);function S(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var C=0,N=0,O=0,U=g.length;O!==U&&g[O]===0;)O++,C++;for(var X=(U-O)*p+1>>>0,$=new Uint8Array(X);O!==U;){for(var K=g[O],ct=0,q=X-1;(K!==0||ct<N)&&q!==-1;q--,ct++)K+=256*$[q]>>>0,$[q]=K%f>>>0,K=K/f>>>0;if(K!==0)throw new Error("Non-zero carry");N=ct,O++}for(var tt=X-N;tt!==X&&$[tt]===0;)tt++;for(var ue=h.repeat(C);tt<X;++tt)ue+=r.charAt($[tt]);return ue}function R(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var C=0;if(g[C]!==" "){for(var N=0,O=0;g[C]===h;)N++,C++;for(var U=(g.length-C)*u+1>>>0,X=new Uint8Array(U);g[C];){var $=n[g.charCodeAt(C)];if($===255)return;for(var K=0,ct=U-1;($!==0||K<O)&&ct!==-1;ct--,K++)$+=f*X[ct]>>>0,X[ct]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");O=K,C++}if(g[C]!==" "){for(var q=U-O;q!==U&&X[q]===0;)q++;for(var tt=new Uint8Array(N+(U-q)),ue=N;q!==U;)tt[ue++]=X[q++];return tt}}}function y(g){var C=R(g);if(C)return C;throw new Error(`Non-${t} character`)}return{encode:S,decodeUnsafe:R,decode:y}}var ps=ds,ms=ps,kn=ms;var nr=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},or=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Nn(this,t)}},sr=class{decoders;constructor(t){this.decoders=t}or(t){return Nn(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Nn(r,t){return new sr({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ir=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new nr(t,e,n),this.decoder=new or(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Pt({name:r,prefix:t,encode:e,decode:n}){return new ir(r,t,e,n)}function lt({name:r,prefix:t,alphabet:e,caseInsensitive:n=!1}){let{encode:o,decode:s}=kn(e,r,n);return Pt({prefix:t,name:r,encode:o,decode:i=>ot(s(i))})}function gs(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let f=t[r[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|f,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function ws(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function bs(r,t){let e={};for(let n=0;n<r.length;++n)if(e[r[n]]=n,t){let o=r[n].toLowerCase(),s=r[n].toUpperCase();o!==r[n]&&(e[o]=n),s!==r[n]&&(e[s]=n)}return e}function _({name:r,prefix:t,bitsPerChar:e,alphabet:n,caseInsensitive:o=!1}){let s=bs(n,o);return Pt({prefix:t,name:r,encode(i){return ws(i,n,e)},decode(i){return gs(i,s,e,r)}})}var ys=lt({prefix:"9",name:"base10",alphabet:"0123456789"});var cr={};F(cr,{base16:()=>xs,base16upper:()=>vs});var xs=_({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),vs=_({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var lr={};F(lr,{base2:()=>Es});var Es=_({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ur={};F(ur,{base256emoji:()=>Cs});var Rn=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),_s=Rn.reduce((r,t,e)=>(r[e]=t,r),[]),Is=Rn.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Ss(r){return r.reduce((t,e)=>(t+=_s[e],t),"")}function Ps(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Is[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Cs=Pt({prefix:"\u{1F680}",name:"base256emoji",encode:Ss,decode:Ps});var fr={};F(fr,{base32:()=>ut,base32hex:()=>Ls,base32hexpad:()=>Ns,base32hexpadupper:()=>Rs,base32hexupper:()=>ks,base32pad:()=>As,base32padupper:()=>Ds,base32upper:()=>Ts,base32z:()=>Fs});var ut=_({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Ts=_({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),As=_({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),Ds=_({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),Ls=_({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),ks=_({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Ns=_({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Rs=_({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),Fs=_({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var hr={};F(hr,{base36:()=>Wt,base36upper:()=>Os});var Wt=lt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Os=lt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var dr={};F(dr,{base58btc:()=>z,base58flickr:()=>Us});var z=lt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Us=lt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var mr={};F(mr,{base64:()=>Gt,base64pad:()=>$s,base64url:()=>pr,base64urlpad:()=>Bs});var Gt=_({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$s=_({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),pr=_({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Bs=_({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var gr={};F(gr,{base8:()=>zs});var zs=_({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var wr={};F(wr,{identity:()=>Ms});var Ms=Pt({prefix:"\0",name:"identity",encode:r=>Dn(r),decode:r=>An(r)});var Oc=new TextEncoder,Uc=new TextDecoder;var yr={};F(yr,{identity:()=>Kt});var js=Un,Fn=128,Hs=127,Ws=~Hs,Gs=Math.pow(2,31);function Un(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Gs;)t[e++]=r&255|Fn,r/=128;for(;r&Ws;)t[e++]=r&255|Fn,r>>>=7;return t[e]=r|0,Un.bytes=e-n+1,t}var Qs=br,Xs=128,On=127;function br(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw br.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&On)<<o:(i&On)*Math.pow(2,o),o+=7}while(i>=Xs);return br.bytes=s-n,e}var Ks=Math.pow(2,7),Js=Math.pow(2,14),Ys=Math.pow(2,21),Zs=Math.pow(2,28),ti=Math.pow(2,35),ei=Math.pow(2,42),ri=Math.pow(2,49),ni=Math.pow(2,56),oi=Math.pow(2,63),si=function(r){return r<Ks?1:r<Js?2:r<Ys?3:r<Zs?4:r<ti?5:r<ei?6:r<ri?7:r<ni?8:r<oi?9:10},ii={encode:js,decode:Qs,encodingLength:si},ai=ii,Qt=ai;function Xt(r,t=0){return[Qt.decode(r,t),Qt.decode.bytes]}function Ct(r,t,e=0){return Qt.encode(r,t,e),t}function Tt(r){return Qt.encodingLength(r)}function Dt(r,t){let e=t.byteLength,n=Tt(r),o=n+Tt(e),s=new Uint8Array(o+e);return Ct(r,s,0),Ct(e,s,n),s.set(t,o),new At(r,e,t,s)}function mt(r){let t=ot(r),[e,n]=Xt(t),[o,s]=Xt(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new At(e,o,i,t)}function $n(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Tn(r.bytes,e.bytes)}}var At=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=pt(n),this.bytes=pt(o)}};var Bn=0,ci="identity",zn=ot;function li(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Dt(Bn,zn(r))}var Kt={code:Bn,name:ci,encode:zn,digest:li};var Er={};F(Er,{sha256:()=>fi,sha512:()=>hi});var ui=20;function vr({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new xr(r,t,e,n,o)}var xr=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??ui,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?Mn(n,this.code,e?.truncate):n.then(o=>Mn(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function Mn(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Dt(t,r)}function Vn(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var fi=vr({name:"sha2-256",code:18,encode:Vn("SHA-256")}),hi=vr({name:"sha2-512",code:19,encode:Vn("SHA-512")});function jn(r,t){let{bytes:e,version:n}=r;return n===0?pi(e,_r(r),t??z.encoder):mi(e,_r(r),t??ut.encoder)}var Hn=new WeakMap;function _r(r){let t=Hn.get(r);if(t==null){let e=new Map;return Hn.set(r,e),e}return t}var T=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=pt(o),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==Jt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==gi)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Dt(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&$n(t.multihash,n.multihash)}toString(t){return jn(this,t)}toJSON(){return{"/":jn(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Wn(n,o,s.bytes))}else if(e[wi]===!0){let{version:n,multihash:o,code:s}=e,i=mt(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Jt)throw new Error(`Version 0 CID must use dag-pb (code: ${Jt}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Wn(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Jt,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=ot(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new At(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,u]=Xt(t.subarray(e));return e+=u,h},o=n(),s=Jt;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,f=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(t,e){let[n,o]=di(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return _r(s).set(n,t),s}};function di(r,t){switch(r[0]){case"Q":{let e=t??z;return[z.prefix,e.decode(`${z.prefix}${r}`)]}case z.prefix:{let e=t??z;return[z.prefix,e.decode(r)]}case ut.prefix:{let e=t??ut;return[ut.prefix,e.decode(r)]}case Wt.prefix:{let e=t??Wt;return[Wt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function pi(r,t,e){let{prefix:n}=e;if(n!==z.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function mi(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Jt=112,gi=18;function Wn(r,t,e){let n=Tt(r),o=n+Tt(t),s=new Uint8Array(o+e.byteLength);return Ct(r,s,0),Ct(t,s,n),s.set(e,o),s}var wi=Symbol.for("@ipld/js-cid/CID");var Yt={...wr,...lr,...gr,...ar,...cr,...fr,...hr,...dr,...mr,...ur},sl={...Er,...yr};function Qn(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Gn=Qn("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ir=Qn("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=J(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),bi={utf8:Gn,"utf-8":Gn,hex:Yt.base16,latin1:Ir,ascii:Ir,binary:Ir,...Yt},pe=bi;function I(r,t="utf8"){let e=pe[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}var Sr={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Xn={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Kn=new globalThis.TextEncoder;function yi(r,t){let e=Sr[t],n=Xn[t];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(t,n*e);return n}function xi(r,t,e){if(e.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Sr[t],o=Xn[t],s=r;for(;s.length>0;){let i=Kn.encodeInto(s,e);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(e[a]),o=BigInt.asUintN(t,o*n)}return o}function Pr(r,{size:t=32,utf8Buffer:e}={}){if(!Sr[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(e)return xi(r,t,e);r=Kn.encode(r)}return yi(r,t)}var Zt={hash:r=>Number(Pr(r,{size:32})),hashV:(r,t)=>vi(Zt.hash(r,t))};function vi(r){let t=r.toString(16);return t.length%2===1&&(t=`0${t}`),I(t,"base16")}var Cr=64,j=class{fp;h;seed;constructor(t,e,n,o=2){if(o>Cr)throw new TypeError("Invalid Fingerprint Size");let s=e.hashV(t,n),i=B(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=e,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(t){return t?.fp instanceof Uint8Array?nt(this.fp,t.fp):!1}};function wt(r,t){return Math.floor(Math.random()*(t-r))+r}var bt=class{contents;constructor(t){this.contents=new Array(t).fill(null)}has(t){if(!(t instanceof j))throw new TypeError("Invalid Fingerprint");return this.contents.some(e=>t.equals(e))}add(t){if(!(t instanceof j))throw new TypeError("Invalid Fingerprint");for(let e=0;e<this.contents.length;e++)if(this.contents[e]==null)return this.contents[e]=t,!0;return!0}swap(t){if(!(t instanceof j))throw new TypeError("Invalid Fingerprint");let e=wt(0,this.contents.length-1),n=this.contents[e];return this.contents[e]=t,n}remove(t){if(!(t instanceof j))throw new TypeError("Invalid Fingerprint");let e=this.contents.findIndex(n=>t.equals(n));return e>-1?(this.contents[e]=null,!0):!1}};var Ei=500,te=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(t){this.filterSize=t.filterSize,this.bucketSize=t.bucketSize??4,this.fingerprintSize=t.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=t.hash??Zt,this.seed=t.seed??wt(0,Math.pow(2,10))}add(t){typeof t=="string"&&(t=I(t));let e=new j(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=(n^e.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new bt(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new bt(this.bucketSize)),this.buckets[n].add(e)||this.buckets[o].add(e))return this.count++,!0;let s=[n,o],i=s[wt(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new bt(this.bucketSize));for(let a=0;a<Ei;a++){let c=this.buckets[i].swap(e);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new bt(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(t){typeof t=="string"&&(t=I(t));let e=new j(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.has(e)??!1;if(o)return o;let s=(n^e.hash())%this.filterSize;return this.buckets[s]?.has(e)??!1}remove(t){typeof t=="string"&&(t=I(t));let e=new j(t,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(t,this.seed)%this.filterSize,o=this.buckets[n]?.remove(e)??!1;if(o)return this.count--,o;let s=(n^e.hash())%this.filterSize,i=this.buckets[s]?.remove(e)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},_i={1:.5,2:.84,4:.95,8:.98};function Ii(r=.001){return r>.002?2:r>1e-5?4:8}function Jn(r,t=.001){let e=Ii(t),n=_i[e],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*e)),Cr);return{filterSize:o,bucketSize:e,fingerprintSize:s}}var me=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(t){this.bucketSize=t.bucketSize??4,this.filterSize=t.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=t.fingerprintSize??2,this.scale=t.scale??2,this.hash=t.hash??Zt,this.seed=t.seed??wt(0,Math.pow(2,10)),this.filterSeries=[new te({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(t){if(typeof t=="string"&&(t=I(t)),this.has(t))return!0;let e=this.filterSeries.find(n=>n.reliable);if(e==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);e=new te({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(e)}return e.add(t)}has(t){typeof t=="string"&&(t=I(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].has(t))return!0;return!1}remove(t){typeof t=="string"&&(t=I(t));for(let e=0;e<this.filterSeries.length;e++)if(this.filterSeries[e].remove(t))return!0;return!1}get count(){return this.filterSeries.reduce((t,e)=>t+e.count,0)}};function ge(r,t=.001,e){return new me({...Jn(r,t),...e??{}})}function Si(r){let t=r.getComponents(),e={},n=0;return t[n]?.name==="ip6zone"&&(e.zone=`${t[n].value}`,n++),t[n]?.name==="ip4"||t[n]?.name==="ip6"||t[n]?.name==="dns"||t[n]?.name==="dns4"||t[n]?.name==="dns6"?(e.type=t[n].name,e.host=t[n].value,n++):t[n]?.name==="dnsaddr"&&(e.type=t[n].name,e.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(e.protocol=t[n].name==="tcp"?"tcp":"udp",e.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(e.type==="ip4"?e.cidr=parseInt(`${t[n].value}`):e.type==="ip6"&&(e.cidr=`${t[n].value}`),n++),e.type==null||e.host==null?null:(t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e)}function we(r){let t=Si(r);if(t==null)throw new _t(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t}var be=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let u=Number.parseInt(h,t);if(!Number.isNaN(u))return u});if(f===void 0)break;if(s*=t,s+=f,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Pi=45,Ci=15,ye=new be;function Yn(r){if(!(r.length>Ci))return ye.new(r).parseWith(()=>ye.readIPv4Addr())}function Zn(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Pi))return ye.new(r).parseWith(()=>ye.readIPv6Addr())}function Lt(r){return!!Yn(r)}function xe(r){return!!Zn(r)}var no=as(ro(),1),Ri=["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"],Fi=Ri.map(r=>new no.Netmask(r));function Rr(r){for(let t of Fi)if(t.contains(r))return!0;return!1}function Oi(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function Ui(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return Rr(o)}function $i(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function Bi(r){let t=r.split(":"),e=t[t.length-1];return Rr(e)}function zi(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 oo(r){if(Lt(r))return Rr(r);if(Oi(r))return Ui(r);if($i(r))return Bi(r);if(xe(r))return zi(r)}function so(r){try{let t=we(r);switch(t.type){case"ip4":case"ip6":return oo(t.host)??!1;default:return t.host==="localhost"}}catch{return!1}}var Mi=Math.pow(2,7),qi=Math.pow(2,14),Vi=Math.pow(2,21),Fr=Math.pow(2,28),Or=Math.pow(2,35),Ur=Math.pow(2,42),$r=Math.pow(2,49),E=128,L=127;function Ft(r){if(r<Mi)return 1;if(r<qi)return 2;if(r<Vi)return 3;if(r<Fr)return 4;if(r<Or)return 5;if(r<Ur)return 6;if(r<$r)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Br(r,t,e=0){switch(Ft(r)){case 8:t[e++]=r&255|E,r/=128;case 7:t[e++]=r&255|E,r/=128;case 6:t[e++]=r&255|E,r/=128;case 5:t[e++]=r&255|E,r/=128;case 4:t[e++]=r&255|E,r>>>=7;case 3:t[e++]=r&255|E,r>>>=7;case 2:t[e++]=r&255|E,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function ji(r,t){let e=r[t],n=0;if(n+=e&L,e<E||(e=r[t+1],n+=(e&L)<<7,e<E)||(e=r[t+2],n+=(e&L)<<14,e<E)||(e=r[t+3],n+=(e&L)<<21,e<E)||(e=r[t+4],n+=(e&L)*Fr,e<E)||(e=r[t+5],n+=(e&L)*Or,e<E)||(e=r[t+6],n+=(e&L)*Ur,e<E)||(e=r[t+7],n+=(e&L)*$r,e<E))return n;throw new RangeError("Could not decode varint")}function Hi(r,t){let e=r.get(t),n=0;if(n+=e&L,e<E||(e=r.get(t+1),n+=(e&L)<<7,e<E)||(e=r.get(t+2),n+=(e&L)<<14,e<E)||(e=r.get(t+3),n+=(e&L)<<21,e<E)||(e=r.get(t+4),n+=(e&L)*Fr,e<E)||(e=r.get(t+5),n+=(e&L)*Or,e<E)||(e=r.get(t+6),n+=(e&L)*Ur,e<E)||(e=r.get(t+7),n+=(e&L)*$r,e<E))return n;throw new RangeError("Could not decode varint")}function zr(r,t=0){return r instanceof Uint8Array?ji(r,t):Hi(r,t)}function Gi(r){return r.buffer instanceof ArrayBuffer}function ee(r){return Gi(r)?r:r.slice()}function Z(r,t="utf8"){let e=pe[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var D=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},st=class extends Error{static name="ValidationError";name="ValidationError"},Ee=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},_e=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function qr(r){return t=>Z(t,r)}function Vr(r){return t=>I(t,r)}function Ot(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function xt(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function io(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=I(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xt(n);return rt([e,o],e.length+o.length)}function ao(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=ut.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xt(n);return rt([e,o],e.length+o.length)}function jr(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=Z(t,"base32"),o=Ot(e);return`${n}:${o}`}var Hr=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new D("Invalid byte value in IP address");t[n]=o}),t},co=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Lt(e[n]),i;s&&(i=Hr(e[n]),e[n]=Z(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,Z(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new D("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},lo=function(r){if(r.byteLength!==4)throw new D("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},uo=function(r){if(r.byteLength!==16)throw new D("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new D(`Invalid IPv6 address "${e}"`)}};function fo(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new D(`Invalid IPv6 address "${r}"`)}}var Mr=Object.values(Yt).map(r=>r.decoder),Qi=(function(){let r=Mr[0].or(Mr[1]);return Mr.slice(2).forEach(t=>r=r.or(t)),r})();function ho(r){return Qi.decode(r)}function po(r){return t=>r.encoder.encode(t)}function Xi(r){if(parseInt(r).toString()!==r)throw new st("Value must be an integer")}function Ki(r){if(r<0)throw new st("Value must be a positive integer, or zero")}function Ji(r){return t=>{if(t>r)throw new st(`Value must be smaller than or equal to ${r}`)}}function Yi(...r){return t=>{for(let e of r)e(t)}}var re=Yi(Xi,Ki,Ji(65535));var A=-1,Wr=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new _e(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},it=new Wr,ha=[{code:4,name:"ip4",size:32,valueToBytes:Hr,bytesToValue:lo,validate:r=>{if(!Lt(r))throw new st(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:xt,bytesToValue:Ot,validate:re},{code:273,name:"udp",size:16,valueToBytes:xt,bytesToValue:Ot,validate:re},{code:33,name:"dccp",size:16,valueToBytes:xt,bytesToValue:Ot,validate:re},{code:41,name:"ip6",size:128,valueToBytes:co,bytesToValue:uo,stringToValue:fo,validate:r=>{if(!xe(r))throw new st(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:A},{code:43,name:"ipcidr",size:8,bytesToValue:qr("base10"),valueToBytes:Vr("base10")},{code:53,name:"dns",size:A},{code:54,name:"dns4",size:A},{code:55,name:"dns6",size:A},{code:56,name:"dnsaddr",size:A},{code:132,name:"sctp",size:16,valueToBytes:xt,bytesToValue:Ot,validate:re},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:A,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:A,bytesToValue:qr("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Vr("base58btc")(r):T.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:jr,valueToBytes:io},{code:445,name:"onion3",size:296,bytesToValue:jr,valueToBytes:ao},{code:446,name:"garlic64",size:A},{code:447,name:"garlic32",size:A},{code:448,name:"tls"},{code:449,name:"sni",size:A},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:A,bytesToValue:po(pr),valueToBytes:ho},{code:480,name:"http"},{code:481,name:"http-path",size:A,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:A}];ha.forEach(r=>{it.addProtocol(r)});function mo(r){let t=[],e=0;for(;e<r.length;){let n=zr(r,e),o=it.getProtocol(n),s=Ft(n),i=da(o,r,e+s),a=0;i>0&&o.size===A&&(a=Ft(i));let c=s+a+i,l={code:n,name:o.name,bytes:ee(r.subarray(e,e+c))};if(i>0){let f=e+s+a,h=r.subarray(f,f+i);l.value=o.bytesToValue?.(h)??Z(h)}t.push(l),e+=c}return t}function go(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=it.getProtocol(n.code),s=Ft(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??I(n.value),a=i.byteLength,o.size===A&&(c=Ft(a)));let l=new Uint8Array(s+c+a),f=0;Br(n.code,l,f),f+=s,i!=null&&(o.size===A&&(Br(a,l,f),f+=c),l.set(i,f)),n.bytes=l}e.push(n.bytes),t+=n.bytes.byteLength}return rt(e,t)}function wo(r){if(r.charAt(0)!=="/")throw new D('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=it.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new D(`Component ${o} was missing value`);e="value"}else if(e==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new D(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}t.push(l),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new D("Incomplete multiaddr");return t}function bo(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=it.getProtocol(t.code);if(e==null)throw new D(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function da(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:zr(t,e)}var pa=Symbol.for("nodejs.util.inspect.custom"),on=Symbol.for("@multiformats/multiaddr");function ma(r){if(r==null&&(r="/"),yo(r))return r.getComponents();if(r instanceof Uint8Array)return mo(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),wo(r);if(Array.isArray(r))return r;throw new D("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ae=class r{[on]=!0;#t;#r;#e;constructor(t="/",e={}){this.#t=ma(t),e.validate!==!1&&ga(this)}get bytes(){return this.#e==null&&(this.#e=go(this.#t)),this.#e}toString(){return this.#r==null&&(this.#r=bo(this.#t)),this.#r}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Ee(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}equals(t){return nt(this.bytes,t.bytes)}[pa](){return`Multiaddr(${this.toString()})`}};function ga(r){r.getComponents().forEach(t=>{let e=it.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function yo(r){return!!r?.[on]}function Bt(r){return new Ae(r)}var x=r=>({match:t=>{let e=t[0];return e==null||e.code!==r||e.value!=null?!1:t.slice(1)}}),d=(r,t)=>({match:e=>{let n=e[0];return n?.code!==r||n.value==null||t!=null&&n.value!==t?!1:e.slice(1)}}),xo=r=>({match:t=>r.match(t)===!1?t:!1}),m=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),k=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1}}),w=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function v(...r){function t(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var wa=d(421),af=v(wa),Le=d(54),ke=d(55),Ne=d(56),an=d(53),cf=v(Le,m(d(421))),lf=v(ke,m(d(421))),uf=v(Ne,m(d(421))),vo=v(k(an,Ne,Le,ke),m(d(421))),Eo=w(d(4),m(d(43))),_o=w(m(d(42)),d(41),m(d(43))),cn=k(Eo,_o),zt=k(cn,an,Le,ke,Ne),ff=v(k(cn,w(k(an,Ne,Le,ke),m(d(421))))),hf=v(Eo),df=v(_o),pf=v(cn),ln=w(zt,d(6)),ce=w(zt,d(273)),mf=v(w(ln,m(d(421)))),gf=v(ce),un=w(ce,x(460),m(d(421))),Re=w(ce,x(461),m(d(421))),ba=k(un,Re),wf=v(un),bf=v(Re),sn=k(zt,ln,ce,un,Re),Io=k(w(sn,x(477),m(d(421)))),yf=v(Io),So=k(w(sn,x(478),m(d(421))),w(sn,x(448),m(d(449)),x(477),m(d(421)))),xf=v(So),Po=w(ce,x(280),m(d(466)),m(d(466)),m(d(421))),vf=v(Po),Co=w(Re,x(465),m(d(466)),m(d(466)),m(d(421))),Ef=v(Co),De=k(Io,So,w(ln,m(d(421))),w(ba,m(d(421))),w(zt,m(d(421))),Po,Co,d(421)),_f=v(De),ya=w(m(De),x(290),xo(x(281)),m(d(421))),If=v(ya),xa=k(w(De,x(290),x(281),m(d(421))),w(De,x(281),m(d(421))),w(x(281),m(d(421)))),Sf=v(xa),va=w(zt,k(w(d(6,"80")),w(d(6),x(480)),x(480)),m(d(481)),m(d(421))),To=v(va),Ea=w(zt,k(w(d(6,"443")),w(d(6,"443"),x(480)),w(d(6),x(443)),w(d(6),x(448),x(480)),w(x(448),x(480)),x(448),x(443)),m(d(481)),m(d(421))),Ao=v(Ea),_a=k(w(d(777),m(d(421)))),Pf=v(_a),Ia=k(w(d(400),m(d(421)))),Cf=v(Ia);function at(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Fe=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Mt=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Fe(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Fe(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var fn=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Do(r={}){return Sa(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Sa(r,t){t=t??{};let e=t.onEnd,n=new Mt,o,s,i,a=at(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,g)=>{s=C=>{s=null,n.push(C);try{y(r(n))}catch(N){g(N)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=at()})}},l=y=>s!=null?s(y):(n.push(y),o),f=y=>(n=new Mt,s!=null?s({error:y}):(n.push({error:y}),o)),h=y=>{if(i)return o;if(t?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},u=y=>i?o:(i=!0,y!=null?f(y):l({done:!0})),p=()=>(n=new Mt,u(),{done:!0}),S=y=>(u(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:S,push:h,end:u,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let C,N;g!=null&&(C=new Promise((O,U)=>{N=()=>{U(new fn)},g.addEventListener("abort",N)}));try{await Promise.race([a.promise,C])}finally{N!=null&&g!=null&&g?.removeEventListener("abort",N)}}},e==null)return o;let R=o;return o={[Symbol.asyncIterator](){return this},next(){return R.next()},throw(y){return R.throw(y),e!=null&&(e(y),e=void 0),{done:!0}},return(){return R.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(y){return R.end(y),e!=null&&(e(y),e=void 0),o},get readableLength(){return R.readableLength},onEmpty:y=>R.onEmpty(y)},o}var hn=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},Lo=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function dn(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,f=new Promise((h,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){u(Lo(i));return}if(i&&(c=()=>{u(Lo(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,u),e===Number.POSITIVE_INFINITY)return;let p=new hn;a=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(S){u(S)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?h():o instanceof Error?u(o):(p.message=o??`Promise timed out after ${e} milliseconds`,u(p))},e)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}var Pa=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function Ca(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:f}=Pa(r),h=async(...p)=>{let S=e.multiArgs?p:p[0];if(e.filter)try{if(!await e.filter(S))return}catch(R){n(),i(R);return}c.push(S),e.count===c.length&&(n(),s(c))},u=(...p)=>{n(),i(e.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)f(p,h);for(let p of e.rejectionEvents)a.includes(p)||f(p,u)};for(let p of a)l(p,h);for(let p of e.rejectionEvents)a.includes(p)||l(p,u);e.signal&&e.signal.addEventListener("abort",()=>{u(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=dn(o,{milliseconds:e.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Oe(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Ca(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function pn(r,t){let e,n=function(){let o=function(){e=void 0,r()};clearTimeout(e),e=setTimeout(o,t)};return n.start=()=>{},n.stop=()=>{clearTimeout(e)},n}var Ue=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};function Ta(r){return r.reason}async function $e(r,t,e){if(t==null)return r;let n=e?.translateError??Ta;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var Be=class{deferred;signal;onProgress;constructor(t){this.signal=t?.signal,this.onProgress=t?.onProgress,this.deferred=at(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new V)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Aa(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var ze=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(t,e){this.id=Aa(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new V),this.cleanup())}async join(t){let e=new Be(t);return this.recipients.push(e),t?.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await $e(this.fn({...this.options??{},signal:this.controller.signal,onProgress:e=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(e)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var qt=class extends It{concurrency;maxSize;queue;pending;sort;paused;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[],this.emitEmpty=pn(this.emitEmpty.bind(this),1),this.emitIdle=pn(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Ue;let n=new ze(t,e);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(e).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new V)}),this.clear()}async onEmpty(t){this.size!==0&&await Oe(this,"empty",t)}async onSizeLessThan(t,e){this.size<t||await Oe(this,"next",{...e,filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await Oe(this,"idle",t)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=Do({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new V("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),t?.signal?.removeEventListener("abort",a),n()}}};function Vt(r){let t=new globalThis.AbortController;function e(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();t.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}async function*le(r,t={}){let e=r.getReader();try{for(;;){let n=await e.read();if(n.done)return;yield n.value}}finally{t.preventCancel!==!0&&await e.cancel(),e.releaseLock()}}var Me=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*jt(r,t={}){let e=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),St(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(t?.maxMessageLength??o.length))throw new Me("Incoming message too long");let i=o.split(e);o=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var Et=class extends Error{static name="InvalidRequestError";constructor(t="Invalid request"){super(t),this.name="InvalidRequestError"}},M=class extends Error{static name="BadResponseError";constructor(t="Bad response"){super(t),this.name="BadResponseError"}};var qe={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},Ve=class{url;started;httpQueue;shutDownController;timeout;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;log;constructor(t,e){this.log=t.logger.forComponent("delegated-routing-v1-http-api-client"),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new qt({concurrency:e.concurrentRequests??qe.concurrentRequests}),this.inFlightRequests=new Map,this.url=e.url instanceof URL?e.url:new URL(e.url),this.timeout=e.timeout??qe.timeout,this.filterAddrs=e.filterAddrs,this.filterProtocols=e.filterProtocols,this.cacheName=e.cacheName??qe.cacheName,this.cacheTTL=e.cacheTTL??qe.cacheTTL}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&this.log("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(t,e={}){this.log("getProviders starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Vt([this.shutDownController.signal,n,e.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers(),a=0;this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let c=new URL(`${this.url}routing/v1/providers/${t}`);this.#r(c,e.filterAddrs,e.filterProtocols);let l=await this.#e(c.toString(),{headers:{accept:"application/x-ndjson, application/json;q=0.8"},signal:o});if(!l.ok){if(l.status===404)return;throw l.status===422?new Et("Request does not conform to schema or semantic constraints"):new M(`Unexpected status code: ${l.status}`)}let f=l.headers.get("Content-Type");if(f==null)throw new M("No Content-Type header received");if(l.body==null){if(f!=="application/x-ndjson")throw new M("Routing response had no body");return}if(f.startsWith("application/json")){let u=(await l.json()).Providers??[];for(let p of u){let S=this.#t(p);S!=null&&(a++,yield S)}}else if(f.includes("application/x-ndjson"))for await(let h of jt(le(l.body))){let u=this.#t(h);u!=null&&(a++,yield u)}else throw new M(`Unsupported Content-Type: ${f}`)}finally{o.clear(),i.resolve(),this.log("getProviders finished found %d providers for %c",a,t)}}async*getPeers(t,e={}){this.log("getPeers starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Vt([this.shutDownController.signal,n,e.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.url}routing/v1/peers/${t}`);this.#r(a,e.filterAddrs,e.filterProtocols);let c=await this.#e(a.toString(),{headers:{Accept:"application/x-ndjson"},signal:o});if(c.status===404)return;if(c.status===422)throw new Et("Request does not conform to schema or semantic constraints");if(c.body==null)throw new M("Routing response had no body");if(c.headers.get("Content-Type")?.startsWith("application/json")){let h=(await c.json()).Peers??[];for(let u of h){let p=this.#t(u);p!=null&&(yield p)}}else for await(let f of jt(le(c.body))){let h=this.#t(f);h!=null&&(yield h)}}catch(a){this.log.error("getPeers errored - %e",a)}finally{o.clear(),i.resolve(),this.log("getPeers finished: %c",t)}}async*getClosestPeers(t,e={}){let n;if(T.asCID(t)===t||t instanceof T)n=t.toV1().toString();else throw new _t("Key must be CID");this.log("getClosestPeers starts: %s",n);let o=AbortSignal.timeout(this.timeout),s=Vt([this.shutDownController.signal,o,e.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));try{await i.promise;let c=new URL(`${this.url}routing/v1/dht/closest/peers/${n}`);this.#r(c,e.filterAddrs,e.filterProtocols);let l=await this.#e(c.toString(),{headers:{Accept:"application/x-ndjson"},signal:s});if(l.status===404)return;if(l.status===422)throw new Et("Request does not conform to schema or semantic constraints");if(l.body==null)throw new M("Routing response had no body");if(l.headers.get("Content-Type")?.startsWith("application/json")){let u=(await l.json()).Peers??[];for(let p of u){let S=this.#t(p);S!=null&&(yield S)}}else for await(let h of jt(le(l.body))){let u=this.#t(h);u!=null&&(yield u)}}catch(c){this.log.error("getClosestPeers errored - %e",c)}finally{s.clear(),a.resolve(),this.log("getClosestPeers finished: %s",n)}}async getIPNS(t,e={}){this.log("getIPNS starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Vt([this.shutDownController.signal,n,e.signal]);let s=Promise.withResolvers(),i=Promise.withResolvers();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.url}routing/v1/ipns/${t}`;try{await s.promise;let c=await this.#e(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(this.log("getIPNS GET %s %d",a,c.status),c.status===404)throw new et("No matching records found");if(c.status===422)throw new Et("Request does not conform to schema or semantic constraints");if(!c.ok)throw new M(`Unexpected status code: ${c.status}`);let l=c.headers.get("Content-Type");if(l==null||!l.includes("application/vnd.ipfs.ipns-record"))throw new et("No matching records found");if(c.body==null)throw new M("GET ipns response had no body");let f=await c.arrayBuffer();return new Uint8Array(f,0,f.byteLength)}catch(c){throw this.log.error("getIPNS GET %s error - %e",a,c),c}finally{o.clear(),i.resolve(),this.log("getIPNS finished: %c",t)}}async putIPNS(t,e,n={}){this.log("putIPNS starts: %c",t);let o=AbortSignal.timeout(this.timeout),s=Vt([this.shutDownController.signal,o,n.signal]);let i=Promise.withResolvers(),a=Promise.withResolvers();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.url}routing/v1/ipns/${t}`;try{await i.promise;let l=await this.#e(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:ee(e),signal:s});if(this.log("putIPNS PUT %s %d",c,l.status),l.status!==200)throw new M("PUT ipns response had status other than 200")}catch(l){throw this.log.error("putIPNS PUT %s error - %e",c,l.stack),l}finally{s.clear(),a.resolve(),this.log("putIPNS finished: %c",t)}}#t(t){try{let e=[],n=t.Addrs?.map(Bt)??[];return t.Protocols!=null&&e.push(...t.Protocols),t.Protocol!=null&&(e.push(t.Protocol),delete t.Protocol),{...t,Schema:"peer",ID:T.createV1(114,La(t.ID)),Addrs:n,Protocols:e}}catch(e){this.log.error("could not conform record to peer schema - %e",e)}}#r(t,e,n){if(e!=null||this.filterAddrs!=null){let o=e?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&t.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&t.searchParams.set("filter-protocols",o)}}async#e(t,e){let n=e.method??"GET",o=`${n}-${t}`;if(n==="GET"){let c=await this.cache?.match(t);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return this.log("returning cached response for %s",o),this.logResponse(c),c;this.log("evicting cached response for %s",o),await this.cache?.delete(t)}else this.cache!=null&&this.log("cache miss for %s",o)}let s=this.inFlightRequests.get(o);if(s!=null){let c=await s;return this.log("deduplicating outgoing request for %s",o),c.clone()}this.log("outgoing request:"),this.logRequest(t,e);let i=fetch(t,e).then(async c=>{if(this.log("incoming response:"),this.logResponse(c),this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,f=new Headers(c.headers);f.set("x-cache-expires",l.toString());let h=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:f});await this.cache.put(t,h)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}toString(){return`DefaultDelegatedRoutingV1HttpApiClient(${this.url})`}logRequest(t,e){let n=new Headers(e.headers);this.log("%s %s HTTP/1.1",e.method??"GET",t);for(let[o,s]of n.entries())this.log("%s: %s",o,s)}logResponse(t){this.log("HTTP/1.1 %d %s",t.status,t.statusText);for(let[e,n]of t.headers.entries())this.log("%s: %s",e,n)}};function La(r){let t=z.baseDecode(r);return mt(t)}function ka(r){return r[Symbol.asyncIterator]!=null}function Na(r){if(ka(r))return(async()=>{for await(let t of r)return t})();for(let t of r)return t}var ko=Na;function Ra(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var No=Ra;function Fa(r){return r[Symbol.asyncIterator]!=null}function Oa(r,t){let e=0;if(Fa(r))return(async function*(){for await(let c of r)yield t(c,e++)})();let n=No(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=t(o,e++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield t(c,e++)})();let a=t;return(function*(){yield i;for(let c of n)yield a(c,e++)})()}var Ro=Oa;function Fo(r){return t=>new Ve(t,r)}var je=I("/ipns/");function Oo(r){return nt(r.subarray(0,je.byteLength),je)}var He=class{name="delegated-http-router";client;constructor(t,e){this.client=Fo(e)(t)}async provide(t,e){}async cancelReprovide(t,e){}async*findProviders(t,e){yield*Ro(this.client.getProviders(t,e),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols,routing:"delegated-http-routing"}))}async put(t,e,n){if(!Oo(t))return;let o=mt(t.slice(je.length)),s=T.createV1(114,o);await this.client.putIPNS(s,e,n)}async get(t,e){if(!Oo(t))throw new et("Not found");let n=mt(t.slice(je.length)),o=T.createV1(114,n);try{return await this.client.getIPNS(o,e)}catch(s){throw s.name==="BadResponseError"?new et("Not found"):s}}async findPeer(t,e){let n=await ko(this.client.getPeers(t,e));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new et("Not found")}async*getClosestPeers(t,e){}toString(){return`DelegatedHTTPRouter(${this.client.url})`}};function Uo(r){return{url:"https://delegated-ipfs.dev",filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}function $o(r){return t=>new He(t,Uo(r))}var Bo="[a-fA-F\\d:]",dt=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Bo})|(?<=${Bo})(?=\\s|$))`:"",W="(?: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}",P="[a-fA-F\\d]{1,4}",We=`
13
3
  (?:
14
- (?:${D}:){7}(?:${D}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
15
- (?:${D}:){6}(?:${J}|:${D}|:)| // 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
16
- (?:${D}:){5}(?::${J}|(?::${D}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
17
- (?:${D}:){4}(?:(?::${D}){0,1}:${J}|(?::${D}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
18
- (?:${D}:){3}(?:(?::${D}){0,2}:${J}|(?::${D}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
19
- (?:${D}:){2}(?:(?::${D}){0,3}:${J}|(?::${D}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
20
- (?:${D}:){1}(?:(?::${D}){0,4}:${J}|(?::${D}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
21
- (?::(?:(?::${D}){0,5}:${J}|(?::${D}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
4
+ (?:${P}:){7}(?:${P}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
5
+ (?:${P}:){6}(?:${W}|:${P}|:)| // 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
6
+ (?:${P}:){5}(?::${W}|(?::${P}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
7
+ (?:${P}:){4}(?:(?::${P}){0,1}:${W}|(?::${P}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
8
+ (?:${P}:){3}(?:(?::${P}){0,2}:${W}|(?::${P}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
9
+ (?:${P}:){2}(?:(?::${P}){0,3}:${W}|(?::${P}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
10
+ (?:${P}:){1}(?:(?::${P}){0,4}:${W}|(?::${P}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
11
+ (?::(?:(?::${P}){0,5}:${W}|(?::${P}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
22
12
  )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
23
- `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),bc=new RegExp(`(?:^${J}$)|(?:^${rr}$)`),xc=new RegExp(`^${J}$`),vc=new RegExp(`^${rr}$`),An=r=>r&&r.exact?bc:new RegExp(`(?:${pt(r)}${J}${pt(r)})|(?:${pt(r)}${rr}${pt(r)})`,"g");An.v4=r=>r&&r.exact?xc:new RegExp(`${pt(r)}${J}${pt(r)}`,"g");An.v6=r=>r&&r.exact?vc:new RegExp(`${pt(r)}${rr}${pt(r)}`,"g");var Pn=An;function Tn(r){let t=(...e)=>r(...e);return Object.defineProperty(t,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),t}function os(){return!1}var{toString:Ec}=Object.prototype;function Dn(r){return Ec.call(r)==="[object RegExp]"}var ss={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function kn(r,t={}){if(!Dn(r))throw new TypeError("Expected a RegExp instance");let e=Object.keys(ss).map(o=>(typeof t[o]=="boolean"?t[o]:r[o])?ss[o]:"").join(""),n=new RegExp(t.source||r.source,e);return n.lastIndex=typeof t.lastIndex=="number"?t.lastIndex:r.lastIndex,n}function Fn(r,t,{timeout:e}={}){try{return Tn(()=>kn(r).test(t),{timeout:e})()}catch(n){if(os(n))return!1;throw n}}var _c=15,Cc=45,is={timeout:400};function Ln(r){return r.length>Cc?!1:Fn(Pn.v6({exact:!0}),r,is)}function as(r){return r.length>_c?!1:Fn(Pn.v4({exact:!0}),r,is)}var cs={http:"80",https:"443",ws:"80",wss:"443"},Sc=["http","https","ws","wss"];function nr(r,t){t=t??{};let e=t.defaultDnsType??"dns",{scheme:n,hostname:o,port:s,path:i}=Ic(r),a=[Ac(o,e),Pc(s,n),Tc(n)];i!=null&&a.push(Dc(i));let c="/"+a.filter(f=>!!f).reduce((f,l)=>f.concat(l),[]).join("/");return Vt(c)}function Ic(r){let[t]=r.split(":");Sc.includes(t)||(r="http"+r.substring(t.length));let{protocol:e,hostname:n,port:o,pathname:s,search:i}=new URL(r);if(o==null||o===""){let c=kc(t);c!=null&&(o=c),c==null&&e==="http:"&&(o="80")}let a;return s!=null&&s!==""&&s!=="/"&&(s.startsWith("/")&&(s=s.substring(1)),a=s),i!=null&&i!==""&&(a=a??"",a+=i),{scheme:t,hostname:n,port:o,path:a}}function Ac(r,t){if(!(r==null||r==="")){if(as(r))return["ip4",r];if(Ln(r))return["ip6",r];if(r[0]==="["){let e=r.substring(1,r.length-1);if(Ln(e))return["ip6",e]}return[t,r]}}function Pc(r,t){if(!(r==null||r===""))return t==="udp"?["udp",r]:["tcp",r]}function Tc(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function Dc(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function kc(r){if(!(r==null||r===""||cs[r]==null))return cs[r]}var Fc=["https://trustless-gateway.link","https://4everland.io"],Lc=2336;function Nc(r){return r=r.toString(),{id:T.createV1(Lc,Zt.digest(C(r))),multiaddrs:[nr(r)]}}function Rc(r){return new URL(V(r.id.multihash.digest))}var Nn=class{name="fallback-router";gateways;shuffle;constructor(t={}){this.gateways=(t.gateways??Fc).map(e=>Nc(e)),this.shuffle=t.shuffle??!0}async*findProviders(t,e){yield*(this.shuffle?this.gateways.toSorted(()=>Math.random()>.5?1:-1):this.gateways).map(n=>({...n,id:n.id,protocols:["transport-ipfs-gateway-http"],routing:"http-gateway-routing"}))}toString(){return`HTTPGatewayRouter([${this.gateways.map(t=>Rc(t)).join(", ")}])`}};function ls(r={}){return new Nn(r)}var ct="/",us=new TextEncoder().encode(ct),or=us[0],mt=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=C(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(e==null&&(e=!0),e&&this.clean(),this._buf.byteLength===0||this._buf[0]!==or)throw new Error("Invalid key")}toString(t="utf8"){return V(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(ct))}static random(){return new r(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new r(t):typeof t.uint8Array=="function"?new r(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=us),this._buf[0]!==or){let t=new Uint8Array(this._buf.byteLength+1);t.fill(or,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===or;)this._buf=this._buf.subarray(0,-1)}less(t){let e=this.list(),n=t.list();for(let o=0;o<e.length;o++){if(n.length<o+1)return!1;let s=e[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return e.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(ct).slice(1)}type(){return Oc(this.baseNamespace())}name(){return $c(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(ct)||(t+=ct),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(ct):new r(t.slice(0,-1).join(ct))}child(t){return this.toString()===ct?t:t.toString()===ct?this:new r(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()===this.toString()?!1:t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()===this.toString()?!1:this.toString().startsWith(t.toString())}isTopLevel(){return this.list().length===1}concat(...t){return r.withNamespaces([...this.namespaces(),...Uc(t.map(e=>e.namespaces()))])}};function Oc(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function $c(r){let t=r.split(":");return t[t.length-1]}function Uc(r){return[].concat(...r)}var M=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var zc=Mn(hs(),1);var Kt;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(Kt||(Kt={}));var km=de("blockstore:core:tiered");var ps="SHARDING";var pg=new mt(ps);var Pg=de("datastore:core:tiered");var sr=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var ye=class extends At{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(t,e){super(),this.logName=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.cidPeerFilterSize=e.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=Ce(this.maxProviders),this.initialProviders=[...e.providers??[]]}async retrieve(t,e={}){let n=wt.encode(t.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",t),o.observers++,o.promise;let s=at(),i={promise:s.promise,observers:1,queryFilter:Ce(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e));let c=!1,f=new Ht({concurrency:this.maxProviders});f.addEventListener("failure",u=>{this.log.error("error querying provider %s, evicting from session - %e",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),f.addEventListener("success",u=>{c=!0,s.resolve(u.detail.result)}),f.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(e.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let p=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(p)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),s.resolve(await this.retrieve(t,e))}).catch(u=>{this.log.error("could not find new providers for %c - %e",t,u),s.reject(u)})});let l=u=>{let p=this.toFilterKey(u.detail);i.queryFilter.has(p)||(i.queryFilter.add(p),this.emitFoundProviderProgressEvent(t,u.detail,e),f.add(async()=>this.queryProvider(t,u.detail,e),{provider:u.detail}).catch(m=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,m)}))};if(this.addEventListener("provider",l),a)try{await he(this.initialPeerSearchComplete,e.signal),a&&this.log("found initial session peers for %c",t)}catch(u){throw a&&this.log("failed to find initial session peers for %c - %e",t,u),this.requests.delete(n),i.observers>1&&s.reject(u),u}Promise.all([...this.providers].filter(u=>{let p=this.toFilterKey(u),m=i.queryFilter.has(p);return m||i.queryFilter.add(this.toFilterKey(u)),!m}).map(async u=>f.add(async()=>this.queryProvider(t,u,e),{provider:u}))).catch(u=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,u)});let h=()=>{s.reject(new W(e.signal?.reason??"Session aborted")),f.abort()};e.signal?.addEventListener("abort",h);try{return await s.promise}finally{this.removeEventListener("provider",l),e.signal?.removeEventListener("abort",h),f.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toFilterKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toFilterKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async addPeer(t,e){let n=await this.convertToProvider(t,"manually-added",e);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(t,e,n){let o=at(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",e,this.maxProviders,t,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let f=i.initialProviders.pop();if(f==null)continue;let l=await i.convertToProvider(f,"manual",n);l!=null&&(yield l)}},c=async function*(){yield*a(),yield*i.findNewProviders(t,n)};for await(let f of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(f)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(f),this.safeDispatchEvent("provider",{detail:f}),s++,this.providers.length===e&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,e,this.providers.length),this.providers.length<e)throw new sr(`Found ${s} of ${e} ${this.name} providers for ${t}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",t,i),o.reject(i)}),o.promise}};function On(r){return r==null?!1:T.asCID(r)!=null}var Yc=[6,53,56,54,55];function gs(r){return bs("sni",r)?.value}function ys(r){let t=bs("tcp",r)?.value;return t==null?"":`:${t}`}function bs(r,t){return t.find(e=>e.name===r)}function ws(r){return r.some(({code:t})=>t===448)}function X(r,t){let e=xs[r.name];if(e==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=e(r,t);return r.code===41?`[${n}]`:n}var xs={ip4:(r,t)=>r.value,ip6:(r,t)=>t.length===0?r.value:`[${r.value}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${X(e,t)}:${r.value}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${X(e,t)}:${r.value}`},dnsaddr:(r,t)=>r.value,dns4:(r,t)=>r.value,dns6:(r,t)=>r.value,dns:(r,t)=>r.value,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${X(e,t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${X(e,t)}`},http:(r,t)=>{let e=ws(t),n=gs(t),o=ys(t);if(e&&n!=null)return`https://${n}${o}`;let s=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=X(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=X(e,t),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return X(e,t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return X(e,t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=X(e,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=ws(t),n=gs(t),o=ys(t);if(e&&n!=null)return`wss://${n}${o}`;let s=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=X(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=X(e,t);return n=n?.replace("tcp://",""),`wss://${n}`}};function ir(r,t){let n=Vt(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=xs[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return t?.assumeHttp!==!1&&Yc.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}function $n(r,t,e){return r.filter(n=>{let o=Ho.exactMatch(n),s=jo.exactMatch(n);if(!o&&!s)return!1;if(o||t&&s)return e||$o.matches(n)?!0:Eo(n)===!1;if(!t&&e){let{host:i}=Se(n);if(i==="127.0.0.1"||i==="localhost"||i.endsWith(".localhost"))return!0}return!1})}async function*ar(r,t,e,n,o,s={}){for await(let i of t.findProviders(r,s)){let a=$n(i.multiaddrs,n,o);if(a.length===0)continue;let c=new URL(ir(a[0]));yield new Qt(c,{logger:e,transformRequestInit:s.transformRequestInit,routing:i.routing})}}async function vs(r,t,e){let{signal:n,log:o}=e??{},s=r.headers.get("content-length");if(s!=null){let c=parseInt(s,10);if(c>t)throw o?.error("content-length header (%d) is greater than the limit (%d)",c,t),r.body!=null&&await r.body.cancel().catch(f=>{o?.error("error cancelling response body after content-length check - %e",f)}),new Error(`Content-Length header (${c}) is greater than the limit (${t}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new xe;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:f}=await i.read();if(c)break;if(a.append(f),a.byteLength>t)throw new Error(`Response body is greater than the limit (${t}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var Zc=2336,Qt=class{url;peer;#t=0;#r=0;#e=0;#o=0;#n=new Map;log;transformRequestInit;routing;constructor(t,{logger:e,transformRequestInit:n,routing:o}){this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=n,this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.host}`),this.routing=o,this.peer=T.createV1(Zc,Zt.digest(C(this.url.toString())))}#s(t){let e=t.multihash.bytes;return wt.encode(e)}async getRawBlock(t,e={}){let n=new URL(this.url.toString());n.pathname=`/ipfs/${t.toString()}`;let o=e.maxSize??Es;if(n.search="?format=raw",e.signal?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let s=this.#s(t),i=new AbortController,a=()=>{i.abort()};e.signal?.addEventListener("abort",a);try{let c=this.#n.get(s);if(c==null){this.#t++;let f={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},l=this.transformRequestInit!=null?await this.transformRequestInit(f):f,h=new Headers(l.headers);this.log(`sending request
13
+ `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),Ua=new RegExp(`(?:^${W}$)|(?:^${We}$)`),$a=new RegExp(`^${W}$`),Ba=new RegExp(`^${We}$`),mn=r=>r&&r.exact?Ua:new RegExp(`(?:${dt(r)}${W}${dt(r)})|(?:${dt(r)}${We}${dt(r)})`,"g");mn.v4=r=>r&&r.exact?$a:new RegExp(`${dt(r)}${W}${dt(r)}`,"g");mn.v6=r=>r&&r.exact?Ba:new RegExp(`${dt(r)}${We}${dt(r)}`,"g");var gn=mn;function wn(r){let t=(...e)=>r(...e);return Object.defineProperty(t,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),t}function zo(){return!1}var{toString:za}=Object.prototype;function bn(r){return za.call(r)==="[object RegExp]"}var Mo={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function yn(r,t={}){if(!bn(r))throw new TypeError("Expected a RegExp instance");let e=Object.keys(Mo).map(o=>(typeof t[o]=="boolean"?t[o]:r[o])?Mo[o]:"").join(""),n=new RegExp(t.source||r.source,e);return n.lastIndex=typeof t.lastIndex=="number"?t.lastIndex:r.lastIndex,n}function xn(r,t,{timeout:e}={}){try{return wn(()=>yn(r).test(t),{timeout:e})()}catch(n){if(zo(n))return!1;throw n}}var Ma=15,qa=45,qo={timeout:400};function vn(r){return r.length>qa?!1:xn(gn.v6({exact:!0}),r,qo)}function Vo(r){return r.length>Ma?!1:xn(gn.v4({exact:!0}),r,qo)}var jo={http:"80",https:"443",ws:"80",wss:"443"},Va=["http","https","ws","wss"];function Ge(r,t){t=t??{};let e=t.defaultDnsType??"dns",{scheme:n,hostname:o,port:s,path:i}=ja(r),a=[Ha(o,e),Wa(s,n),Ga(n)];i!=null&&a.push(Qa(i));let c="/"+a.filter(l=>!!l).reduce((l,f)=>l.concat(f),[]).join("/");return Bt(c)}function ja(r){let[t]=r.split(":");Va.includes(t)||(r="http"+r.substring(t.length));let{protocol:e,hostname:n,port:o,pathname:s,search:i}=new URL(r);if(o==null||o===""){let c=Xa(t);c!=null&&(o=c),c==null&&e==="http:"&&(o="80")}let a;return s!=null&&s!==""&&s!=="/"&&(s.startsWith("/")&&(s=s.substring(1)),a=s),i!=null&&i!==""&&(a=a??"",a+=i),{scheme:t,hostname:n,port:o,path:a}}function Ha(r,t){if(!(r==null||r==="")){if(Vo(r))return["ip4",r];if(vn(r))return["ip6",r];if(r[0]==="["){let e=r.substring(1,r.length-1);if(vn(e))return["ip6",e]}return[t,r]}}function Wa(r,t){if(!(r==null||r===""))return t==="udp"?["udp",r]:["tcp",r]}function Ga(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function Qa(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function Xa(r){if(!(r==null||r===""||jo[r]==null))return jo[r]}var Ka=["https://trustless-gateway.link","https://4everland.io"],Ja=2336;function Ya(r){return r=r.toString(),{id:T.createV1(Ja,Kt.digest(I(r))),multiaddrs:[Ge(r)]}}function Za(r){return new URL(Z(r.id.multihash.digest))}var En=class{name="fallback-router";gateways;shuffle;constructor(t={}){this.gateways=(t.gateways??Ka).map(e=>Ya(e)),this.shuffle=t.shuffle??!0}async*findProviders(t,e){yield*(this.shuffle?this.gateways.toSorted(()=>Math.random()>.5?1:-1):this.gateways).map(n=>({...n,id:n.id,protocols:["transport-ipfs-gateway-http"],routing:"http-gateway-routing"}))}toString(){return`HTTPGatewayRouter([${this.gateways.map(t=>Za(t)).join(", ")}])`}};function Ho(r={}){return new En(r)}var Qe=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}};var Xe=class extends It{initialPeerSearchComplete;requests;logName;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;cidPeerFilterSize;constructor(t,e){super(),this.logName=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.logName),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.cidPeerFilterSize=e.cidPeerFilterSize??100,this.providers=[],this.evictionFilter=ge(this.maxProviders),this.initialProviders=[...e.providers??[]]}async retrieve(t,e={}){let n=Gt.encode(t.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",t),o.observers++,o.promise;let s=at(),i={promise:s.promise,observers:1,queryFilter:ge(this.cidPeerFilterSize)};this.requests.set(n,i);let a=!1;this.initialPeerSearchComplete==null&&(a=!0,this.log=this.logger.forComponent(`${this.logName}:${t}`),this.initialPeerSearchComplete=this.findProviders(t,this.minProviders,e));let c=!1,l=new qt({concurrency:this.maxProviders});l.addEventListener("failure",u=>{this.log.error("error querying provider %s, evicting from session - %e",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),l.addEventListener("success",u=>{c=!0,s.resolve(u.detail.result)}),l.addEventListener("idle",()=>{if(c){this.log.trace("session idle, found block");return}if(e.signal?.aborted===!0){this.log.trace("session idle, signal aborted");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let p=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(p)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),s.resolve(await this.retrieve(t,e))}).catch(u=>{this.log.error("could not find new providers for %c - %e",t,u),s.reject(u)})});let f=u=>{let p=this.toFilterKey(u.detail);i.queryFilter.has(p)||(i.queryFilter.add(p),this.emitFoundProviderProgressEvent(t,u.detail,e),l.add(async()=>this.queryProvider(t,u.detail,e),{provider:u.detail}).catch(S=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,S)}))};if(this.addEventListener("provider",f),a)try{await $e(this.initialPeerSearchComplete,e.signal),a&&this.log("found initial session peers for %c",t)}catch(u){throw a&&this.log("failed to find initial session peers for %c - %e",t,u),this.requests.delete(n),i.observers>1&&s.reject(u),u}Promise.all([...this.providers].filter(u=>{let p=this.toFilterKey(u),S=i.queryFilter.has(p);return S||i.queryFilter.add(this.toFilterKey(u)),!S}).map(async u=>l.add(async()=>this.queryProvider(t,u,e),{provider:u}))).catch(u=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c - %e",t,u)});let h=()=>{s.reject(new V(e.signal?.reason??"Session aborted")),l.abort()};e.signal?.addEventListener("abort",h);try{return await s.promise}finally{this.removeEventListener("provider",f),e.signal?.removeEventListener("abort",h),l.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toFilterKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toFilterKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async addPeer(t,e){let n=await this.convertToProvider(t,"manually-added",e);n==null||this.hasProvider(n)||(this.providers.push(n),this.safeDispatchEvent("provider",{detail:n}))}async findProviders(t,e,n){let o=at(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c - %d initial providers",e,this.maxProviders,t,this.initialProviders.length);let i=this,a=async function*(){for(;i.initialProviders.length>0;){let l=i.initialProviders.pop();if(l==null)continue;let f=await i.convertToProvider(l,"manual",n);f!=null&&(yield f)}},c=async function*(){yield*a(),yield*i.findNewProviders(t,n)};for await(let l of c()){if(this.providers.length===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(l)&&(this.log("found %d providers, %d in session",s,this.providers.length),this.providers.push(l),this.safeDispatchEvent("provider",{detail:l}),s++,this.providers.length===e&&(this.log("session is ready with %d peer(s), new peers present",this.providers.length),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers %d",this.providers.length);break}}if(this.log("found %d new session peers while trying to find %d, %d in session",s,e,this.providers.length),this.providers.length<e)throw new Qe(`Found ${s} of ${e} ${this.name} providers for ${t}, ${this.providers.length} in session after evictions`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c - %e",t,i),o.reject(i)}),o.promise}};function Wo(r){return r==null?!1:T.asCID(r)!=null}var nc=[6,53,56,54,55];function Go(r){return Ko("sni",r)?.value}function Qo(r){let t=Ko("tcp",r)?.value;return t==null?"":`:${t}`}function Ko(r,t){return t.find(e=>e.name===r)}function Xo(r){return r.some(({code:t})=>t===448)}function G(r,t){let e=Jo[r.name];if(e==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=e(r,t);return r.code===41?`[${n}]`:n}var Jo={ip4:(r,t)=>r.value,ip6:(r,t)=>t.length===0?r.value:`[${r.value}]`,tcp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`tcp://${G(e,t)}:${r.value}`},udp:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`udp://${G(e,t)}:${r.value}`},dnsaddr:(r,t)=>r.value,dns4:(r,t)=>r.value,dns6:(r,t)=>r.value,dns:(r,t)=>r.value,ipfs:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${G(e,t)}`},p2p:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return`${G(e,t)}`},http:(r,t)=>{let e=Xo(t),n=Go(t),o=Qo(t);if(e&&n!=null)return`https://${n}${o}`;let s=e?"https://":"http://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=G(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=G(e,t),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return G(e,t)},sni:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");return G(e,t)},https:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=G(e,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=Xo(t),n=Go(t),o=Qo(t);if(e&&n!=null)return`wss://${n}${o}`;let s=e?"wss://":"ws://",i=t.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=G(i,t);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,t)=>{let e=t.pop();if(e==null)throw new Error("Unexpected end of multiaddr");let n=G(e,t);return n=n?.replace("tcp://",""),`wss://${n}`}};function Ke(r,t){let n=Bt(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=Jo[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return t?.assumeHttp!==!1&&nc.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var Q=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};function _n(r,t,e){return r.filter(n=>{let o=Ao.exactMatch(n),s=To.exactMatch(n);if(!o&&!s)return!1;if(o||t&&s)return e||vo.matches(n)?!0:so(n)===!1;if(!t&&e){let{host:i}=we(n);if(i==="127.0.0.1"||i==="localhost"||i.endsWith(".localhost"))return!0}return!1})}async function*Je(r,t,e,n,o,s={}){for await(let i of t.findProviders(r,s)){let a=_n(i.multiaddrs,n,o);if(a.length===0)continue;let c=new URL(Ke(a[0]));yield new Ht(c,{logger:e,transformRequestInit:s.transformRequestInit,routing:i.routing})}}async function Yo(r,t,e){let{signal:n,log:o}=e??{},s=r.headers.get("content-length");if(s!=null){let c=parseInt(s,10);if(c>t)throw o?.error("content-length header (%d) is greater than the limit (%d)",c,t),r.body!=null&&await r.body.cancel().catch(l=>{o?.error("error cancelling response body after content-length check - %e",l)}),new Error(`Content-Length header (${c}) is greater than the limit (${t}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new he;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await i.read();if(c)break;if(a.append(l),a.byteLength>t)throw new Error(`Response body is greater than the limit (${t}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var oc=2336,Ht=class{url;peer;#t=0;#r=0;#e=0;#o=0;#n=new Map;log;transformRequestInit;routing;constructor(t,{logger:e,transformRequestInit:n,routing:o}){this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=n,this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.host}`),this.routing=o,this.peer=T.createV1(oc,Kt.digest(I(this.url.toString())))}#s(t){let e=t.multihash.bytes;return Gt.encode(e)}async getRawBlock(t,e={}){let n=new URL(this.url.toString());n.pathname=`/ipfs/${t.toString()}`;let o=e.maxSize??Zo;if(n.search="?format=raw",e.signal?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let s=this.#s(t),i=new AbortController,a=()=>{i.abort()};e.signal?.addEventListener("abort",a);try{let c=this.#n.get(s);if(c==null){this.#t++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},f=this.transformRequestInit!=null?await this.transformRequestInit(l):l,h=new Headers(f.headers);this.log(`sending request
24
14
  %s %s HTTP/1.1
25
15
  %s
26
- `,l.method??"GET",n,[...h.entries()].map(([u,p])=>`${u}: ${p}`).join(`
27
- `)),e.onProgress?.(new M("helia:block-broker:connect",{broker:"trustless-gateway",type:"connect",provider:this.peer,cid:t})),c=fetch(n.toString(),l).then(async u=>{if(this.log(`received response
16
+ `,f.method??"GET",n,[...h.entries()].map(([u,p])=>`${u}: ${p}`).join(`
17
+ `)),e.onProgress?.(new Q("helia:block-broker:connect",{broker:"trustless-gateway",type:"connect",provider:this.peer,cid:t})),c=fetch(n.toString(),f).then(async u=>{if(this.log(`received response
28
18
  HTTP/1.1 %d %s
29
19
  %s
30
- `,u.status,u.statusText,[...u.headers.entries()].map(([m,x])=>`${m}: ${x}`).join(`
31
- `)),!u.ok)throw this.#r++,new Error(`Unable to fetch raw block for CID ${t} from gateway ${this.url}, received ${u.status} ${u.statusText}`);e.onProgress?.(new M("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:nr(n.toString()),cid:t})),e.onProgress?.(new M("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:t}));let p=await vs(u,o,{signal:i.signal,log:this.log});return e.onProgress?.(new M("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:t})),this.#o++,p}),this.#n.set(s,c)}return await c}catch(c){throw e.signal?.aborted===!0?new Error(`Fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#r++,new Error(`Unable to fetch raw block for CID ${t} - ${c.message}`))}finally{e.signal?.removeEventListener("abort",a),this.#n.delete(s)}}reliability(){return this.#t===0?1:this.#e>0?-1/0:this.#o/(this.#t+this.#r*3)}incrementInvalidBlocks(){this.#e++}getStats(){return{attempts:this.#t,errors:this.#r,invalidBlocks:this.#e,successes:this.#o,pendingResponses:this.#n.size}}toString(){return`TrustlessGateway(${this.url})`}};var Un=class extends ye{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??cr,this.allowLocal=e.allowLocal??lr,this.transformRequestInit=e.transformRequestInit}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url),n?.onProgress?.(new M("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}));let o;try{o=await e.getRawBlock(t,n),this.log.trace("got block for %c from %s",t,e.url)}finally{n?.onProgress?.(new M("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}))}return await n.validateFn?.(o),o}async*findNewProviders(t,e={}){yield*ar(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})}toFilterKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}async convertToProvider(t,e,n){if(n?.signal?.throwIfAborted(),On(t))return;let o=$n(Array.isArray(t)?t:[t],this.allowInsecure,this.allowLocal);if(o.length===0)return;let s=ir(o[0]);return new Qt(s,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:e})}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new M("trustless-gateway:found-provider",{type:"trustless-gateway",cid:t,url:e.url.toJSON(),routing:e.routing}))}};function _s(r,t){return new Un(r,t)}var ur=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??cr,this.allowLocal=e.allowLocal??lr,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let o of ar(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",t,o.url);try{let s=await o.getRawBlock(t,e);this.log.trace("got block for %c from %s",t,o.url);try{await e.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s - %e",t,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s - %e",t,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${o.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return _s({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var cr=!1,lr=!1,Es=2097152;function Cs(r={}){return t=>new ur(t,r)}function tl(r,t){return t?.routers??[ls(),rs({url:"https://delegated-ipfs.dev"})].forEach(e=>{r.addRouter(e)}),t?.blockBrokers??[Cs()].forEach(e=>{r.addBlockBroker(e)}),r}return ks(el);})();
20
+ `,u.status,u.statusText,[...u.headers.entries()].map(([S,R])=>`${S}: ${R}`).join(`
21
+ `)),!u.ok)throw this.#r++,new Error(`Unable to fetch raw block for CID ${t} from gateway ${this.url}, received ${u.status} ${u.statusText}`);e.onProgress?.(new Q("helia:block-broker:connected",{broker:"trustless-gateway",type:"connected",provider:this.peer,address:Ge(n.toString()),cid:t})),e.onProgress?.(new Q("helia:block-broker:request-block",{broker:"trustless-gateway",type:"request-block",provider:this.peer,cid:t}));let p=await Yo(u,o,{signal:i.signal,log:this.log});return e.onProgress?.(new Q("helia:block-broker:receive-block",{broker:"trustless-gateway",type:"receive-block",provider:this.peer,cid:t})),this.#o++,p}),this.#n.set(s,c)}return await c}catch(c){throw e.signal?.aborted===!0?new Error(`Fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#r++,new Error(`Unable to fetch raw block for CID ${t} - ${c.message}`))}finally{e.signal?.removeEventListener("abort",a),this.#n.delete(s)}}reliability(){return this.#t===0?1:this.#e>0?-1/0:this.#o/(this.#t+this.#r*3)}incrementInvalidBlocks(){this.#e++}getStats(){return{attempts:this.#t,errors:this.#r,invalidBlocks:this.#e,successes:this.#o,pendingResponses:this.#n.size}}toString(){return`TrustlessGateway(${this.url})`}};var In=class extends Xe{name="trustless-gateway-session";routing;allowInsecure;allowLocal;transformRequestInit;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??Ye,this.allowLocal=e.allowLocal??Ze,this.transformRequestInit=e.transformRequestInit}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url),n?.onProgress?.(new Q("helia:block-brokers:query-provider:start",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}));let o;try{o=await e.getRawBlock(t,n),this.log.trace("got block for %c from %s",t,e.url)}finally{n?.onProgress?.(new Q("helia:block-brokers:query-provider:end",{blockBroker:"trustless-gateway",provider:e.url,transport:"http",cid:t}))}return await n.validateFn?.(o),o}async*findNewProviders(t,e={}){yield*Je(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})}toFilterKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}async convertToProvider(t,e,n){if(n?.signal?.throwIfAborted(),Wo(t))return;let o=_n(Array.isArray(t)?t:[t],this.allowInsecure,this.allowLocal);if(o.length===0)return;let s=Ke(o[0]);return new Ht(s,{logger:this.logger,transformRequestInit:this.transformRequestInit,routing:e})}emitFoundProviderProgressEvent(t,e,n){n?.onProgress?.(new Q("trustless-gateway:found-provider",{type:"trustless-gateway",cid:t,url:e.url.toJSON(),routing:e.routing}))}};function ts(r,t){return new In(r,t)}var tr=class{name="trustless-gateway";allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??Ye,this.allowLocal=e.allowLocal??Ze,this.transformRequestInit=e.transformRequestInit}async retrieve(t,e={}){let n=[];for await(let o of Je(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...e,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",t,o.url);try{let s=await o.getRawBlock(t,e);this.log.trace("got block for %c from %s",t,o.url);try{await e.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s - %e",t,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s - %e",t,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${o.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return ts({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Ye=!1,Ze=!1,Zo=2097152;function es(r={}){return t=>new tr(t,r)}function sc(r,t){return t?.routers??[Ho(),$o({url:"https://delegated-ipfs.dev"})].forEach(e=>{r.addRouter(e)}),t?.blockBrokers??[es()].forEach(e=>{r.addBlockBroker(e)}),r}return cs(ic);})();
32
22
  return HeliaHttp}));
33
23
  //# sourceMappingURL=index.min.js.map