@helia/http 2.2.1 → 3.0.0

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,40 +1,37 @@
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 q1=Object.create;var Ua=Object.defineProperty;var z1=Object.getOwnPropertyDescriptor;var G1=Object.getOwnPropertyNames;var W1=Object.getPrototypeOf,j1=Object.prototype.hasOwnProperty;var Tt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ee=(r,e)=>{for(var t in e)Ua(r,t,{get:e[t],enumerable:!0})},Cg=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of G1(e))!j1.call(r,o)&&o!==t&&Ua(r,o,{get:()=>e[o],enumerable:!(n=z1(e,o))||n.enumerable});return r};var nn=(r,e,t)=>(t=r!=null?q1(W1(r)):{},Cg(e||!r||!r.__esModule?Ua(t,"default",{value:r,enumerable:!0}):t,r)),Y1=r=>Cg(Ua({},"__esModule",{value:!0}),r);var J0=Tt((tL,rp)=>{"use strict";var vS=Object.prototype.hasOwnProperty,it="~";function Mi(){}Object.create&&(Mi.prototype=Object.create(null),new Mi().__proto__||(it=!1));function ES(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function X0(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new ES(t,n||r,o),i=it?it+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function Hc(r,e){--r._eventsCount===0?r._events=new Mi:delete r._events[e]}function Xe(){this._events=new Mi,this._eventsCount=0}Xe.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)vS.call(t,n)&&e.push(it?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Xe.prototype.listeners=function(e){var t=it?it+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Xe.prototype.listenerCount=function(e){var t=it?it+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Xe.prototype.emit=function(e,t,n,o,s,i){var a=it?it+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};Xe.prototype.on=function(e,t,n){return X0(this,e,t,n,!1)};Xe.prototype.once=function(e,t,n){return X0(this,e,t,n,!0)};Xe.prototype.removeListener=function(e,t,n,o){var s=it?it+e:e;if(!this._events[s])return this;if(!t)return Hc(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&Hc(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:Hc(this,s)}return this};Xe.prototype.removeAllListeners=function(e){var t;return e?(t=it?it+e:e,this._events[t]&&Hc(this,t)):(this._events=new Mi,this._eventsCount=0),this};Xe.prototype.off=Xe.prototype.removeListener;Xe.prototype.addListener=Xe.prototype.on;Xe.prefixed=it;Xe.EventEmitter=Xe;typeof rp<"u"&&(rp.exports=Xe)});var nw=Tt((SL,rw)=>{rw.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var ux=Tt(oa=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var l,u,f,d;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[l,u,f,d].join(".")},i=function(c){var l,u,f,d,h,p;for(l=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),h=p[0],u=p[1],c=c.substring(u),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var l,u,f,d,h;for(d=0,l=10,u="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,l=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,l=8,u="7")),h=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)d=d*l+(t(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")d=d*l+(10+t(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*l+(10+t(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===h)throw new Error("empty octet");return[d,f]},r=function(){function c(l,u){var f,d,h,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(p=l.split("/",2),l=p[0],u=p[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(m){throw f=m,new Error("Invalid mask: "+u)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(m){throw f=m,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,f,d;for(d=i(this.first),f=i(this.last),u=0;d<=f;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),oa.ip2long=i,oa.long2ip=a,oa.Netmask=r}).call(oa)});var Tm=Tt((DU,km)=>{var PU=function(){typeof km<"u"&&(km.exports=m);var r=86400,e=3200,t=146097*e/400,n=r*t,o=1e3*n,s=864e13,i=4294967296,a=1e6,c="000000000",l=Math.trunc||function(C){var x=C-C%1;return x==0&&(C<0||C===0&&1/C!=1/0)?-0:x},u=m.prototype,f=(m.fromDate=function(C){return new m(+C)},m.fromInt64BE=D(0,1,2,3,0,4),m.fromInt64LE=D(3,2,1,0,4,0),m.fromString=function(L){var x,P=new m,L=(L+="").replace(/^\s*[+\-]?\d+/,function(A){var A=+A,v=1970+(A-1970)%400;return P.year=A-v,v}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function(k,A,v){return A<0&&(v*=-1),x=6e4*(60*+A+ +v),""}).replace(/\.\d+$/,function(k){return P.nano=+(k+c).substr(1,9),""}).split(/\D+/);if(1<L.length?L[1]--:L[1]=0,P.time=x=Date.UTC.apply(Date,L)-(x||0),isNaN(x))throw new TypeError("Invalid Date");return w(P)},m.fromTimeT=function(C){return S(C,0)},u.year=0,u.time=0,u.nano=0,u.addNano=function(C){return this.nano+=+C||0,this},u.getNano=function(){var C=w(this);return(C.time%1e3*a+ +C.nano+1e9)%1e9},u.getTimeT=function(){var x=w(this),C=Math.floor(x.time/1e3),x=x.year;return x&&(C+=x*t*r/e),C},u.getYear=function(){return this.toDate().getUTCFullYear()+this.year},u.toDate=function(){return y(w(this).time)},u.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},u.toString=function(C){var x=this,P=x.toDate(),L={H:function(){return z(P.getUTCHours())},L:function(){return W(P.getUTCMilliseconds(),3)},M:function(){return z(P.getUTCMinutes())},N:function(){return W(x.getNano(),9)},S:function(){return z(P.getUTCSeconds())},Y:function(){var k=x.getYear();return 999999<k?"+"+k:9999<k?"+"+W(k,6):0<=k?W(k,4):-999999<=k?"-"+W(-k,6):k},a:function(){return h[P.getUTCDay()]},b:function(){return d[P.getUTCMonth()]},d:function(){return z(P.getUTCDate())},e:function(){return function(k){return(9<k?"":" ")+(0|k)}(P.getUTCDate())},m:function(){return z(P.getUTCMonth()+1)}};return function k(A){return A.replace(/%./g,function(v){var _=v[1],b=p[_],_=L[_];return b?k(b):_?_():v})}(C||f)},u.writeInt64BE=E(0,1,2,3,0,4),u.writeInt64LE=E(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],p={"%":"%",F:"%Y-%m-%d",n:`
3
- `,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return m;function m(C,x,P){var L=this;if(!(L instanceof m))return new m(C,x,P);L.time=+C||0,L.nano=+x||0,L.year=+P||0,w(L)}function w(C){var x,P,L,k=C.year,A=C.time,v=C.nano,b=((v<0||a<=v)&&(v-=(P=Math.floor(v/a))*a,A+=P,P=1),k%e);return(A<-s||s<A||b)&&((x=l(A/o))&&(k+=x*e,A-=x*o),(L=y(A)).setUTCFullYear(b+L.getUTCFullYear()),L=(A=+L)+(x=l((k-=b)/e))*o,x&&-s<=L&&L<=s&&(k-=x*e,A=L),P=1),P&&(C.year=k,C.time=A,C.nano=v),C}function y(C){var x=new Date(0);return x.setTime(C),x}function S(k,L){k=+k||0;var P=l((L=(L|0)*i)/n)+l(k/n),L=L%n+k%n,k=l(L/n);return k&&(P+=k,L-=k*n),new m(1e3*L,0,P*e)}function E(C,x,P,L,k,A){return function(b,_){var V=w(this);b=b||new Array(8),M(b,_|=0);var F=Math.floor(V.time/1e3),V=V.year*(t*r/e),R=l(V/i)+l(F/i),V=V%i+F%i,F=Math.floor(V/i);return F&&(R+=F,V-=F*i),v(b,_+k,R),v(b,_+A,V),b};function v(b,_,R){b[_+C]=R>>24&255,b[_+x]=R>>16&255,b[_+P]=R>>8&255,b[_+L]=255&R}}function D(C,x,P,L,k,A){return function(b,_){M(b,_|=0);var R=v(b,_+k);return S(v(b,_+A),R)};function v(b,_){return 16777216*b[_+C]+(b[_+x]<<16|b[_+P]<<8|b[_+L])}}function M(C,x){if(C=C&&C.length,C==null)throw new TypeError("Invalid Buffer");if(C<x+8)throw new RangeError("Out of range")}function z(C){return(9<C?"":"0")+(0|C)}function W(C,x){return(c+(0|C)).substr(-x)}}()});var Cv=Tt((Q$,Iv)=>{function $t(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}Iv.exports=$t;$t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};$t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};$t.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};$t.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};$t.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};$t.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};$t.prototype.start=$t.prototype.try;$t.prototype.errors=function(){return this._errors};$t.prototype.attempts=function(){return this._attempts};$t.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var o=this._errors[n],s=o.message,i=(r[s]||0)+1;r[s]=i,i>=t&&(e=o,t=i)}return e}});var kv=Tt(vo=>{var ok=Cv();vo.operation=function(r){var e=vo.timeouts(r);return new ok(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};vo.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<e.retries;o++)n.push(this.createTimeout(o,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(o,e)),n.sort(function(s,i){return s-i}),n};vo.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};vo.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var o=0;o<t.length;o++){var s=t[o],i=r[s];r[s]=function(c){var l=vo.operation(e),u=Array.prototype.slice.call(arguments,1),f=u.pop();u.push(function(d){l.retry(d)||(d&&(arguments[0]=l.mainError()),f.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,i),r[s].options=e}}});var Bv=Tt((tH,Tv)=>{Tv.exports=kv()});var Hv=Tt((Pz,$v)=>{"use strict";function Tk(r){return r>=55296&&r<=56319}function Bk(r){return r>=56320&&r<=57343}$v.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var o=t.length,s=0,i,a,c=0;c<o;c+=1){if(i=t.charCodeAt(c),a=t[c],Tk(i)&&Bk(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),s+=e(a),s===n)return t.slice(0,c+1);if(s>n)return t.slice(0,c-a.length+1)}return t}});var zv=Tt((Dz,qv)=>{"use strict";function Pk(r){return r>=55296&&r<=56319}function Dk(r){return r>=56320&&r<=57343}qv.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,o=null,s=null,i=0;i<t;i++)o=e.charCodeAt(i),Dk(o)?s!=null&&Pk(s)?n+=1:n+=3:o<=127?n+=1:o>=128&&o<=2047?n+=2:o>=2048&&o<=65535&&(n+=3),s=o;return n}});var Wv=Tt((Lz,Gv)=>{"use strict";var Lk=Hv(),Nk=zv();Gv.exports=Lk.bind(null,Nk)});var Zv=Tt((Nz,Yv)=>{"use strict";var Rk=Wv(),Ok=/[\/\?<>\\:\*\|"]/g,Mk=/[\x00-\x1f\x80-\x9f]/g,Uk=/^\.+$/,Fk=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,Vk=/[\. ]+$/;function jv(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(Ok,e).replace(Mk,e).replace(Uk,e).replace(Fk,e).replace(Vk,e);return Rk(t,255)}Yv.exports=function(r,e){var t=e&&e.replacement||"",n=jv(r,t);return t===""?n:jv(n,"")}});var Xv=Tt(Ks=>{"use strict";var $k="[object ArrayBuffer]",Zr=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===$k}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},mg="string",Hk=/^[0-9a-f\s]+$/i,qk=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,zk=/^[a-zA-Z0-9-_]+$/,gf=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=Zr.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},Ht=class{static toString(e,t=!1){let n=Zr.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},yf=class r{static isHex(e){return typeof e===mg&&Hk.test(e)}static isBase64(e){return typeof e===mg&&qk.test(e)}static isBase64Url(e){return typeof e===mg&&zk.test(e)}static ToString(e,t="utf8"){let n=Zr.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Ht.toString(n,!0);case"utf16":case"utf16be":return Ht.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Ht.fromString(e,!0);case"utf16":case"utf16be":return Ht.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Zr.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return gf.fromString(e);case"utf16":case"utf16be":return Ht.fromString(e);case"utf16le":case"usc2":return Ht.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return gf.toString(e);case"utf16":case"utf16be":return Ht.toString(e);case"utf16le":case"usc2":return Ht.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=Zr.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Zr.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return Ht.toString(e,t)}static FromUtf16String(e,t=!1){return Ht.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};yf.DEFAULT_UTF8_ENCODING="utf8";function Gk(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function Wk(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function jk(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}Ks.BufferSourceConverter=Zr;Ks.Convert=yf;Ks.assign=Gk;Ks.combine=Wk;Ks.isEqual=jk});var fT={};Ee(fT,{DEFAULT_SESSION_MAX_PROVIDERS:()=>Sp,DEFAULT_SESSION_MIN_PROVIDERS:()=>Ap,InsufficientProvidersError:()=>Gi,NoRoutersAvailableError:()=>_n,UnknownCodecError:()=>ji,UnknownHashAlgorithmError:()=>Wi,createHeliaHTTP:()=>uT,heliaDefaults:()=>H1});var kg=Symbol.for("@libp2p/connection");var on=Symbol.for("@libp2p/content-routing");var ld=Symbol.for("@libp2p/peer-discovery");var Fa=Symbol.for("@libp2p/peer-id");function hr(r){return!!r?.[Fa]}var sn=Symbol.for("@libp2p/peer-routing");var ud="keep-alive";var bT=Symbol.for("@libp2p/transport");var Ln;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ln||(Ln={}));var mt=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var B=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Co=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},zs=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var Va=class extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}},ko=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Ie=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},To=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},an=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Ka=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},cn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Gs=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},$a=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Ha=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Cr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Bo=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var Po=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},qa=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},za=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},qt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var tt=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function Ga(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function pr(...r){let e=[];for(let t of r)Ga(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function mr(...r){let e=[];for(let t of r)Ga(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var Nn=Symbol.for("@libp2p/service-capabilities"),fd=Symbol.for("@libp2p/service-dependencies");function de(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var j=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function Q(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Wa=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Do=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Wa(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Wa(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var dd=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ws(r={}){return Z1(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Z1(r,e){e=e??{};let t=e.onEnd,n=new Do,o,s,i,a=Q(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((w,y)=>{s=S=>{s=null,n.push(S);try{w(r(n))}catch(E){y(E)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Q()})}},l=w=>s!=null?s(w):(n.push(w),o),u=w=>(n=new Do,s!=null?s({error:w}):(n.push({error:w}),o)),f=w=>{if(i)return o;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:w})},d=w=>i?o:(i=!0,w!=null?u(w):l({done:!0})),h=()=>(n=new Do,d(),{done:!0}),p=w=>(d(w),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:f,end:d,get readableLength(){return n.size},onEmpty:async w=>{let y=w?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let S,E;y!=null&&(S=new Promise((D,M)=>{E=()=>{M(new dd)},y.addEventListener("abort",E)}));try{await Promise.race([a.promise,S])}finally{E!=null&&y!=null&&y?.removeEventListener("abort",E)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(w){return m.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(w){return m.end(w),t!=null&&(t(w),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:w=>m.onEmpty(w)},o}var gt=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function gr(r,e,t,n){let o=new gt(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){pd(t,"abort",f),pd(r,e,l),pd(r,s,u)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};hd(t,"abort",f),hd(r,e,l),hd(r,s,u)})}function hd(r,e,t){r!=null&&(Tg(r)?r.addEventListener(e,t):r.addListener(e,t))}function pd(r,e,t){r!=null&&(Tg(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Tg(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function js(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var ja=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Ya=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Za=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function Le(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Za(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Za(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Xa=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Q(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new mt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function X1(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ja=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=X1(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new mt),this.cleanup())}async join(e={}){let t=new Xa(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Le(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var zt=class extends tt{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=js(this.emitEmpty.bind(this),1),this.emitIdle=js(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Ya;let n=new Ja(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new mt)}),this.clear()}async onEmpty(e){this.size!==0&&await gr(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await gr(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await gr(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ws({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new mt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Lo=class extends zt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function J1(r){return r[Symbol.asyncIterator]!=null}function Q1(r){if(J1(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ys=Q1;function be(r=0){return new Uint8Array(r)}function ze(r=0){return new Uint8Array(r)}var eE=Math.pow(2,7),tE=Math.pow(2,14),rE=Math.pow(2,21),md=Math.pow(2,28),gd=Math.pow(2,35),yd=Math.pow(2,42),wd=Math.pow(2,49),se=128,Ge=127;function Ce(r){if(r<eE)return 1;if(r<tE)return 2;if(r<rE)return 3;if(r<md)return 4;if(r<gd)return 5;if(r<yd)return 6;if(r<wd)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function No(r,e,t=0){switch(Ce(r)){case 8:e[t++]=r&255|se,r/=128;case 7:e[t++]=r&255|se,r/=128;case 6:e[t++]=r&255|se,r/=128;case 5:e[t++]=r&255|se,r/=128;case 4:e[t++]=r&255|se,r>>>=7;case 3:e[t++]=r&255|se,r>>>=7;case 2:e[t++]=r&255|se,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function nE(r,e,t=0){switch(Ce(r)){case 8:e.set(t++,r&255|se),r/=128;case 7:e.set(t++,r&255|se),r/=128;case 6:e.set(t++,r&255|se),r/=128;case 5:e.set(t++,r&255|se),r/=128;case 4:e.set(t++,r&255|se),r>>>=7;case 3:e.set(t++,r&255|se),r>>>=7;case 2:e.set(t++,r&255|se),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function bd(r,e){let t=r[e],n=0;if(n+=t&Ge,t<se||(t=r[e+1],n+=(t&Ge)<<7,t<se)||(t=r[e+2],n+=(t&Ge)<<14,t<se)||(t=r[e+3],n+=(t&Ge)<<21,t<se)||(t=r[e+4],n+=(t&Ge)*md,t<se)||(t=r[e+5],n+=(t&Ge)*gd,t<se)||(t=r[e+6],n+=(t&Ge)*yd,t<se)||(t=r[e+7],n+=(t&Ge)*wd,t<se))return n;throw new RangeError("Could not decode varint")}function oE(r,e){let t=r.get(e),n=0;if(n+=t&Ge,t<se||(t=r.get(e+1),n+=(t&Ge)<<7,t<se)||(t=r.get(e+2),n+=(t&Ge)<<14,t<se)||(t=r.get(e+3),n+=(t&Ge)<<21,t<se)||(t=r.get(e+4),n+=(t&Ge)*md,t<se)||(t=r.get(e+5),n+=(t&Ge)*gd,t<se)||(t=r.get(e+6),n+=(t&Ge)*yd,t<se)||(t=r.get(e+7),n+=(t&Ge)*wd,t<se))return n;throw new RangeError("Could not decode varint")}function yr(r,e,t=0){return e==null&&(e=ze(Ce(r))),e instanceof Uint8Array?No(r,e,t):nE(r,e,t)}function Rn(r,e=0){return r instanceof Uint8Array?bd(r,e):oE(r,e)}function We(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=ze(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function Z(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Pg=Symbol.for("@achingbrain/uint8arraylist");function Bg(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Oo(r){return!!r?.[Pg]}var ee=class r{bufs;length;[Pg]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Oo(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Oo(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Bg(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Bg(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Oo(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return We(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:We(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Oo(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ze(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=be(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=be(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=be(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=ze(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=be(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=be(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=be(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=be(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=be(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Z(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Qa=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Mo=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ec=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Zs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function tc(r){return r[Symbol.asyncIterator]!=null}function Dg(r,e){if(r.byteLength>e)throw new Mo("Message length too long")}var nc=r=>{let e=Ce(r),t=ze(e);return yr(r,t),nc.bytes=e,t};nc.bytes=0;function oc(r,e){e=e??{};let t=e.lengthEncoder??nc,n=e?.maxDataLength??4194304;function*o(s){Dg(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return tc(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}oc.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??nc,n=e?.maxDataLength??4194304;return Dg(r,n),new ee(t(r.byteLength),r)};var On;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(On||(On={}));var vd=r=>{let e=Rn(r);return vd.bytes=Ce(e),e};vd.bytes=0;function xd(r,e){let t=new ee,n=On.LENGTH,o=-1,s=e?.lengthDecoder??vd,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===On.LENGTH)try{if(o=s(t),o<0)throw new Qa("Invalid message length");if(o>a)throw new Mo("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=On.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new ec("Message length length too long");break}throw l}if(n===On.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=On.LENGTH}}}return tc(r)?async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Zs("Unexpected end of input")}():function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Zs("Unexpected end of input")}()}xd.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return xd(n,{...e??{},onLength:s=>{t=s}})};function iE(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Uo=iE;function aE(r){return r[Symbol.asyncIterator]!=null}function cE(r,e){let t=0;if(aE(r))return async function*(){for await(let c of r)yield e(c,t++)}();let n=Uo(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){yield await i;for(let c of n)yield e(c,t++)}();let a=e;return function*(){yield i;for(let c of n)yield a(c,t++)}()}var sc=cE;var Ed=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Q(),this.haveNext=Q()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Q(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Q(),await Le(this.readNext.promise,t?.signal,t)}};function ic(){return new Ed}function lE(r){return r[Symbol.asyncIterator]!=null}async function uE(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*fE(r){let e=new AbortController,t=ic();uE(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*dE(r){for(let e of r)yield*e}function hE(...r){let e=[];for(let t of r)lE(t)||e.push(t);return e.length===r.length?dE(e):fE(r)}var Bt=hE;function pE(r){return r[Symbol.asyncIterator]!=null}function mE(r,e){return pE(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var ac=mE;var Ad=new Float32Array([-0]),ln=new Uint8Array(Ad.buffer);function Lg(r,e,t){Ad[0]=r,e[t]=ln[0],e[t+1]=ln[1],e[t+2]=ln[2],e[t+3]=ln[3]}function Ng(r,e){return ln[0]=r[e],ln[1]=r[e+1],ln[2]=r[e+2],ln[3]=r[e+3],Ad[0]}var Sd=new Float64Array([-0]),je=new Uint8Array(Sd.buffer);function Rg(r,e,t){Sd[0]=r,e[t]=je[0],e[t+1]=je[1],e[t+2]=je[2],e[t+3]=je[3],e[t+4]=je[4],e[t+5]=je[5],e[t+6]=je[6],e[t+7]=je[7]}function Og(r,e){return je[0]=r[e],je[1]=r[e+1],je[2]=r[e+2],je[3]=r[e+3],je[4]=r[e+4],je[5]=r[e+5],je[6]=r[e+6],je[7]=r[e+7],Sd[0]}var gE=BigInt(Number.MAX_SAFE_INTEGER),yE=BigInt(Number.MIN_SAFE_INTEGER),yt=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Mn;if(e<gE&&e>yE)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Mg&&(o=0n,++n>Mg&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Mn;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Mn}},Mn=new yt(0,0);Mn.toBigInt=function(){return 0n};Mn.zzEncode=Mn.zzDecode=function(){return this};Mn.length=function(){return 1};var Mg=4294967296n;function Ug(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Fg(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function _d(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Gt(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function cc(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Id=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Gt(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Gt(this,4);return cc(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Gt(this,4);return cc(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Gt(this,4);let e=Ng(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Gt(this,4);let e=Og(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Gt(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Fg(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Gt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Gt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new yt(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Gt(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Gt(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Gt(this,8);let e=cc(this.buf,this.pos+=4),t=cc(this.buf,this.pos+=4);return new yt(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=bd(this.buf,this.pos);return this.pos+=Ce(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Cd(r){return new Id(r instanceof Uint8Array?r:r.subarray())}function Ne(r,e,t){let n=Cd(r);return e.decode(n,void 0,t)}var Ld={};Ee(Ld,{base10:()=>SE});var y6=new Uint8Array(0);function Kg(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Wt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function $g(r){return new TextEncoder().encode(r)}function Hg(r){return new TextDecoder().decode(r)}function wE(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,w=0,y=0,S=p.length;y!==S&&p[y]===0;)y++,m++;for(var E=(S-y)*u+1>>>0,D=new Uint8Array(E);y!==S;){for(var M=p[y],z=0,W=E-1;(M!==0||z<w)&&W!==-1;W--,z++)M+=256*D[W]>>>0,D[W]=M%a>>>0,M=M/a>>>0;if(M!==0)throw new Error("Non-zero carry");w=z,y++}for(var C=E-w;C!==E&&D[C]===0;)C++;for(var x=c.repeat(m);C<E;++C)x+=r.charAt(D[C]);return x}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var w=0,y=0;p[m]===c;)w++,m++;for(var S=(p.length-m)*l+1>>>0,E=new Uint8Array(S);p[m];){var D=t[p.charCodeAt(m)];if(D===255)return;for(var M=0,z=S-1;(D!==0||M<y)&&z!==-1;z--,M++)D+=a*E[z]>>>0,E[z]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");y=M,m++}if(p[m]!==" "){for(var W=S-y;W!==S&&E[W]===0;)W++;for(var C=new Uint8Array(w+(S-W)),x=w;W!==S;)C[x++]=E[W++];return C}}}function h(p){var m=d(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var bE=wE,xE=bE,qg=xE;var Td=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Bd=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return zg(this,e)}},Pd=class{decoders;constructor(e){this.decoders=e}or(e){return zg(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function zg(r,e){return new Pd({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Dd=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Td(e,t,n),this.decoder=new Bd(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Fo({name:r,prefix:e,encode:t,decode:n}){return new Dd(r,e,t,n)}function un({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=qg(t,r);return Fo({prefix:e,name:r,encode:n,decode:s=>Wt(o(s))})}function vE(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function EE(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function AE(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function xe({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=AE(n);return Fo({prefix:e,name:r,encode(s){return EE(s,n,t)},decode(s){return vE(s,o,t,r)}})}var SE=un({prefix:"9",name:"base10",alphabet:"0123456789"});var Nd={};Ee(Nd,{base16:()=>_E,base16upper:()=>IE});var _E=xe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),IE=xe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Rd={};Ee(Rd,{base2:()=>CE});var CE=xe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Od={};Ee(Od,{base256emoji:()=>DE});var Gg=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}"),kE=Gg.reduce((r,e,t)=>(r[t]=e,r),[]),TE=Gg.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function BE(r){return r.reduce((e,t)=>(e+=kE[t],e),"")}function PE(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=TE[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var DE=Fo({prefix:"\u{1F680}",name:"base256emoji",encode:BE,decode:PE});var Md={};Ee(Md,{base32:()=>ke,base32hex:()=>OE,base32hexpad:()=>UE,base32hexpadupper:()=>FE,base32hexupper:()=>ME,base32pad:()=>NE,base32padupper:()=>RE,base32upper:()=>LE,base32z:()=>VE});var ke=xe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),LE=xe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),NE=xe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),RE=xe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),OE=xe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ME=xe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),UE=xe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),FE=xe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),VE=xe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ud={};Ee(Ud,{base36:()=>wr,base36upper:()=>KE});var wr=un({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),KE=un({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Fd={};Ee(Fd,{base58btc:()=>ie,base58flickr:()=>$E});var ie=un({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),$E=un({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Kd={};Ee(Kd,{base64:()=>Ye,base64pad:()=>HE,base64url:()=>Vd,base64urlpad:()=>qE});var Ye=xe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),HE=xe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Vd=xe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qE=xe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var $d={};Ee($d,{base8:()=>zE});var zE=xe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Hd={};Ee(Hd,{identity:()=>GE});var GE=Fo({prefix:"\0",name:"identity",encode:r=>Hg(r),decode:r=>$g(r)});var lc={};Ee(lc,{code:()=>qd,decode:()=>XE,encode:()=>ZE,name:()=>YE});var WE=new TextEncoder,jE=new TextDecoder,YE="json",qd=512;function ZE(r){return WE.encode(JSON.stringify(r))}function XE(r){return JSON.parse(jE.decode(r))}var Js={};Ee(Js,{code:()=>Xs,decode:()=>e2,encode:()=>QE,name:()=>JE});var JE="raw",Xs=85;function QE(r){return Wt(r)}function e2(r){return Wt(r)}var Gd={};Ee(Gd,{identity:()=>Ze});var t2=Yg,Wg=128,r2=127,n2=~r2,o2=Math.pow(2,31);function Yg(r,e,t){e=e||[],t=t||0;for(var n=t;r>=o2;)e[t++]=r&255|Wg,r/=128;for(;r&n2;)e[t++]=r&255|Wg,r>>>=7;return e[t]=r|0,Yg.bytes=t-n+1,e}var s2=zd,i2=128,jg=127;function zd(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw zd.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&jg)<<o:(i&jg)*Math.pow(2,o),o+=7}while(i>=i2);return zd.bytes=s-n,t}var a2=Math.pow(2,7),c2=Math.pow(2,14),l2=Math.pow(2,21),u2=Math.pow(2,28),f2=Math.pow(2,35),d2=Math.pow(2,42),h2=Math.pow(2,49),p2=Math.pow(2,56),m2=Math.pow(2,63),g2=function(r){return r<a2?1:r<c2?2:r<l2?3:r<u2?4:r<f2?5:r<d2?6:r<h2?7:r<p2?8:r<m2?9:10},y2={encode:t2,decode:s2,encodingLength:g2},w2=y2,Qs=w2;function ei(r,e=0){return[Qs.decode(r,e),Qs.decode.bytes]}function Vo(r,e,t=0){return Qs.encode(r,e,t),e}function Ko(r){return Qs.encodingLength(r)}function jt(r,e){let t=e.byteLength,n=Ko(r),o=n+Ko(t),s=new Uint8Array(o+t);return Vo(r,s,0),Vo(t,s,n),s.set(e,o),new $o(r,t,e,s)}function wt(r){let e=Wt(r),[t,n]=ei(e),[o,s]=ei(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new $o(t,o,i,e)}function Zg(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Kg(r.bytes,t.bytes)}}var $o=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var Xg=0,b2="identity",Jg=Wt;function x2(r){return jt(Xg,Jg(r))}var Ze={code:Xg,name:b2,encode:Jg,digest:x2};var Yd={};Ee(Yd,{sha256:()=>Yt,sha512:()=>fc});function jd({name:r,code:e,encode:t}){return new Wd(r,e,t)}var Wd=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?jt(this.code,t):t.then(n=>jt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ey(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Yt=jd({name:"sha2-256",code:18,encode:ey("SHA-256")}),fc=jd({name:"sha2-512",code:19,encode:ey("SHA-512")});function ty(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return E2(t,Zd(r),e??ie.encoder);default:return A2(t,Zd(r),e??ke.encoder)}}var ry=new WeakMap;function Zd(r){let e=ry.get(r);if(e==null){let t=new Map;return ry.set(r,t),t}return e}var H=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==ti)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==S2)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=jt(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Zg(e.multihash,n.multihash)}toString(e){return ty(this,e)}toJSON(){return{"/":ty(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??ny(n,o,s.bytes))}else if(t[_2]===!0){let{version:n,multihash:o,code:s}=t,i=wt(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ti)throw new Error(`Version 0 CID must use dag-pb (code: ${ti}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=ny(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ti,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Wt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new $o(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=ei(e.subarray(t));return t+=d,f},o=n(),s=ti;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=v2(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Zd(s).set(n,e),s}};function v2(r,e){switch(r[0]){case"Q":{let t=e??ie;return[ie.prefix,t.decode(`${ie.prefix}${r}`)]}case ie.prefix:{let t=e??ie;return[ie.prefix,t.decode(r)]}case ke.prefix:{let t=e??ke;return[ke.prefix,t.decode(r)]}case wr.prefix:{let t=e??wr;return[wr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function E2(r,e,t){let{prefix:n}=t;if(n!==ie.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function A2(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var ti=112,S2=18;function ny(r,e,t){let n=Ko(r),o=n+Ko(e),s=new Uint8Array(o+t.byteLength);return Vo(r,s,0),Vo(e,s,n),s.set(t,o),s}var _2=Symbol.for("@ipld/js-cid/CID");var ri={...Hd,...Rd,...$d,...Ld,...Nd,...Md,...Ud,...Fd,...Kd,...Od},eB={...Yd,...Gd};function sy(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var oy=sy("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Xd=sy("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ze(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),I2={utf8:oy,"utf-8":oy,hex:ri.base16,latin1:Xd,ascii:Xd,binary:Xd,...ri},dc=I2;function T(r,e="utf8"){let t=dc[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Jd(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return ze(i);o+i>e&&(n=ze(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Un=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Qd(){}var th=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},C2=Jd();function k2(r){return globalThis.Buffer!=null?ze(r):C2(r)}var oi=class{len;head;tail;states;constructor(){this.len=0,this.head=new Un(Qd,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Un(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new rh((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(hc,10,yt.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=yt.fromBigInt(e);return this._push(hc,t.length(),t)}uint64Number(e){return this._push(No,Ce(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=yt.fromBigInt(e).zzEncode();return this._push(hc,t.length(),t)}sint64Number(e){let t=yt.fromNumber(e).zzEncode();return this._push(hc,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(eh,1,e?1:0)}fixed32(e){return this._push(ni,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=yt.fromBigInt(e);return this._push(ni,4,t.lo)._push(ni,4,t.hi)}fixed64Number(e){let t=yt.fromNumber(e);return this._push(ni,4,t.lo)._push(ni,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Lg,4,e)}double(e){return this._push(Rg,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(eh,1,0):this.uint32(t)._push(B2,t,e)}string(e){let t=Ug(e);return t!==0?this.uint32(t)._push(_d,t,e):this._push(eh,1,0)}fork(){return this.states=new th(this),this.head=this.tail=new Un(Qd,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Un(Qd,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=k2(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function eh(r,e,t){e[t]=r&255}function T2(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var rh=class extends Un{next;constructor(e,t){super(T2,e,t),this.next=void 0}};function hc(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function ni(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function B2(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(oi.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(P2,e,r),this},oi.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(D2,e,r),this});function P2(r,e,t){e.set(r,t)}function D2(r,e,t){r.length<40?_d(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(T(r),t)}function nh(){return new oi}function Re(r,e){let t=nh();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Ho;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ho||(Ho={}));function pc(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function si(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return pc("enum",Ho.VARINT,t,n)}function Oe(r,e){return pc("message",Ho.LENGTH_DELIMITED,r,e)}var Fn=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},ii=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};function O(r,e="utf8"){let t=dc[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var L2=parseInt("11111",2),oh=parseInt("10000000",2),N2=parseInt("01111111",2),iy={0:ai,1:ai,2:R2,3:U2,4:F2,5:M2,6:O2,16:ai,22:ai,48:ai};function Pt(r,e={offset:0}){let t=r[e.offset]&L2;if(e.offset++,iy[t]!=null)return iy[t](r,e);throw new Error("No decoder for tag "+t)}function ci(r,e){let t=0;if((r[e.offset]&oh)===oh){let n=r[e.offset]&N2,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function ai(r,e){ci(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Pt(r,e);if(n===null)break;t.push(n)}return t}function R2(r,e){let t=ci(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function O2(r,e){let t=ci(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function M2(r,e){return e.offset++,null}function U2(r,e){let t=ci(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function F2(r,e){let t=ci(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function V2(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ee;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function mc(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=V2(r.byteLength);return new ee(Uint8Array.from([e.byteLength|oh]),e)}function rt(r){let e=new ee,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ee(Uint8Array.from([2]),mc(e),e)}function li(r){let e=Uint8Array.from([0]),t=new ee(e,r);return new ee(Uint8Array.from([3]),mc(t),t)}function ay(r){return new ee(Uint8Array.from([4]),mc(r),r)}function Zt(r,e=48){let t=new ee;for(let n of r)t.append(n);return new ee(Uint8Array.from([e]),mc(t),t)}var cy="1.2.840.10045.3.1.7",ly="1.3.132.0.34",uy="1.3.132.0.35";async function fy(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function dy(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function hy(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var K2=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),$2=Uint8Array.from([6,5,43,129,4,0,34]),H2=Uint8Array.from([6,5,43,129,4,0,35]),py={ext:!0,kty:"EC",crv:"P-256"},my={ext:!0,kty:"EC",crv:"P-384"},gy={ext:!0,kty:"EC",crv:"P-521"},qo=32,zo=48,Go=66;function yy(r){let e=Pt(r);return sh(e)}function sh(r){let e=r[1],t=O(e,"base64url"),n=r[2][1][0],o=1,s,i;if(e.byteLength===qo)return s=O(n.subarray(o,o+qo),"base64url"),i=O(n.subarray(o+qo),"base64url"),new Kn({...py,key_ops:["sign"],d:t,x:s,y:i});if(e.byteLength===zo)return s=O(n.subarray(o,o+zo),"base64url"),i=O(n.subarray(o+zo),"base64url"),new Kn({...my,key_ops:["sign"],d:t,x:s,y:i});if(e.byteLength===Go)return s=O(n.subarray(o,o+Go),"base64url"),i=O(n.subarray(o+Go),"base64url"),new Kn({...gy,key_ops:["sign"],d:t,x:s,y:i});throw new B(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function ih(r){let e=Pt(r);return wy(e)}function wy(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===qo*2+1)return n=O(e.subarray(t,t+qo),"base64url"),o=O(e.subarray(t+qo),"base64url"),new Vn({...py,key_ops:["verify"],x:n,y:o});if(e.byteLength===zo*2+1)return n=O(e.subarray(t,t+zo),"base64url"),o=O(e.subarray(t+zo),"base64url"),new Vn({...my,key_ops:["verify"],x:n,y:o});if(e.byteLength===Go*2+1)return n=O(e.subarray(t,t+Go),"base64url"),o=O(e.subarray(t+Go),"base64url"),new Vn({...gy,key_ops:["verify"],x:n,y:o});throw new B(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function by(r){return Zt([rt(Uint8Array.from([1])),ay(T(r.d??"","base64url")),Zt([vy(r.crv)],160),Zt([li(new ee(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function xy(r){return Zt([rt(Uint8Array.from([1])),Zt([vy(r.crv)],160),Zt([li(new ee(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function vy(r){if(r==="P-256")return K2;if(r==="P-384")return $2;if(r==="P-521")return H2;throw new B(`Invalid curve ${r}`)}async function Ey(r="P-256"){let e=await fy(r);return new Kn(e.privateKey)}var Vn=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=xy(this.jwk)),this._raw}toMultihash(){return Ze.digest(Dt(this))}toCID(){return H.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}async verify(e,t,n){return hy(this.jwk,t,e,n)}},Kn=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Vn({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=by(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}async sign(e,t){return dy(this.jwk,e,t)}};var $n=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Br(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Tr(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function nt(r,...e){if(!Br(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function jo(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Tr(r.outputLen),Tr(r.blockLen)}function Yo(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Sy(r,e){nt(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function ut(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Hn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Xt(r,e){return r<<32-e|r>>>e}function gc(r,e){return r<<e|r>>>32-e>>>0}var _y=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",q2=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Lt(r){if(nt(r),_y)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=q2[r[t]];return e}var kr={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ay(r){if(r>=kr._0&&r<=kr._9)return r-kr._0;if(r>=kr.A&&r<=kr.F)return r-(kr.A-10);if(r>=kr.a&&r<=kr.f)return r-(kr.a-10)}function qn(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(_y)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Ay(r.charCodeAt(s)),a=Ay(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}var z2=async()=>{};async function Iy(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let s=Date.now()-n;s>=0&&s<e||(await z2(),n+=s)}}function yc(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function ui(r){return typeof r=="string"&&(r=yc(r)),nt(r),r}function ah(r){return typeof r=="string"&&(r=yc(r)),nt(r),r}function ot(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];nt(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Cy(r,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(r,e)}var Wo=class{};function fi(r){let e=n=>r().update(ui(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function fn(r=32){if($n&&typeof $n.getRandomValues=="function")return $n.getRandomValues(new Uint8Array(r));if($n&&typeof $n.randomBytes=="function")return Uint8Array.from($n.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function G2(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,l=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+l,a,n)}function wc(r,e,t){return r&e^~r&t}function bc(r,e,t){return r&e^r&t^e&t}var zn=class extends Wo{constructor(e,t,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Hn(this.buffer)}update(e){Yo(this),e=ui(e),nt(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Hn(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Yo(this),Sy(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,ut(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;G2(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Hn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Pr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var xc=BigInt(4294967295),ky=BigInt(32);function W2(r,e=!1){return e?{h:Number(r&xc),l:Number(r>>ky&xc)}:{h:Number(r>>ky&xc)|0,l:Number(r&xc)|0}}function Ty(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=W2(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var ch=(r,e,t)=>r>>>t,lh=(r,e,t)=>r<<32-t|e>>>t,Gn=(r,e,t)=>r>>>t|e<<32-t,Wn=(r,e,t)=>r<<32-t|e>>>t,di=(r,e,t)=>r<<64-t|e>>>t-32,hi=(r,e,t)=>r>>>t-32|e<<64-t;function xr(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var By=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Py=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Dy=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Ly=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Ny=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Ry=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var Y2=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),dn=new Uint32Array(64),vc=class extends zn{constructor(e=32){super(64,e,8,!1),this.A=Pr[0]|0,this.B=Pr[1]|0,this.C=Pr[2]|0,this.D=Pr[3]|0,this.E=Pr[4]|0,this.F=Pr[5]|0,this.G=Pr[6]|0,this.H=Pr[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)dn[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=dn[f-15],h=dn[f-2],p=Xt(d,7)^Xt(d,18)^d>>>3,m=Xt(h,17)^Xt(h,19)^h>>>10;dn[f]=m+dn[f-7]+p+dn[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Xt(a,6)^Xt(a,11)^Xt(a,25),h=u+d+wc(a,c,l)+Y2[f]+dn[f]|0,m=(Xt(n,2)^Xt(n,13)^Xt(n,22))+bc(n,o,s)|0;u=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){ut(dn)}destroy(){this.set(0,0,0,0,0,0,0,0),ut(this.buffer)}};var Oy=Ty(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Z2=Oy[0],X2=Oy[1],hn=new Uint32Array(80),pn=new Uint32Array(80),Ec=class extends zn{constructor(e=64){super(128,e,16,!1),this.Ah=Me[0]|0,this.Al=Me[1]|0,this.Bh=Me[2]|0,this.Bl=Me[3]|0,this.Ch=Me[4]|0,this.Cl=Me[5]|0,this.Dh=Me[6]|0,this.Dl=Me[7]|0,this.Eh=Me[8]|0,this.El=Me[9]|0,this.Fh=Me[10]|0,this.Fl=Me[11]|0,this.Gh=Me[12]|0,this.Gl=Me[13]|0,this.Hh=Me[14]|0,this.Hl=Me[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:h,Gl:p,Hh:m,Hl:w}=this;return[e,t,n,o,s,i,a,c,l,u,f,d,h,p,m,w]}set(e,t,n,o,s,i,a,c,l,u,f,d,h,p,m,w){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=m|0,this.Hl=w|0}process(e,t){for(let E=0;E<16;E++,t+=4)hn[E]=e.getUint32(t),pn[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let D=hn[E-15]|0,M=pn[E-15]|0,z=Gn(D,M,1)^Gn(D,M,8)^ch(D,M,7),W=Wn(D,M,1)^Wn(D,M,8)^lh(D,M,7),C=hn[E-2]|0,x=pn[E-2]|0,P=Gn(C,x,19)^di(C,x,61)^ch(C,x,6),L=Wn(C,x,19)^hi(C,x,61)^lh(C,x,6),k=Dy(W,L,pn[E-7],pn[E-16]),A=Ly(k,z,P,hn[E-7],hn[E-16]);hn[E]=A|0,pn[E]=k|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:h,Fl:p,Gh:m,Gl:w,Hh:y,Hl:S}=this;for(let E=0;E<80;E++){let D=Gn(f,d,14)^Gn(f,d,18)^di(f,d,41),M=Wn(f,d,14)^Wn(f,d,18)^hi(f,d,41),z=f&h^~f&m,W=d&p^~d&w,C=Ny(S,M,W,X2[E],pn[E]),x=Ry(C,y,D,z,Z2[E],hn[E]),P=C|0,L=Gn(n,o,28)^di(n,o,34)^di(n,o,39),k=Wn(n,o,28)^hi(n,o,34)^hi(n,o,39),A=n&s^n&a^s&a,v=o&i^o&c^i&c;y=m|0,S=w|0,m=h|0,w=p|0,h=f|0,p=d|0,{h:f,l:d}=xr(l|0,u|0,x|0,P|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let b=By(P,k,v);n=Py(b,x,L,A),o=b|0}({h:n,l:o}=xr(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=xr(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=xr(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=xr(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=xr(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=xr(this.Fh|0,this.Fl|0,h|0,p|0),{h:m,l:w}=xr(this.Gh|0,this.Gl|0,m|0,w|0),{h:y,l:S}=xr(this.Hh|0,this.Hl|0,y|0,S|0),this.set(n,o,s,i,a,c,l,u,f,d,h,p,m,w,y,S)}roundClean(){ut(hn,pn)}destroy(){ut(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Ac=fi(()=>new vc);var Sc=fi(()=>new Ec);var dh=BigInt(0),fh=BigInt(1);function Dr(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function bt(r,e,t=""){let n=Br(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function pi(r){let e=r.toString(16);return e.length&1?"0"+e:e}function My(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?dh:BigInt("0x"+r)}function Zo(r){return My(Lt(r))}function Lr(r){return nt(r),My(Lt(Uint8Array.from(r).reverse()))}function _c(r,e){return qn(r.toString(16).padStart(e*2,"0"))}function hh(r,e){return _c(r,e).reverse()}function ce(r,e,t){let n;if(typeof e=="string")try{n=qn(e)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Br(e))n=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(r+" of length "+t+" expected, got "+o);return n}function Uy(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function ph(r){return Uint8Array.from(r)}var uh=r=>typeof r=="bigint"&&dh<=r;function Fy(r,e,t){return uh(r)&&uh(e)&&uh(t)&&e<=r&&r<t}function mi(r,e,t,n){if(!Fy(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Ic(r){let e;for(e=0;r>dh;r>>=fh,e+=1);return e}var mn=r=>(fh<<BigInt(r))-fh;function Vy(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=h=>new Uint8Array(h),o=h=>Uint8Array.of(h),s=n(r),i=n(r),a=0,c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>t(i,s,...h),u=(h=n(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,p=[];for(;h<e;){s=l();let m=s.slice();p.push(m),h+=s.length}return ot(...p)};return(h,p)=>{c(),u(h);let m;for(;!(m=p(f()));)u();return c(),m}}function gn(r,e,t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(o,s,i){let a=r[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>n(o,s,!1)),Object.entries(t).forEach(([o,s])=>n(o,s,!0))}var mh=()=>{throw new Error("not implemented")};function Xo(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var st=BigInt(0),Te=BigInt(1),jn=BigInt(2),Hy=BigInt(3),qy=BigInt(4),zy=BigInt(5),J2=BigInt(7),Gy=BigInt(8),Q2=BigInt(9),Wy=BigInt(16);function ve(r,e){let t=r%e;return t>=st?t:e+t}function he(r,e,t){let n=r;for(;e-- >st;)n*=n,n%=t;return n}function Ky(r,e){if(r===st)throw new Error("invert: expected non-zero number");if(e<=st)throw new Error("invert: expected positive modulus, got "+e);let t=ve(r,e),n=e,o=st,s=Te,i=Te,a=st;for(;t!==st;){let l=n/t,u=n%t,f=o-i*l,d=s-a*l;n=t,t=u,o=i,s=a,i=f,a=d}if(n!==Te)throw new Error("invert: does not exist");return ve(o,e)}function gh(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function jy(r,e){let t=(r.ORDER+Te)/qy,n=r.pow(e,t);return gh(r,n,e),n}function eA(r,e){let t=(r.ORDER-zy)/Gy,n=r.mul(e,jn),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,jn),o),a=r.mul(s,r.sub(i,r.ONE));return gh(r,a,e),a}function tA(r){let e=xt(r),t=Yy(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+J2)/Wy;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),f=a.mul(l,o),d=a.mul(l,s),h=a.eql(a.sqr(u),c),p=a.eql(a.sqr(f),c);l=a.cmov(l,u,h),u=a.cmov(d,f,p);let m=a.eql(a.sqr(u),c),w=a.cmov(l,u,m);return gh(a,w,c),w}}function Yy(r){if(r<Hy)throw new Error("sqrt is not defined for small field");let e=r-Te,t=0;for(;e%jn===st;)e/=jn,t++;let n=jn,o=xt(r);for(;$y(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return jy;let s=o.pow(n,e),i=(e+Te)/jn;return function(c,l){if(c.is0(l))return l;if($y(c,l)!==1)throw new Error("Cannot find square root");let u=t,f=c.mul(c.ONE,s),d=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,m=c.sqr(d);for(;!c.eql(m,c.ONE);)if(p++,m=c.sqr(m),p===u)throw new Error("Cannot find square root");let w=Te<<BigInt(u-p-1),y=c.pow(f,w);u=p,f=c.sqr(y),d=c.mul(d,f),h=c.mul(h,y)}return h}}function rA(r){return r%qy===Hy?jy:r%Gy===zy?eA:r%Wy===Q2?tA(r):Yy(r)}var Nr=(r,e)=>(ve(r,e)&Te)===Te,nA=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function yh(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=nA.reduce((n,o)=>(n[o]="function",n),e);return gn(r,t),r}function oA(r,e,t){if(t<st)throw new Error("invalid exponent, negatives unsupported");if(t===st)return r.ONE;if(t===Te)return e;let n=r.ONE,o=e;for(;t>st;)t&Te&&(n=r.mul(n,o)),o=r.sqr(o),t>>=Te;return n}function gi(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function $y(r,e){let t=(r.ORDER-Te)/jn,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Cc(r,e){e!==void 0&&Tr(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function xt(r,e,t=!1,n={}){if(r<=st)throw new Error("invalid field: expected ORDER > 0, got "+r);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||t)throw new Error("cannot specify opts in two arguments");let d=e;d.BITS&&(o=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(t=d.isLE),typeof d.modFromBytes=="boolean"&&(i=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(o=e),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:l}=Cc(r,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,f=Object.freeze({ORDER:r,isLE:t,BITS:c,BYTES:l,MASK:mn(c),ZERO:st,ONE:Te,allowedLengths:a,create:d=>ve(d,r),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return st<=d&&d<r},is0:d=>d===st,isValidNot0:d=>!f.is0(d)&&f.isValid(d),isOdd:d=>(d&Te)===Te,neg:d=>ve(-d,r),eql:(d,h)=>d===h,sqr:d=>ve(d*d,r),add:(d,h)=>ve(d+h,r),sub:(d,h)=>ve(d-h,r),mul:(d,h)=>ve(d*h,r),pow:(d,h)=>oA(f,d,h),div:(d,h)=>ve(d*Ky(h,r),r),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>Ky(d,r),sqrt:s||(d=>(u||(u=rA(r)),u(f,d))),toBytes:d=>t?hh(d,l):_c(d,l),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);let m=new Uint8Array(l);m.set(d,t?0:m.length-d.length),d=m}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let p=t?Lr(d):Zo(d);if(i&&(p=ve(p,r)),!h&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>gi(f,d),cmov:(d,h,p)=>p?h:d});return Object.freeze(f)}function Zy(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function wh(r){let e=Zy(r);return e+Math.ceil(e/2)}function bh(r,e,t=!1){let n=r.length,o=Zy(e),s=wh(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Lr(r):Zo(r),a=ve(i,e-Te)+Te;return t?hh(a,o):_c(a,o)}var Jo=BigInt(0),Yn=BigInt(1);function yi(r,e){let t=e.negate();return r?t:e}function Rr(r,e){let t=gi(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function e0(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function xh(r,e){e0(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=mn(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Xy(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=Yn);let l=e*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:h,offsetF:l}}function sA(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function iA(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}var vh=new WeakMap,t0=new WeakMap;function Eh(r){return t0.get(r)||1}function Jy(r){if(r!==Jo)throw new Error("invalid wNAF")}var Qo=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Jo;)t&Yn&&(n=n.add(o)),o=o.double(),t>>=Yn;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=xh(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=xh(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:h}=Xy(n,a,i);n=c,u?s=s.add(yi(d,t[h])):o=o.add(yi(f,t[l]))}return Jy(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=xh(e,this.bits);for(let i=0;i<s.windows&&n!==Jo;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=Xy(n,i,s);if(n=a,!l){let f=t[c];o=o.add(u?f.negate():f)}}return Jy(n),o}getPrecomputes(e,t,n){let o=vh.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),vh.set(t,o))),o}cached(e,t,n){let o=Eh(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=Eh(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){e0(t,this.bits),t0.set(e,t),vh.delete(e)}hasCache(e){return Eh(e)!==1}};function r0(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Jo||n>Jo;)t&Yn&&(s=s.add(o)),n&Yn&&(i=i.add(o)),o=o.double(),t>>=Yn,n>>=Yn;return{p1:s,p2:i}}function es(r,e,t,n){sA(t,r),iA(n,e);let o=t.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=r.ZERO,a=Ic(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=mn(c),u=new Array(Number(l)+1).fill(i),f=Math.floor((e.BITS-1)/c)*c,d=i;for(let h=f;h>=0;h-=c){u.fill(i);for(let m=0;m<s;m++){let w=n[m],y=Number(w>>BigInt(h)&l);u[y]=u[y].add(t[m])}let p=i;for(let m=u.length-1,w=i;m>0;m--)w=w.add(u[m]),p=p.add(w);if(d=d.add(p),h!==0)for(let m=0;m<c;m++)d=d.double()}return d}function Qy(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return yh(e),e}else return xt(r,{isLE:t})}function kc(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Jo))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Qy(e.p,t.Fp,n),s=Qy(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}var yn=BigInt(0),Be=BigInt(1),Ah=BigInt(2),aA=BigInt(8);function cA(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function lA(r,e={}){let t=kc("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;gn(e,{},{uvRatio:"function"});let a=Ah<<BigInt(o.BYTES*8)-Be,c=w=>n.create(w),l=e.uvRatio||((w,y)=>{try{return{isValid:!0,value:n.sqrt(n.div(w,y))}}catch{return{isValid:!1,value:yn}}});if(!cA(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(w,y,S=!1){let E=S?Be:yn;return mi("coordinate "+w,y,E,a),y}function f(w){if(!(w instanceof p))throw new Error("ExtendedPoint expected")}let d=Xo((w,y)=>{let{X:S,Y:E,Z:D}=w,M=w.is0();y==null&&(y=M?aA:n.inv(D));let z=c(S*y),W=c(E*y),C=n.mul(D,y);if(M)return{x:yn,y:Be};if(C!==Be)throw new Error("invZ was invalid");return{x:z,y:W}}),h=Xo(w=>{let{a:y,d:S}=s;if(w.is0())throw new Error("bad point: ZERO");let{X:E,Y:D,Z:M,T:z}=w,W=c(E*E),C=c(D*D),x=c(M*M),P=c(x*x),L=c(W*y),k=c(x*c(L+C)),A=c(P+c(S*c(W*C)));if(k!==A)throw new Error("bad point: equation left != right (1)");let v=c(E*D),b=c(M*z);if(v!==b)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,S,E,D){this.X=u("x",y),this.Y=u("y",S),this.Z=u("z",E,!0),this.T=u("t",D),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:S,y:E}=y||{};return u("x",S),u("y",E),new p(S,E,Be,c(S*E))}static fromBytes(y,S=!1){let E=n.BYTES,{a:D,d:M}=s;y=ph(bt(y,E,"point")),Dr(S,"zip215");let z=ph(y),W=y[E-1];z[E-1]=W&-129;let C=Lr(z),x=S?a:n.ORDER;mi("point.y",C,yn,x);let P=c(C*C),L=c(P-Be),k=c(M*P-D),{isValid:A,value:v}=l(L,k);if(!A)throw new Error("bad point: invalid y coordinate");let b=(v&Be)===Be,_=(W&128)!==0;if(!S&&v===yn&&_)throw new Error("bad point: x=0 and x_0=1");return _!==b&&(v=c(-v)),p.fromAffine({x:v,y:C})}static fromHex(y,S=!1){return p.fromBytes(ce("point",y),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,S=!0){return m.createCache(this,y),S||this.multiply(Ah),this}assertValidity(){h(this)}equals(y){f(y);let{X:S,Y:E,Z:D}=this,{X:M,Y:z,Z:W}=y,C=c(S*W),x=c(M*D),P=c(E*W),L=c(z*D);return C===x&&P===L}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=s,{X:S,Y:E,Z:D}=this,M=c(S*S),z=c(E*E),W=c(Ah*c(D*D)),C=c(y*M),x=S+E,P=c(c(x*x)-M-z),L=C+z,k=L-W,A=C-z,v=c(P*k),b=c(L*A),_=c(P*A),R=c(k*L);return new p(v,b,R,_)}add(y){f(y);let{a:S,d:E}=s,{X:D,Y:M,Z:z,T:W}=this,{X:C,Y:x,Z:P,T:L}=y,k=c(D*C),A=c(M*x),v=c(W*E*L),b=c(z*P),_=c((D+M)*(C+x)-k-A),R=b-v,V=b+v,F=c(A-S*k),$=c(_*R),G=c(V*F),Y=c(_*F),ge=c(R*V);return new p($,G,ge,Y)}subtract(y){return this.add(y.negate())}multiply(y){if(!o.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:S,f:E}=m.cached(this,y,D=>Rr(p,D));return Rr(p,[S,E])[0]}multiplyUnsafe(y,S=p.ZERO){if(!o.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===yn?p.ZERO:this.is0()||y===Be?this:m.unsafe(this,y,E=>Rr(p,E),S)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(y){return d(this,y)}clearCofactor(){return i===Be?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:S}=this.toAffine(),E=n.toBytes(S);return E[E.length-1]|=y&Be?128:0,E}toHex(){return Lt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(y){return Rr(p,y)}static msm(y,S){return es(p,o,y,S)}_setWindowSize(y){this.precompute(y)}toRawBytes(){return this.toBytes()}}p.BASE=new p(s.Gx,s.Gy,Be,c(s.Gx*s.Gy)),p.ZERO=new p(yn,Be,Be,yn),p.Fp=n,p.Fn=o;let m=new Qo(p,o.BITS);return p.BASE.precompute(8),p}var Tc=class{constructor(e){this.ep=e}static fromBytes(e){mh()}static fromHex(e){mh()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Lt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}};function uA(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');gn(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||fn,c=t.adjustScalarBytes||(x=>x),l=t.domain||((x,P,L)=>{if(Dr(L,"phflag"),P.length||L)throw new Error("Contexts/pre-hash are not supported");return x});function u(x){return i.create(Lr(x))}function f(x){let P=E.secretKey;x=ce("private key",x,P);let L=ce("hashed private key",e(x),2*P),k=c(L.slice(0,P)),A=L.slice(P,2*P),v=u(k);return{head:k,prefix:A,scalar:v}}function d(x){let{head:P,prefix:L,scalar:k}=f(x),A=o.multiply(k),v=A.toBytes();return{head:P,prefix:L,scalar:k,point:A,pointBytes:v}}function h(x){return d(x).pointBytes}function p(x=Uint8Array.of(),...P){let L=ot(...P);return u(e(l(L,ce("context",x),!!n)))}function m(x,P,L={}){x=ce("message",x),n&&(x=n(x));let{prefix:k,scalar:A,pointBytes:v}=d(P),b=p(L.context,k,x),_=o.multiply(b).toBytes(),R=p(L.context,_,v,x),V=i.create(b+R*A);if(!i.isValid(V))throw new Error("sign failed: invalid s");let F=ot(_,i.toBytes(V));return bt(F,E.signature,"result")}let w={zip215:!0};function y(x,P,L,k=w){let{context:A,zip215:v}=k,b=E.signature;x=ce("signature",x,b),P=ce("message",P),L=ce("publicKey",L,E.publicKey),v!==void 0&&Dr(v,"zip215"),n&&(P=n(P));let _=b/2,R=x.subarray(0,_),V=Lr(x.subarray(_,b)),F,$,G;try{F=r.fromBytes(L,v),$=r.fromBytes(R,v),G=o.multiplyUnsafe(V)}catch{return!1}if(!v&&F.isSmallOrder())return!1;let Y=p(A,$.toBytes(),F.toBytes(),P);return $.add(F.multiplyUnsafe(Y)).subtract(G).clearCofactor().is0()}let S=s.BYTES,E={secretKey:S,publicKey:S,signature:2*S,seed:S};function D(x=a(E.seed)){return bt(x,E.seed,"seed")}function M(x){let P=C.randomSecretKey(x);return{secretKey:P,publicKey:h(P)}}function z(x){return Br(x)&&x.length===i.BYTES}function W(x,P){try{return!!r.fromBytes(x,P)}catch{return!1}}let C={getExtendedPublicKey:d,randomSecretKey:D,isValidSecretKey:z,isValidPublicKey:W,toMontgomery(x){let{y:P}=r.fromBytes(x),L=E.publicKey,k=L===32;if(!k&&L!==57)throw new Error("only defined for 25519 and 448");let A=k?s.div(Be+P,Be-P):s.div(P-Be,P+Be);return s.toBytes(A)},toMontgomeryPriv(x){let P=E.secretKey;bt(x,P);let L=e(x.subarray(0,P));return c(L).subarray(0,P)},randomPrivateKey:D,precompute(x=8,P=r.BASE){return P.precompute(x,!1)}};return Object.freeze({keygen:M,getPublicKey:h,sign:m,verify:y,utils:C,Point:r,lengths:E})}function fA(r){let e={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=xt(e.n,r.nBitLength,!0),o={Fp:t,Fn:n,uvRatio:r.uvRatio},s={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:e,curveOpts:o,hash:r.hash,eddsaOpts:s}}function dA(r,e){let t=e.Point;return Object.assign({},e,{ExtendedPoint:t,CURVE:r,nBitLength:t.Fn.BITS,nByteLength:t.Fn.BYTES})}function n0(r){let{CURVE:e,curveOpts:t,hash:n,eddsaOpts:o}=fA(r),s=lA(e,t),i=uA(s,n,o);return dA(r,i)}var hA=BigInt(0),Or=BigInt(1),o0=BigInt(2),k4=BigInt(3),pA=BigInt(5),mA=BigInt(8),ts=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),wi={p:ts,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:mA,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function gA(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=ts,a=r*r%s*r%s,c=he(a,o0,s)*a%s,l=he(c,Or,s)*r%s,u=he(l,pA,s)*l%s,f=he(u,e,s)*u%s,d=he(f,t,s)*f%s,h=he(d,n,s)*d%s,p=he(h,o,s)*h%s,m=he(p,o,s)*h%s,w=he(m,e,s)*u%s;return{pow_p_5_8:he(w,o0,s)*r%s,b2:a}}function yA(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Sh=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ch(r,e){let t=ts,n=ve(e*e*e,t),o=ve(n*n*e,t),s=gA(r*o).pow_p_5_8,i=ve(r*n*s,t),a=ve(e*i*i,t),c=i,l=ve(i*Sh,t),u=a===r,f=a===ve(-r,t),d=a===ve(-r*Sh,t);return u&&(i=c),(f||d)&&(i=l),Nr(i,t)&&(i=ve(-i,t)),{isValid:u||f,value:i}}var wn=xt(wi.p,{isLE:!0}),wA=xt(wi.n,{isLE:!0}),bA={...wi,Fp:wn,hash:Sc,adjustScalarBytes:yA,uvRatio:Ch},Nt=n0(bA);var _h=Sh,xA=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),vA=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),EA=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),AA=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),s0=r=>Ch(Or,r),SA=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ih=r=>Nt.Point.Fp.create(Lr(r)&SA);function i0(r){let{d:e}=wi,t=ts,n=y=>wn.create(y),o=n(_h*r*r),s=n((o+Or)*EA),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:l}=Ch(s,a),u=n(l*r);Nr(u,t)||(u=n(-u)),c||(l=u),c||(i=o);let f=n(i*(o-Or)*AA-a),d=l*l,h=n((l+l)*a),p=n(f*xA),m=n(Or-d),w=n(Or+d);return new Nt.Point(n(h*w),n(m*p),n(p*w),n(h*m))}function _A(r){nt(r,64);let e=Ih(r.subarray(0,32)),t=i0(e),n=Ih(r.subarray(32,64)),o=i0(n);return new Mr(t.add(o))}var Mr=class r extends Tc{constructor(e){super(e)}static fromAffine(e){return new r(Nt.Point.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static hashToCurve(e){return _A(ce("ristrettoHash",e,64))}static fromBytes(e){nt(e,32);let{a:t,d:n}=wi,o=ts,s=D=>wn.create(D),i=Ih(e);if(!Uy(wn.toBytes(i),e)||Nr(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Or+t*a),l=s(Or-t*a),u=s(c*c),f=s(l*l),d=s(t*n*u-f),{isValid:h,value:p}=s0(s(d*f)),m=s(p*l),w=s(p*m*d),y=s((i+i)*m);Nr(y,o)&&(y=s(-y));let S=s(c*w),E=s(y*S);if(!h||Nr(E,o)||S===hA)throw new Error("invalid ristretto255 encoding 2");return new r(new Nt.Point(y,S,Or,E))}static fromHex(e){return r.fromBytes(ce("ristrettoHex",e,32))}static msm(e,t){return es(r,Nt.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,s=ts,i=w=>wn.create(w),a=i(i(n+t)*i(n-t)),c=i(e*t),l=i(c*c),{value:u}=s0(i(a*l)),f=i(u*a),d=i(u*c),h=i(f*d*o),p;if(Nr(o*h,s)){let w=i(t*_h),y=i(e*_h);e=w,t=y,p=i(f*vA)}else p=d;Nr(e*h,s)&&(t=i(-t));let m=i((n-t)*p);return Nr(m,s)&&(m=i(-m)),wn.toBytes(m)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=l=>wn.create(l),a=i(t*s)===i(n*o),c=i(n*s)===i(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Mr.BASE=new Mr(Nt.Point.BASE);Mr.ZERO=new Mr(Nt.Point.ZERO);Mr.Fp=wn;Mr.Fn=wA;var bi=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},xi=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Bc=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var a0={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Bc("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Ae=a0;var Zn=32,vt=64,kh=32;var rs,c0=(async()=>{try{return await Ae.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function l0(){let r=Nt.utils.randomPrivateKey(),e=Nt.getPublicKey(r);return{privateKey:BA(r,e),publicKey:e}}async function IA(r,e){let t;r.length===vt?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:O(r.subarray(32),"base64url"),d:O(t,"base64url"),ext:!0,key_ops:["sign"]},o=await Ae.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Ae.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function CA(r,e){let t=r.subarray(0,kh);return Nt.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function u0(r,e){return rs==null&&(rs=await c0),rs?IA(r,e):CA(r,e)}async function kA(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ae.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ae.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function TA(r,e,t){return Nt.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function f0(r,e,t){return rs==null&&(rs=await c0),rs?kA(r,e,t):TA(r,e,t)}function BA(r,e){let t=new Uint8Array(vt);for(let n=0;n<kh;n++)t[n]=r[n],t[kh+n]=e[n];return t}function ns(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var vi=class{type="Ed25519";raw;constructor(e){this.raw=ss(e,Zn)}toMultihash(){return Ze.digest(Dt(this))}toCID(){return H.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=f0(this.raw,t,e);return ns(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},os=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=ss(e,vt),this.publicKey=new vi(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=u0(this.raw,e);return ns(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function Th(r){if(r.length>vt){r=ss(r,vt+Zn);let n=r.subarray(0,vt),o=r.subarray(vt,r.length);return new os(n,o)}r=ss(r,vt);let e=r.subarray(0,vt),t=r.subarray(Zn);return new os(e,t)}function Bh(r){return r=ss(r,Zn),new vi(r)}async function h0(){let{privateKey:r,publicKey:e}=l0();return new os(r,e)}function ss(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new B(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var ue;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ue||(ue={}));var Ph;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ph||(Ph={}));(function(r){r.codec=()=>si(Ph)})(ue||(ue={}));var vr;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ue.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=ue.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Re(t,r.codec()),r.decode=(t,n)=>Ne(t,r.codec(),n)})(vr||(vr={}));var Ei;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),ue.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=ue.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Re(t,r.codec()),r.decode=(t,n)=>Ne(t,r.codec(),n)})(Ei||(Ei={}));function Jt(r){if(isNaN(r)||r<=0)throw new B("random bytes length must be a Number bigger than 0");return fn(r)}var Si={};Ee(Si,{MAX_RSA_KEY_SIZE:()=>Dh,generateRSAKeyPair:()=>Kh,jwkToJWKKeyPair:()=>y0,jwkToPkcs1:()=>NA,jwkToPkix:()=>Oh,jwkToRSAPrivateKey:()=>Vh,pkcs1MessageToJwk:()=>Nh,pkcs1MessageToRSAPrivateKey:()=>Pc,pkcs1ToJwk:()=>LA,pkcs1ToRSAPrivateKey:()=>Mh,pkixMessageToJwk:()=>Rh,pkixMessageToRSAPublicKey:()=>Fh,pkixToJwk:()=>RA,pkixToRSAPublicKey:()=>Uh});var is=Ac;var as=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Si.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return H.createV1(114,this._multihash)}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}verify(e,t,n){return g0(this.jwk,t,e,n)}},Ai=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Si.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}sign(e,t){return m0(this.jwk,e,t)}};var Dh=8192,Lh=18,PA=1062,DA=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function LA(r){let e=Pt(r);return Nh(e)}function Nh(r){return{n:O(r[1],"base64url"),e:O(r[2],"base64url"),d:O(r[3],"base64url"),p:O(r[4],"base64url"),q:O(r[5],"base64url"),dp:O(r[6],"base64url"),dq:O(r[7],"base64url"),qi:O(r[8],"base64url"),kty:"RSA"}}function NA(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new B("JWK was missing components");return Zt([rt(Uint8Array.from([0])),rt(T(r.n,"base64url")),rt(T(r.e,"base64url")),rt(T(r.d,"base64url")),rt(T(r.p,"base64url")),rt(T(r.q,"base64url")),rt(T(r.dp,"base64url")),rt(T(r.dq,"base64url")),rt(T(r.qi,"base64url"))]).subarray()}function RA(r){let e=Pt(r,{offset:0});return Rh(e)}function Rh(r){let e=Pt(r[1],{offset:0});return{kty:"RSA",n:O(e[0],"base64url"),e:O(e[1],"base64url")}}function Oh(r){if(r.n==null||r.e==null)throw new B("JWK was missing components");return Zt([DA,li(Zt([rt(T(r.n,"base64url")),rt(T(r.e,"base64url"))]))]).subarray()}function Mh(r){let e=Pt(r);return Pc(e)}function Pc(r){let e=Nh(r);return Vh(e)}function Uh(r,e){if(r.byteLength>=PA)throw new Co("Key size is too large");let t=Pt(r,{offset:0});return Fh(t,r,e)}function Fh(r,e,t){let n=Rh(r);if(t==null){let o=is(vr.encode({Type:ue.RSA,Data:e}));t=jt(Lh,o)}return new as(n,t)}function Vh(r){if(b0(r)>Dh)throw new B("Key size is too large");let e=y0(r),t=is(vr.encode({Type:ue.RSA,Data:Oh(e.publicKey)})),n=jt(Lh,t);return new Ai(e.privateKey,new as(e.publicKey,n))}async function Kh(r){if(r>Dh)throw new B("Key size is too large");let e=await w0(r),t=is(vr.encode({Type:ue.RSA,Data:Oh(e.publicKey)})),n=jt(Lh,t);return new Ai(e.privateKey,new as(e.publicKey,n))}function y0(r){if(r==null)throw new B("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function w0(r,e){let t=await Ae.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await OA(t,e);return{privateKey:n[0],publicKey:n[1]}}async function m0(r,e,t){let n=await Ae.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Ae.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function g0(r,e,t,n){let o=await Ae.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ae.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function OA(r,e){if(r.privateKey==null||r.publicKey==null)throw new B("Private and public key are required");let t=await Promise.all([Ae.get().subtle.exportKey("jwk",r.privateKey),Ae.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function b0(r){if(r.kty!=="RSA")throw new B("invalid key type");if(r.n==null)throw new B("invalid key modulus");return T(r.n,"base64url").length*8}var Dc=class extends Wo{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,jo(e);let n=ui(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),ut(s)}update(e){return Yo(this),this.iHash.update(e),this}digestInto(e){Yo(this),nt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},_i=(r,e,t)=>new Dc(r,e).update(t).digest();_i.create=(r,e)=>new Dc(r,e);var x0=(r,e)=>(r+(r>=0?e:-e)/v0)/e;function MA(r,e,t){let[[n,o],[s,i]]=e,a=x0(i*r,t),c=x0(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,f=l<Fr,d=u<Fr;f&&(l=-l),d&&(u=-u);let h=mn(Math.ceil(Ic(t)/2))+ls;if(l<Fr||l>=h||u<Fr||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}function Hh(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function $h(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Dr(t.lowS,"lowS"),Dr(t.prehash,"prehash"),t.format!==void 0&&Hh(t.format),t}var qh=class extends Error{constructor(e=""){super(e)}},Ur={Err:qh,_tlv:{encode:(r,e)=>{let{Err:t}=Ur;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=pi(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?pi(o.length/2|128):"";return pi(r)+s+o+e},decode(r,e){let{Err:t}=Ur,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Ur;if(r<Fr)throw new e("integer: negative integers are not allowed");let t=pi(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Ur;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Zo(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Ur,o=ce("signature",r),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Ur,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},Fr=BigInt(0),ls=BigInt(1),v0=BigInt(2),Lc=BigInt(3),UA=BigInt(4);function cs(r,e){let{BYTES:t}=r,n;if(typeof e=="bigint")n=e;else{let o=ce("private key",e);try{n=r.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!r.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function FA(r,e={}){let t=kc("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;gn(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=A0(n,o);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(k,A,v){let{x:b,y:_}=A.toAffine(),R=n.toBytes(b);if(Dr(v,"isCompressed"),v){u();let V=!n.isOdd(_);return ot(E0(V),R)}else return ot(Uint8Array.of(4),R,n.toBytes(_))}function d(k){bt(k,void 0,"Point");let{publicKey:A,publicKeyUncompressed:v}=l,b=k.length,_=k[0],R=k.subarray(1);if(b===A&&(_===2||_===3)){let V=n.fromBytes(R);if(!n.isValid(V))throw new Error("bad point: is not on curve, wrong x");let F=m(V),$;try{$=n.sqrt(F)}catch(ge){let le=ge instanceof Error?": "+ge.message:"";throw new Error("bad point: is not on curve, sqrt error"+le)}u();let G=n.isOdd($);return(_&1)===1!==G&&($=n.neg($)),{x:V,y:$}}else if(b===v&&_===4){let V=n.BYTES,F=n.fromBytes(R.subarray(0,V)),$=n.fromBytes(R.subarray(V,V*2));if(!w(F,$))throw new Error("bad point: is not on curve");return{x:F,y:$}}else throw new Error(`bad point: got length ${b}, expected compressed=${A} or uncompressed=${v}`)}let h=e.toBytes||f,p=e.fromBytes||d;function m(k){let A=n.sqr(k),v=n.mul(A,k);return n.add(n.add(v,n.mul(k,s.a)),s.b)}function w(k,A){let v=n.sqr(A),b=m(k);return n.eql(v,b)}if(!w(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(s.a,Lc),UA),S=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(y,S)))throw new Error("bad curve params: a or b");function E(k,A,v=!1){if(!n.isValid(A)||v&&n.is0(A))throw new Error(`bad point coordinate ${k}`);return A}function D(k){if(!(k instanceof x))throw new Error("ProjectivePoint expected")}function M(k){if(!c||!c.basises)throw new Error("no endo");return MA(k,c.basises,o.ORDER)}let z=Xo((k,A)=>{let{X:v,Y:b,Z:_}=k;if(n.eql(_,n.ONE))return{x:v,y:b};let R=k.is0();A==null&&(A=R?n.ONE:n.inv(_));let V=n.mul(v,A),F=n.mul(b,A),$=n.mul(_,A);if(R)return{x:n.ZERO,y:n.ZERO};if(!n.eql($,n.ONE))throw new Error("invZ was invalid");return{x:V,y:F}}),W=Xo(k=>{if(k.is0()){if(e.allowInfinityPoint&&!n.is0(k.Y))return;throw new Error("bad point: ZERO")}let{x:A,y:v}=k.toAffine();if(!n.isValid(A)||!n.isValid(v))throw new Error("bad point: x or y not field elements");if(!w(A,v))throw new Error("bad point: equation left != right");if(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function C(k,A,v,b,_){return v=new x(n.mul(v.X,k),v.Y,v.Z),A=yi(b,A),v=yi(_,v),A.add(v)}class x{constructor(A,v,b){this.X=E("x",A),this.Y=E("y",v,!0),this.Z=E("z",b),Object.freeze(this)}static CURVE(){return s}static fromAffine(A){let{x:v,y:b}=A||{};if(!A||!n.isValid(v)||!n.isValid(b))throw new Error("invalid affine point");if(A instanceof x)throw new Error("projective point not allowed");return n.is0(v)&&n.is0(b)?x.ZERO:new x(v,b,n.ONE)}static fromBytes(A){let v=x.fromAffine(p(bt(A,void 0,"point")));return v.assertValidity(),v}static fromHex(A){return x.fromBytes(ce("pointHex",A))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(A=8,v=!0){return L.createCache(this,A),v||this.multiply(Lc),this}assertValidity(){W(this)}hasEvenY(){let{y:A}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(A)}equals(A){D(A);let{X:v,Y:b,Z:_}=this,{X:R,Y:V,Z:F}=A,$=n.eql(n.mul(v,F),n.mul(R,_)),G=n.eql(n.mul(b,F),n.mul(V,_));return $&&G}negate(){return new x(this.X,n.neg(this.Y),this.Z)}double(){let{a:A,b:v}=s,b=n.mul(v,Lc),{X:_,Y:R,Z:V}=this,F=n.ZERO,$=n.ZERO,G=n.ZERO,Y=n.mul(_,_),ge=n.mul(R,R),le=n.mul(V,V),re=n.mul(_,R);return re=n.add(re,re),G=n.mul(_,V),G=n.add(G,G),F=n.mul(A,G),$=n.mul(b,le),$=n.add(F,$),F=n.sub(ge,$),$=n.add(ge,$),$=n.mul(F,$),F=n.mul(re,F),G=n.mul(b,G),le=n.mul(A,le),re=n.sub(Y,le),re=n.mul(A,re),re=n.add(re,G),G=n.add(Y,Y),Y=n.add(G,Y),Y=n.add(Y,le),Y=n.mul(Y,re),$=n.add($,Y),le=n.mul(R,V),le=n.add(le,le),Y=n.mul(le,re),F=n.sub(F,Y),G=n.mul(le,ge),G=n.add(G,G),G=n.add(G,G),new x(F,$,G)}add(A){D(A);let{X:v,Y:b,Z:_}=this,{X:R,Y:V,Z:F}=A,$=n.ZERO,G=n.ZERO,Y=n.ZERO,ge=s.a,le=n.mul(s.b,Lc),re=n.mul(v,R),ye=n.mul(b,V),_e=n.mul(_,F),lt=n.add(v,b),we=n.add(R,V);lt=n.mul(lt,we),we=n.add(re,ye),lt=n.sub(lt,we),we=n.add(v,_);let qe=n.add(R,F);return we=n.mul(we,qe),qe=n.add(re,_e),we=n.sub(we,qe),qe=n.add(b,_),$=n.add(V,F),qe=n.mul(qe,$),$=n.add(ye,_e),qe=n.sub(qe,$),Y=n.mul(ge,we),$=n.mul(le,_e),Y=n.add($,Y),$=n.sub(ye,Y),Y=n.add(ye,Y),G=n.mul($,Y),ye=n.add(re,re),ye=n.add(ye,re),_e=n.mul(ge,_e),we=n.mul(le,we),ye=n.add(ye,_e),_e=n.sub(re,_e),_e=n.mul(ge,_e),we=n.add(we,_e),re=n.mul(ye,we),G=n.add(G,re),re=n.mul(qe,we),$=n.mul(lt,$),$=n.sub($,re),re=n.mul(lt,ye),Y=n.mul(qe,Y),Y=n.add(Y,re),new x($,G,Y)}subtract(A){return this.add(A.negate())}is0(){return this.equals(x.ZERO)}multiply(A){let{endo:v}=e;if(!o.isValidNot0(A))throw new Error("invalid scalar: out of range");let b,_,R=V=>L.cached(this,V,F=>Rr(x,F));if(v){let{k1neg:V,k1:F,k2neg:$,k2:G}=M(A),{p:Y,f:ge}=R(F),{p:le,f:re}=R(G);_=ge.add(re),b=C(v.beta,Y,le,V,$)}else{let{p:V,f:F}=R(A);b=V,_=F}return Rr(x,[b,_])[0]}multiplyUnsafe(A){let{endo:v}=e,b=this;if(!o.isValid(A))throw new Error("invalid scalar: out of range");if(A===Fr||b.is0())return x.ZERO;if(A===ls)return b;if(L.hasCache(this))return this.multiply(A);if(v){let{k1neg:_,k1:R,k2neg:V,k2:F}=M(A),{p1:$,p2:G}=r0(x,b,R,F);return C(v.beta,$,G,_,V)}else return L.unsafe(b,A)}multiplyAndAddUnsafe(A,v,b){let _=this.multiplyUnsafe(v).add(A.multiplyUnsafe(b));return _.is0()?void 0:_}toAffine(A){return z(this,A)}isTorsionFree(){let{isTorsionFree:A}=e;return i===ls?!0:A?A(x,this):L.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:A}=e;return i===ls?this:A?A(x,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(A=!0){return Dr(A,"isCompressed"),this.assertValidity(),h(x,this,A)}toHex(A=!0){return Lt(this.toBytes(A))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(A=!0){return this.toBytes(A)}_setWindowSize(A){this.precompute(A)}static normalizeZ(A){return Rr(x,A)}static msm(A,v){return es(x,o,A,v)}static fromPrivateKey(A){return x.BASE.multiply(cs(o,A))}}x.BASE=new x(s.Gx,s.Gy,n.ONE),x.ZERO=new x(n.ZERO,n.ONE,n.ZERO),x.Fp=n,x.Fn=o;let P=o.BITS,L=new Qo(x,e.endo?Math.ceil(P/2):P);return x.BASE.precompute(8),x}function E0(r){return Uint8Array.of(r?2:3)}function A0(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function VA(r,e={}){let{Fn:t}=r,n=e.randomBytes||fn,o=Object.assign(A0(r.Fp,t),{seed:wh(t.ORDER)});function s(h){try{return!!cs(t,h)}catch{return!1}}function i(h,p){let{publicKey:m,publicKeyUncompressed:w}=o;try{let y=h.length;return p===!0&&y!==m||p===!1&&y!==w?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return bh(bt(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(cs(t,h)).toBytes(p)}function l(h){let p=a(h);return{secretKey:p,publicKey:c(p)}}function u(h){if(typeof h=="bigint")return!1;if(h instanceof r)return!0;let{secretKey:p,publicKey:m,publicKeyUncompressed:w}=o;if(t.allowedLengths||p===m)return;let y=ce("key",h).length;return y===m||y===w}function f(h,p,m=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");let w=cs(t,h);return r.fromHex(p).multiply(w).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:l,Point:r,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>cs(t,h),precompute(h=8,p=r.BASE){return p.precompute(h,!1)}},lengths:o})}function KA(r,e,t={}){jo(e),gn(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=t.randomBytes||fn,o=t.hmac||((v,...b)=>_i(e,v,ot(...b))),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h}=VA(r,t),p={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function w(v){let b=a>>ls;return v>b}function y(v,b){if(!i.isValidNot0(b))throw new Error(`invalid signature ${v}: out of range 1..Point.Fn.ORDER`);return b}function S(v,b){Hh(b);let _=h.signature,R=b==="compact"?_:b==="recovered"?_+1:void 0;return bt(v,R,`${b} signature`)}class E{constructor(b,_,R){this.r=y("r",b),this.s=y("s",_),R!=null&&(this.recovery=R),Object.freeze(this)}static fromBytes(b,_=m){S(b,_);let R;if(_==="der"){let{r:G,s:Y}=Ur.toSig(bt(b));return new E(G,Y)}_==="recovered"&&(R=b[0],_="compact",b=b.subarray(1));let V=i.BYTES,F=b.subarray(0,V),$=b.subarray(V,V*2);return new E(i.fromBytes(F),i.fromBytes($),R)}static fromHex(b,_){return this.fromBytes(qn(b),_)}addRecoveryBit(b){return new E(this.r,this.s,b)}recoverPublicKey(b){let _=s.ORDER,{r:R,s:V,recovery:F}=this;if(F==null||![0,1,2,3].includes(F))throw new Error("recovery id invalid");if(a*v0<_&&F>1)throw new Error("recovery id is ambiguous for h>1 curve");let G=F===2||F===3?R+a:R;if(!s.isValid(G))throw new Error("recovery id 2 or 3 invalid");let Y=s.toBytes(G),ge=r.fromBytes(ot(E0((F&1)===0),Y)),le=i.inv(G),re=M(ce("msgHash",b)),ye=i.create(-re*le),_e=i.create(V*le),lt=r.BASE.multiplyUnsafe(ye).add(ge.multiplyUnsafe(_e));if(lt.is0())throw new Error("point at infinify");return lt.assertValidity(),lt}hasHighS(){return w(this.s)}toBytes(b=m){if(Hh(b),b==="der")return qn(Ur.hexFromSig(this));let _=i.toBytes(this.r),R=i.toBytes(this.s);if(b==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ot(Uint8Array.of(this.recovery),_,R)}return ot(_,R)}toHex(b){return Lt(this.toBytes(b))}assertValidity(){}static fromCompact(b){return E.fromBytes(ce("sig",b),"compact")}static fromDER(b){return E.fromBytes(ce("sig",b),"der")}normalizeS(){return this.hasHighS()?new E(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Lt(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Lt(this.toBytes("compact"))}}let D=t.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");let _=Zo(b),R=b.length*8-c;return R>0?_>>BigInt(R):_},M=t.bits2int_modN||function(b){return i.create(D(b))},z=mn(c);function W(v){return mi("num < 2^"+c,v,Fr,z),i.toBytes(v)}function C(v,b){return bt(v,void 0,"message"),b?bt(e(v),void 0,"prehashed message"):v}function x(v,b,_){if(["recovered","canonical"].some(ye=>ye in _))throw new Error("sign() legacy options not supported");let{lowS:R,prehash:V,extraEntropy:F}=$h(_,p);v=C(v,V);let $=M(v),G=cs(i,b),Y=[W(G),W($)];if(F!=null&&F!==!1){let ye=F===!0?n(h.secretKey):F;Y.push(ce("extraEntropy",ye))}let ge=ot(...Y),le=$;function re(ye){let _e=D(ye);if(!i.isValidNot0(_e))return;let lt=i.inv(_e),we=r.BASE.multiply(_e).toAffine(),qe=i.create(we.x);if(qe===Fr)return;let Ma=i.create(lt*i.create(le+qe*G));if(Ma===Fr)return;let _g=(we.x===qe?0:2)|Number(we.y&ls),Ig=Ma;return R&&w(Ma)&&(Ig=i.neg(Ma),_g^=1),new E(qe,Ig,_g)}return{seed:ge,k2sig:re}}function P(v,b,_={}){v=ce("message",v);let{seed:R,k2sig:V}=x(v,b,_);return Vy(e.outputLen,i.BYTES,o)(R,V)}function L(v){let b,_=typeof v=="string"||Br(v),R=!_&&v!==null&&typeof v=="object"&&typeof v.r=="bigint"&&typeof v.s=="bigint";if(!_&&!R)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(R)b=new E(v.r,v.s);else if(_){try{b=E.fromBytes(ce("sig",v),"der")}catch(V){if(!(V instanceof Ur.Err))throw V}if(!b)try{b=E.fromBytes(ce("sig",v),"compact")}catch{return!1}}return b||!1}function k(v,b,_,R={}){let{lowS:V,prehash:F,format:$}=$h(R,p);if(_=ce("publicKey",_),b=C(ce("message",b),F),"strict"in R)throw new Error("options.strict was renamed to lowS");let G=$===void 0?L(v):E.fromBytes(ce("sig",v),$);if(G===!1)return!1;try{let Y=r.fromBytes(_);if(V&&G.hasHighS())return!1;let{r:ge,s:le}=G,re=M(b),ye=i.inv(le),_e=i.create(re*ye),lt=i.create(ge*ye),we=r.BASE.multiplyUnsafe(_e).add(Y.multiplyUnsafe(lt));return we.is0()?!1:i.create(we.x)===ge}catch{return!1}}function A(v,b,_={}){let{prehash:R}=$h(_,p);return b=C(b,R),E.fromBytes(v,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h,Point:r,sign:P,verify:k,recoverPublicKey:A,Signature:E,hash:e})}function $A(r){let e={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=xt(e.n,{BITS:r.nBitLength,allowedLengths:n,modFromBytes:r.wrapPrivateKey}),s={Fp:t,Fn:o,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:e,curveOpts:s}}function HA(r){let{CURVE:e,curveOpts:t}=$A(r),n={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:e,curveOpts:t,hash:r.hash,ecdsaOpts:n}}function qA(r,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},r,Cc(t.Fn.ORDER,t.Fn.BITS))})}function S0(r){let{CURVE:e,curveOpts:t,hash:n,ecdsaOpts:o}=HA(r),s=FA(e,t),i=KA(s,n,o);return qA(r,i)}function _0(r,e){let t=n=>S0({...r,hash:n});return{...t(e),create:t}}var Gh={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},zA={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var I0=BigInt(2);function GA(r){let e=Gh.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=he(u,t,e)*u%e,d=he(f,t,e)*u%e,h=he(d,I0,e)*l%e,p=he(h,o,e)*h%e,m=he(p,s,e)*p%e,w=he(m,a,e)*m%e,y=he(w,c,e)*w%e,S=he(y,a,e)*m%e,E=he(S,t,e)*u%e,D=he(E,i,e)*p%e,M=he(D,n,e)*l%e,z=he(M,I0,e);if(!zh.eql(zh.sqr(z),r))throw new Error("Cannot find square root");return z}var zh=xt(Gh.p,{sqrt:GA}),Qt=_0({...Gh,Fp:zh,lowS:!0,endo:zA},Ac);var C0=32;function k0(r,e,t){let n=Yt.digest(e instanceof Uint8Array?e:e.subarray());if(ns(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),Qt.sign(o,r).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new bi(String(o))});try{return Qt.sign(n.digest,r).toDERRawBytes()}catch(o){throw new bi(String(o))}}function T0(r,e,t,n){let o=Yt.digest(t instanceof Uint8Array?t:t.subarray());if(ns(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Qt.verify(e,s,r))).catch(s=>{throw s.name==="AbortError"?s:new xi(String(s))});try{return n?.signal?.throwIfAborted(),Qt.verify(e,o.digest,r)}catch(s){throw new xi(String(s))}}var Ii=class{type="secp256k1";raw;_key;constructor(e){this._key=D0(e),this.raw=B0(this._key)}toMultihash(){return Ze.digest(Dt(this))}toCID(){return H.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}verify(e,t,n){return T0(this._key,t,e,n)}},Ci=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=P0(e),this.publicKey=new Ii(t??L0(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Z(this.raw,e.raw)}sign(e,t){return k0(this.raw,e,t)}};function Wh(r){return new Ci(r)}function jh(r){return new Ii(r)}async function N0(){let r=WA();return new Ci(r)}function B0(r){return Qt.ProjectivePoint.fromHex(r).toRawBytes(!0)}function P0(r){try{return Qt.getPublicKey(r,!0),r}catch(e){throw new zs(String(e))}}function D0(r){try{return Qt.ProjectivePoint.fromHex(r),r}catch(e){throw new Co(String(e))}}function L0(r){try{return Qt.getPublicKey(r,!0)}catch(e){throw new zs(String(e))}}function WA(){return Qt.utils.randomPrivateKey()}async function Nc(r,e){if(r==="Ed25519")return h0();if(r==="secp256k1")return N0();if(r==="RSA")return Kh(jA(e));if(r==="ECDSA")return Ey(YA(e));throw new qt}function bn(r,e){let{Type:t,Data:n}=vr.decode(r),o=n??new Uint8Array;switch(t){case ue.RSA:return Uh(o,e);case ue.Ed25519:return Bh(o);case ue.secp256k1:return jh(o);case ue.ECDSA:return ih(o);default:throw new qt}}function Rc(r){let{Type:e,Data:t}=vr.decode(r.digest),n=t??new Uint8Array;switch(e){case ue.Ed25519:return Bh(n);case ue.secp256k1:return jh(n);case ue.ECDSA:return ih(n);default:throw new qt}}function Dt(r){return vr.encode({Type:ue[r.type],Data:r.raw})}function R0(r){let e=Ei.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case ue.RSA:return Mh(t);case ue.Ed25519:return Th(t);case ue.secp256k1:return Wh(t);case ue.ECDSA:return yy(t);default:throw new qt}}function O0(r){if(r.byteLength===vt)return Th(r);if(r.byteLength===C0)return Wh(r);let e=Pt(r),t=e[2]?.[0];if(t===cy||t===ly||t===uy)return sh(e);if(e.length>8)return Pc(e);throw new B("Could not extract private key from raw bytes")}function Xn(r){return Ei.encode({Type:ue[r.type],Data:r.raw})}function jA(r){return r==null?2048:parseInt(r,10)}function YA(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new B("Unsupported curve, should be P-256, P-384 or P-521")}var M0=Symbol.for("nodejs.util.inspect.custom"),ZA=114,ki=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Fa]=!0;toString(){return this.string==null&&(this.string=ie.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return H.createV1(ZA,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Z(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Z(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[M0](){return`PeerId(${this.toString()})`}},Ti=class extends ki{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Bi=class extends ki{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Pi=class extends ki{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},XA=2336,Di=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ze.digest(T(this.url))}[M0](){return`PeerId(${this.url})`}[Fa]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return H.createV1(XA,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=O(e)),e.toString()===this.toString())}};var JA=114,U0=2336;function Rt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=wt(ie.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Jn(H.parse(r));if(e==null)throw new B('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=wt(e.decode(r))}return us(t)}function Yh(r){if(r.type==="Ed25519")return new Bi({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Pi({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Ti({multihash:r.toCID().multihash,publicKey:r});throw new qt}function F0(r){return Yh(r.publicKey)}function us(r){if(eS(r))return new Ti({multihash:r});if(QA(r))try{let e=Rc(r);if(e.type==="Ed25519")return new Bi({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Pi({multihash:r,publicKey:e})}catch{let t=O(r.digest);return new Di(new URL(t))}throw new cn("Supplied PeerID Multihash is invalid")}function Jn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==JA&&r.code!==U0)throw new Ka("Supplied PeerID CID is invalid");if(r.code===U0){let e=O(r.multihash.digest);return new Di(new URL(e))}return us(r.multihash)}function QA(r){return r.code===Ze.code}function eS(r){return r.code===Yt.code}function Qn(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function Oc(r){let e=wt(ie.decode(`z${r}`));return us(e)}var Ot=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Qn(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Qn(this.map.values(),e=>e.key)}values(){return Qn(this.map.values(),e=>e.value)}get size(){return this.map.size}};var eo=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Qn(this.set.entries(),e=>{let t=Oc(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=Oc(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Qn(this.set.values(),e=>Oc(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};function V0(r,e,t,n){jo(r);let o=Cy({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(Tr(s),Tr(i),Tr(a),s<1)throw new Error("iterations (c) should be >= 1");let c=ah(e),l=ah(t),u=new Uint8Array(i),f=_i.create(r,c),d=f._cloneInto().update(l);return{c:s,dkLen:i,asyncTick:a,DK:u,PRF:f,PRFSalt:d}}function K0(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),ut(o),t}function $0(r,e,t,n){let{c:o,dkLen:s,DK:i,PRF:a,PRFSalt:c}=V0(r,e,t,n),l,u=new Uint8Array(4),f=Hn(u),d=new Uint8Array(a.outputLen);for(let h=1,p=0;p<s;h++,p+=a.outputLen){let m=i.subarray(p,p+a.outputLen);f.setInt32(0,h,!1),(l=c._cloneInto(l)).update(u).digestInto(d),m.set(d.subarray(0,m.length));for(let w=1;w<o;w++){a._cloneInto(l).update(d).digestInto(d);for(let y=0;y<m.length;y++)m[y]^=d[y]}}return K0(a,c,i,l,d)}async function Mc(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=V0(r,e,t,n),u,f=new Uint8Array(4),d=Hn(f),h=new Uint8Array(c.outputLen);for(let p=1,m=0;m<s;p++,m+=c.outputLen){let w=a.subarray(m,m+c.outputLen);d.setInt32(0,p,!1),(u=l._cloneInto(u)).update(f).digestInto(h),w.set(h.subarray(0,w.length)),await Iy(o-1,i,()=>{c._cloneInto(u).update(h).digestInto(h);for(let y=0;y<w.length;y++)w[y]^=h[y]})}return K0(c,l,a,u,h)}var Li=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),xn=new Uint32Array(80),Uc=class extends zn{constructor(){super(64,20,8,!1),this.A=Li[0]|0,this.B=Li[1]|0,this.C=Li[2]|0,this.D=Li[3]|0,this.E=Li[4]|0}get(){let{A:e,B:t,C:n,D:o,E:s}=this;return[e,t,n,o,s]}set(e,t,n,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0}process(e,t){for(let c=0;c<16;c++,t+=4)xn[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)xn[c]=gc(xn[c-3]^xn[c-8]^xn[c-14]^xn[c-16],1);let{A:n,B:o,C:s,D:i,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=wc(o,s,i),u=1518500249):c<40?(l=o^s^i,u=1859775393):c<60?(l=bc(o,s,i),u=2400959708):(l=o^s^i,u=3395469782);let f=gc(n,5)+l+a+u+xn[c]|0;a=i,i=s,s=gc(o,30),o=n,n=f}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,this.set(n,o,s,i,a)}roundClean(){ut(xn)}destroy(){this.set(0,0,0,0,0),ut(this.buffer)}},H0=fi(()=>new Uc);var q0=H0;var fs=Sc;var z0={sha1:q0,"sha2-256":is,"sha2-512":fs};function Ni(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(z0).join(" / ");throw new B(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let s=z0[o],i=$0(s,r,e,{c:t,dkLen:n});return Ye.encode(i).substring(1)}var Zh={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},G0={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},W0=new globalThis.TextEncoder;function tS(r,e){let t=Zh[e],n=G0[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function rS(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Zh[e],o=G0[e],s=r;for(;s.length>0;){let i=W0.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Xh(r,{size:e=32,utf8Buffer:t}={}){if(!Zh[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return rS(r,e,t);r=W0.encode(r)}return tS(r,e)}var Ri={hash:r=>Number(Xh(r,{size:32})),hashV:(r,e)=>nS(Ri.hash(r,e))};function nS(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),T(e,"base16")}var Jh=64,er=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Jh)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=be(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?Z(this.fp,e.fp):!1}};function to(r,e){return Math.floor(Math.random()*(e-r))+r}var ro=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof er))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof er))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof er))throw new TypeError("Invalid Fingerprint");let t=to(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof er))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var oS=500,Oi=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??Ri,this.seed=e.seed??to(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=T(e));let t=new er(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new ro(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new ro(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[to(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new ro(this.bucketSize));for(let a=0;a<oS;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new ro(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=T(e));let t=new er(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=T(e));let t=new er(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},sS={1:.5,2:.84,4:.95,8:.98};function iS(r=.001){return r>.002?2:r>1e-5?4:8}function j0(r,e=.001){let t=iS(e),n=sS[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Jh);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var Fc=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??Ri,this.seed=e.seed??to(0,Math.pow(2,10)),this.filterSeries=[new Oi({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=T(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Oi({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function no(r,e=.001,t){return new Fc({...j0(r,e),...t??{}})}var Qh=class extends Ot{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function ep(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Qh({name:e,metrics:t}):n=new Ot,n}function aS(r,e){try{if(typeof r=="string"&&r.length>0)return cS(r);if(typeof r=="number"&&isFinite(r))return e?.long?uS(r):lS(r);throw new Error("Value is not a string or number.")}catch(t){let n=fS(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function cS(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Kc=aS;function lS(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function uS(r){let e=Math.abs(r);return e>=864e5?Vc(r,e,864e5,"day"):e>=36e5?Vc(r,e,36e5,"hour"):e>=6e4?Vc(r,e,6e4,"minute"):e>=1e3?Vc(r,e,1e3,"second"):`${r} ms`}function Vc(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function fS(r){return typeof r=="object"&&r!==null&&"message"in r}function tp(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=Kc,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,d=null,h,p;function m(...w){if(!m.enabled)return;let y=m,S=Number(new Date),E=S-(f||S);y.diff=E,y.prev=f,y.curr=S,f=S,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let D=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(z,W)=>{if(z==="%%")return"%";D++;let C=t.formatters[W];if(typeof C=="function"){let x=w[D];z=C.call(y,x),w.splice(D,1),D--}return z}),t.formatArgs.call(y,w),(y.log||t.log).apply(y,w)}return m.namespace=u,m.useColors=t.useColors(),m.color=t.selectColor(u),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(u)),p),set:w=>{d=w}}),typeof t.init=="function"&&t.init(m),m}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function s(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(u))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var $c=wS(),dS=["#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 hS(){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 pS(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Kc(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var mS=console.debug??console.log??(()=>{});function gS(r){try{r?$c?.setItem("debug",r):$c?.removeItem("debug")}catch{}}function yS(){let r;try{r=$c?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function wS(){try{return localStorage}catch{}}function bS(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Y0=tp({formatArgs:pS,save:gS,load:yS,useColors:hS,setupFormatters:bS,colors:dS,storage:$c,log:mS});var ft=Y0;ft.formatters.b=r=>r==null?"undefined":ie.baseEncode(r);ft.formatters.t=r=>r==null?"undefined":ke.baseEncode(r);ft.formatters.m=r=>r==null?"undefined":Ye.baseEncode(r);ft.formatters.p=r=>r==null?"undefined":r.toString();ft.formatters.c=r=>r==null?"undefined":r.toString();ft.formatters.k=r=>r==null?"undefined":r.toString();ft.formatters.a=r=>r==null?"undefined":r.toString();ft.formatters.e=r=>r==null?"undefined":Z0(r.stack)??Z0(r.message)??r.toString();function xS(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function vn(){return{forComponent(r){return Et(r)}}}function Et(r){let e=xS(`${r}:trace`);return ft.enabled(`${r}:trace`)&&ft.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=ft(`${r}:trace`)),Object.assign(ft(r),{error:ft(`${r}:error`),trace:e})}function Z0(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var np=nn(J0(),1);var Ui=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},op=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Q0=r=>globalThis.DOMException===void 0?new op(r):new DOMException(r),ew=r=>{let e=r.reason===void 0?Q0("This operation was aborted."):r.reason;return e instanceof Error?e:Q0(e)};function sp(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a,l=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&f(ew(h)),a=()=>{f(ew(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new Ui;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){f(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${t} milliseconds`,f(d))},t),(async()=>{try{u(await r)}catch(h){f(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}function ip(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Fi=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=ip(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}setPriority(e,t){let n=this.#e.findIndex(s=>s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var oo=class extends np.default{#e;#t;#r=0;#a;#i;#l=0;#o;#u;#n;#m;#s=0;#f;#c;#g;#b=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Fi,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#i=e.interval,this.#n=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#c=e.autoStart===!1}get#x(){return this.#t||this.#r<this.#a}get#v(){return this.#s<this.#f}#E(){this.#s--,this.#d(),this.emit("next")}#A(){this.#w(),this.#y(),this.#u=void 0}get#S(){let e=Date.now();if(this.#o===void 0){let t=this.#l-e;if(t<0)this.#r=this.#e?this.#s:0;else return this.#u===void 0&&(this.#u=setTimeout(()=>{this.#A()},t)),!0}return!1}#d(){if(this.#n.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#c){let e=!this.#S;if(this.#x&&this.#v){let t=this.#n.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#o!==void 0||(this.#o=setInterval(()=>{this.#w()},this.#i),this.#l=Date.now()+this.#i)}#w(){this.#r===0&&this.#s===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#r=this.#e?this.#s:0,this.#h()}#h(){for(;this.#d(););}get concurrency(){return this.#f}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#f=e,this.#h()}async#_(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#n.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#b++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#s++,this.#r++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=sp(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#_(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof Ui&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#E()}},t),this.emit("add"),this.#d()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#c?(this.#c=!1,this.#h(),this):this}pause(){this.#c=!0}clear(){this.#n=new this.#m}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#s===0&&this.#n.size===0||await this.#p("idle")}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#c}};function qc(r){let e=[At.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var ap=60;function zc(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:At[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:At[e.type],TTL:e.TTL??e.ttl??ap,data:e.data instanceof Uint8Array?O(e.data):e.data}))}}var AS=4;function cp(r,e={}){let t=new oo({concurrency:e.queryConcurrency??AS});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),qc(o.types).forEach(a=>{s.append("type",At[a])}),o.onProgress?.(new j("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=zc(await a.json());return o.onProgress?.(new j("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function tw(){return[cp("https://cloudflare-dns.com/dns-query"),cp("https://dns.google/resolve")]}var ow=nn(nw(),1);var lp=class{lru;constructor(e){this.lru=(0,ow.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return zc({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:At[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??ap)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function sw(r){return new lp(r)}var SS=1e3,Gc=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=sw(e.cacheSize??SS),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=tw())}async query(e,t={}){let n=qc(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new j("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new j("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var At;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(At||(At={}));function Wc(r={}){return new Gc(r)}var _S=["string","number","bigint","symbol"],IS=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function iw(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(_S.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(CS(r))return"Buffer";let t=kS(r);return t||"Object"}function CS(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function kS(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(IS.includes(e))return e}var g=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};g.uint=new g(0,"uint",!0);g.negint=new g(1,"negint",!0);g.bytes=new g(2,"bytes",!0);g.string=new g(3,"string",!0);g.array=new g(4,"array",!1);g.map=new g(5,"map",!1);g.tag=new g(6,"tag",!1);g.float=new g(7,"float",!0);g.false=new g(7,"false",!0);g.true=new g(7,"true",!0);g.null=new g(7,"null",!0);g.undefined=new g(7,"undefined",!0);g.break=new g(7,"break",!0);var I=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var ds=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",TS=new TextDecoder,BS=new TextEncoder;function jc(r){return ds&&globalThis.Buffer.isBuffer(r)}function Vi(r){return r instanceof Uint8Array?jc(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var uw=ds?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):cw(r,e,t):(r,e,t)=>t-e>64?TS.decode(r.subarray(e,t)):cw(r,e,t),Yc=ds?r=>r.length>64?globalThis.Buffer.from(r):aw(r):r=>r.length>64?BS.encode(r):aw(r),Er=r=>Uint8Array.from(r),hs=ds?(r,e,t)=>jc(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),fw=ds?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Vi(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},dw=ds?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function hw(r,e){if(jc(r)&&jc(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function aw(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function cw(r,e,t){let n=[];for(;e<t;){let o=r[e],s=null,i=o>239?4:o>223?3:o>191?2:1;if(e+i<=t){let a,c,l,u;switch(i){case 1:o<128&&(s=o);break;case 2:a=r[e+1],(a&192)===128&&(u=(o&31)<<6|a&63,u>127&&(s=u));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(u=(o&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(s=u))}}s===null?(s=65533,i=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),e+=i}return up(n)}var lw=4096;function up(r){let e=r.length;if(e<=lw)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=lw));return t}var PS=256,Ki=class{constructor(e=PS){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=dw(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=hs(n,0,this.cursor)}else t=fw(this.chunks,this.cursor);return e&&this.reset(),t}};var K="CBOR decode error:",Vr="CBOR encode error:",$i=[];$i[23]=1;$i[24]=2;$i[25]=3;$i[26]=5;$i[27]=9;function Kr(r,e,t){if(r.length-e<t)throw new Error(`${K} not enough data for type`)}var Pe=[24,256,65536,4294967296,BigInt("18446744073709551616")];function St(r,e,t){Kr(r,e,1);let n=r[e];if(t.strict===!0&&n<Pe[0])throw new Error(`${K} integer encoded in more bytes than necessary (strict decode)`);return n}function _t(r,e,t){Kr(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Pe[1])throw new Error(`${K} integer encoded in more bytes than necessary (strict decode)`);return n}function It(r,e,t){Kr(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Pe[2])throw new Error(`${K} integer encoded in more bytes than necessary (strict decode)`);return n}function Ct(r,e,t){Kr(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],s=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&s<Pe[3])throw new Error(`${K} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${K} integers outside of the safe integer range are not supported`)}function pw(r,e,t,n){return new I(g.uint,St(r,e+1,n),2)}function mw(r,e,t,n){return new I(g.uint,_t(r,e+1,n),3)}function gw(r,e,t,n){return new I(g.uint,It(r,e+1,n),5)}function yw(r,e,t,n){return new I(g.uint,Ct(r,e+1,n),9)}function Mt(r,e){return Ue(r,0,e.value)}function Ue(r,e,t){if(t<Pe[0]){let n=Number(t);r.push([e|n])}else if(t<Pe[1]){let n=Number(t);r.push([e|24,n])}else if(t<Pe[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Pe[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<Pe[4]){let o=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=s&255,s=s>>8,o[7]=s&255,s=s>>8,o[6]=s&255,s=s>>8,o[5]=s&255,o[4]=i&255,i=i>>8,o[3]=i&255,i=i>>8,o[2]=i&255,i=i>>8,o[1]=i&255,r.push(o)}else throw new Error(`${K} encountered BigInt larger than allowable range`)}}Mt.encodedSize=function(e){return Ue.encodedSize(e.value)};Ue.encodedSize=function(e){return e<Pe[0]?1:e<Pe[1]?2:e<Pe[2]?3:e<Pe[3]?5:9};Mt.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function ww(r,e,t,n){return new I(g.negint,-1-St(r,e+1,n),2)}function bw(r,e,t,n){return new I(g.negint,-1-_t(r,e+1,n),3)}function xw(r,e,t,n){return new I(g.negint,-1-It(r,e+1,n),5)}var fp=BigInt(-1),vw=BigInt(1);function Ew(r,e,t,n){let o=Ct(r,e+1,n);if(typeof o!="bigint"){let s=-1-o;if(s>=Number.MIN_SAFE_INTEGER)return new I(g.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${K} integers outside of the safe integer range are not supported`);return new I(g.negint,fp-BigInt(o),9)}function Zc(r,e){let t=e.value,n=typeof t=="bigint"?t*fp-vw:t*-1-1;Ue(r,e.type.majorEncoded,n)}Zc.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*fp-vw:t*-1-1;return n<Pe[0]?1:n<Pe[1]?2:n<Pe[2]?3:n<Pe[3]?5:9};Zc.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Hi(r,e,t,n){Kr(r,e,t+n);let o=hs(r,e+t,e+t+n);return new I(g.bytes,o,t+n)}function Aw(r,e,t,n){return Hi(r,e,1,t)}function Sw(r,e,t,n){return Hi(r,e,2,St(r,e+1,n))}function _w(r,e,t,n){return Hi(r,e,3,_t(r,e+1,n))}function Iw(r,e,t,n){return Hi(r,e,5,It(r,e+1,n))}function Cw(r,e,t,n){let o=Ct(r,e+1,n);if(typeof o=="bigint")throw new Error(`${K} 64-bit integer bytes lengths not supported`);return Hi(r,e,9,o)}function Xc(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===g.string?Yc(r.value):r.value),r.encodedBytes}function ps(r,e){let t=Xc(e);Ue(r,e.type.majorEncoded,t.length),r.push(t)}ps.encodedSize=function(e){let t=Xc(e);return Ue.encodedSize(t.length)+t.length};ps.compareTokens=function(e,t){return LS(Xc(e),Xc(t))};function LS(r,e){return r.length<e.length?-1:r.length>e.length?1:hw(r,e)}function qi(r,e,t,n,o){let s=t+n;Kr(r,e,s);let i=new I(g.string,uw(r,e+t,e+s),s);return o.retainStringBytes===!0&&(i.byteValue=hs(r,e+t,e+s)),i}function kw(r,e,t,n){return qi(r,e,1,t,n)}function Tw(r,e,t,n){return qi(r,e,2,St(r,e+1,n),n)}function Bw(r,e,t,n){return qi(r,e,3,_t(r,e+1,n),n)}function Pw(r,e,t,n){return qi(r,e,5,It(r,e+1,n),n)}function Dw(r,e,t,n){let o=Ct(r,e+1,n);if(typeof o=="bigint")throw new Error(`${K} 64-bit integer string lengths not supported`);return qi(r,e,9,o,n)}var Lw=ps;function ms(r,e,t,n){return new I(g.array,n,t)}function Nw(r,e,t,n){return ms(r,e,1,t)}function Rw(r,e,t,n){return ms(r,e,2,St(r,e+1,n))}function Ow(r,e,t,n){return ms(r,e,3,_t(r,e+1,n))}function Mw(r,e,t,n){return ms(r,e,5,It(r,e+1,n))}function Uw(r,e,t,n){let o=Ct(r,e+1,n);if(typeof o=="bigint")throw new Error(`${K} 64-bit integer array lengths not supported`);return ms(r,e,9,o)}function Fw(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${K} indefinite length items not allowed`);return ms(r,e,1,1/0)}function Jc(r,e){Ue(r,g.array.majorEncoded,e.value)}Jc.compareTokens=Mt.compareTokens;Jc.encodedSize=function(e){return Ue.encodedSize(e.value)};function gs(r,e,t,n){return new I(g.map,n,t)}function Vw(r,e,t,n){return gs(r,e,1,t)}function Kw(r,e,t,n){return gs(r,e,2,St(r,e+1,n))}function $w(r,e,t,n){return gs(r,e,3,_t(r,e+1,n))}function Hw(r,e,t,n){return gs(r,e,5,It(r,e+1,n))}function qw(r,e,t,n){let o=Ct(r,e+1,n);if(typeof o=="bigint")throw new Error(`${K} 64-bit integer map lengths not supported`);return gs(r,e,9,o)}function zw(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${K} indefinite length items not allowed`);return gs(r,e,1,1/0)}function Qc(r,e){Ue(r,g.map.majorEncoded,e.value)}Qc.compareTokens=Mt.compareTokens;Qc.encodedSize=function(e){return Ue.encodedSize(e.value)};function Gw(r,e,t,n){return new I(g.tag,t,1)}function Ww(r,e,t,n){return new I(g.tag,St(r,e+1,n),2)}function jw(r,e,t,n){return new I(g.tag,_t(r,e+1,n),3)}function Yw(r,e,t,n){return new I(g.tag,It(r,e+1,n),5)}function Zw(r,e,t,n){return new I(g.tag,Ct(r,e+1,n),9)}function el(r,e){Ue(r,g.tag.majorEncoded,e.value)}el.compareTokens=Mt.compareTokens;el.encodedSize=function(e){return Ue.encodedSize(e.value)};var FS=20,VS=21,KS=22,$S=23;function Xw(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${K} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new I(g.null,null,1):new I(g.undefined,void 0,1)}function Jw(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${K} indefinite length items not allowed`);return new I(g.break,void 0,1)}function dp(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${K} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${K} Infinity values are not supported`)}return new I(g.float,r,e)}function Qw(r,e,t,n){return dp(hp(r,e+1),3,n)}function eb(r,e,t,n){return dp(pp(r,e+1),5,n)}function tb(r,e,t,n){return dp(sb(r,e+1),9,n)}function tl(r,e,t){let n=e.value;if(n===!1)r.push([g.float.majorEncoded|FS]);else if(n===!0)r.push([g.float.majorEncoded|VS]);else if(n===null)r.push([g.float.majorEncoded|KS]);else if(n===void 0)r.push([g.float.majorEncoded|$S]);else{let o,s=!1;(!t||t.float64!==!0)&&(nb(n),o=hp(tr,1),n===o||Number.isNaN(n)?(tr[0]=249,r.push(tr.slice(0,3)),s=!0):(ob(n),o=pp(tr,1),n===o&&(tr[0]=250,r.push(tr.slice(0,5)),s=!0))),s||(HS(n),o=sb(tr,1),tr[0]=251,r.push(tr.slice(0,9)))}}tl.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){nb(n);let o=hp(tr,1);if(n===o||Number.isNaN(n))return 3;if(ob(n),o=pp(tr,1),n===o)return 5}return 9};var rb=new ArrayBuffer(9),Ut=new DataView(rb,1),tr=new Uint8Array(rb,0);function nb(r){if(r===1/0)Ut.setUint16(0,31744,!1);else if(r===-1/0)Ut.setUint16(0,64512,!1);else if(Number.isNaN(r))Ut.setUint16(0,32256,!1);else{Ut.setFloat32(0,r);let e=Ut.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Ut.setUint16(0,31744,!1);else if(t===0)Ut.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Ut.setUint16(0,0):o<-14?Ut.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Ut.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function hp(r,e){if(r.length-e<2)throw new Error(`${K} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,s;return n===0?s=o*2**-24:n!==31?s=(o+1024)*2**(n-25):s=o===0?1/0:NaN,t&32768?-s:s}function ob(r){Ut.setFloat32(0,r,!1)}function pp(r,e){if(r.length-e<4)throw new Error(`${K} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function HS(r){Ut.setFloat64(0,r,!1)}function sb(r,e){if(r.length-e<8)throw new Error(`${K} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}tl.compareTokens=Mt.compareTokens;function ne(r,e,t){throw new Error(`${K} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function rl(r){return()=>{throw new Error(`${K} ${r}`)}}var N=[];for(let r=0;r<=23;r++)N[r]=ne;N[24]=pw;N[25]=mw;N[26]=gw;N[27]=yw;N[28]=ne;N[29]=ne;N[30]=ne;N[31]=ne;for(let r=32;r<=55;r++)N[r]=ne;N[56]=ww;N[57]=bw;N[58]=xw;N[59]=Ew;N[60]=ne;N[61]=ne;N[62]=ne;N[63]=ne;for(let r=64;r<=87;r++)N[r]=Aw;N[88]=Sw;N[89]=_w;N[90]=Iw;N[91]=Cw;N[92]=ne;N[93]=ne;N[94]=ne;N[95]=rl("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)N[r]=kw;N[120]=Tw;N[121]=Bw;N[122]=Pw;N[123]=Dw;N[124]=ne;N[125]=ne;N[126]=ne;N[127]=rl("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)N[r]=Nw;N[152]=Rw;N[153]=Ow;N[154]=Mw;N[155]=Uw;N[156]=ne;N[157]=ne;N[158]=ne;N[159]=Fw;for(let r=160;r<=183;r++)N[r]=Vw;N[184]=Kw;N[185]=$w;N[186]=Hw;N[187]=qw;N[188]=ne;N[189]=ne;N[190]=ne;N[191]=zw;for(let r=192;r<=215;r++)N[r]=Gw;N[216]=Ww;N[217]=jw;N[218]=Yw;N[219]=Zw;N[220]=ne;N[221]=ne;N[222]=ne;N[223]=ne;for(let r=224;r<=243;r++)N[r]=rl("simple values are not supported");N[244]=ne;N[245]=ne;N[246]=ne;N[247]=Xw;N[248]=rl("simple values are not supported");N[249]=Qw;N[250]=eb;N[251]=tb;N[252]=ne;N[253]=ne;N[254]=ne;N[255]=Jw;var rr=[];for(let r=0;r<24;r++)rr[r]=new I(g.uint,r,1);for(let r=-1;r>=-24;r--)rr[31-r]=new I(g.negint,r,1);rr[64]=new I(g.bytes,new Uint8Array(0),1);rr[96]=new I(g.string,"",1);rr[128]=new I(g.array,0,1);rr[160]=new I(g.map,0,1);rr[244]=new I(g.false,!1,1);rr[245]=new I(g.true,!0,1);rr[246]=new I(g.null,null,1);function ib(r){switch(r.type){case g.false:return Er([244]);case g.true:return Er([245]);case g.null:return Er([246]);case g.bytes:return r.value.length?void 0:Er([64]);case g.string:return r.value===""?Er([96]):void 0;case g.array:return r.value===0?Er([128]):void 0;case g.map:return r.value===0?Er([160]):void 0;case g.uint:return r.value<24?Er([Number(r.value)]):void 0;case g.negint:if(r.value>=-24)return Er([31-Number(r.value)])}}var zS={float64:!1,mapSorter:jS,quickEncodeToken:ib};function GS(){let r=[];return r[g.uint.major]=Mt,r[g.negint.major]=Zc,r[g.bytes.major]=ps,r[g.string.major]=Lw,r[g.array.major]=Jc,r[g.map.major]=Qc,r[g.tag.major]=el,r[g.float.major]=tl,r}var ab=GS(),mp=new Ki,ol=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Vr} object contains circular references`);return new r(t,e)}},En={null:new I(g.null,null),undefined:new I(g.undefined,void 0),true:new I(g.true,!0),false:new I(g.false,!1),emptyArray:new I(g.array,0),emptyMap:new I(g.map,0)},An={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new I(g.float,r):r>=0?new I(g.uint,r):new I(g.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new I(g.uint,r):new I(g.negint,r)},Uint8Array(r,e,t,n){return new I(g.bytes,r)},string(r,e,t,n){return new I(g.string,r)},boolean(r,e,t,n){return r?En.true:En.false},null(r,e,t,n){return En.null},undefined(r,e,t,n){return En.undefined},ArrayBuffer(r,e,t,n){return new I(g.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new I(g.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[En.emptyArray,new I(g.break)]:En.emptyArray;n=ol.createCheck(n,r);let o=[],s=0;for(let i of r)o[s++]=nl(i,t,n);return t.addBreakTokens?[new I(g.array,r.length),o,new I(g.break)]:[new I(g.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",s=o?r.keys():Object.keys(r),i=o?r.size:s.length;if(!i)return t.addBreakTokens===!0?[En.emptyMap,new I(g.break)]:En.emptyMap;n=ol.createCheck(n,r);let a=[],c=0;for(let l of s)a[c++]=[nl(l,t,n),nl(o?r.get(l):r[l],t,n)];return WS(a,t),t.addBreakTokens?[new I(g.map,i),a,new I(g.break)]:[new I(g.map,i),a]}};An.Map=An.Object;An.Buffer=An.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))An[`${r}Array`]=An.DataView;function nl(r,e={},t){let n=iw(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||An[n];if(typeof o=="function"){let i=o(r,n,e,t);if(i!=null)return i}let s=An[n];if(!s)throw new Error(`${Vr} unsupported type: ${n}`);return s(r,n,e,t)}function WS(r,e){e.mapSorter&&r.sort(e.mapSorter)}function jS(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,s=ab[o].compareTokens(t,n);return s===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),s}function cb(r,e,t,n){if(Array.isArray(e))for(let o of e)cb(r,o,t,n);else t[e.type.major](r,e,n)}function gp(r,e,t){let n=nl(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let s=e[n.type.major];if(s.encodedSize){let i=s.encodedSize(n,t),a=new Ki(i);if(s(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return Vi(a.chunks[0])}}return mp.reset(),cb(mp,n,e,t),mp.toBytes(!0)}function Sn(r,e){return e=Object.assign({},zS,e),gp(r,ab,e)}var YS={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},sl=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=rr[e];if(t===void 0){let n=N[e];if(!n)throw new Error(`${K} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},zi=Symbol.for("DONE"),il=Symbol.for("BREAK");function ZS(r,e,t){let n=[];for(let o=0;o<r.value;o++){let s=ys(e,t);if(s===il){if(r.value===1/0)break;throw new Error(`${K} got unexpected break to lengthed array`)}if(s===zi)throw new Error(`${K} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=s}return n}function XS(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},s=n?new Map:void 0;for(let i=0;i<r.value;i++){let a=ys(e,t);if(a===il){if(r.value===1/0)break;throw new Error(`${K} got unexpected break to lengthed map`)}if(a===zi)throw new Error(`${K} found map but not enough entries (got ${i} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${K} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&s.has(a)||!n&&a in o))throw new Error(`${K} found repeat map key "${a}"`);let c=ys(e,t);if(c===zi)throw new Error(`${K} found map but not enough entries (got ${i} [no value], expected ${r.value})`);n?s.set(a,c):o[a]=c}return n?s:o}function ys(r,e){if(r.done())return zi;let t=r.next();if(t.type===g.break)return il;if(t.type.terminal)return t.value;if(t.type===g.array)return ZS(t,r,e);if(t.type===g.map)return XS(t,r,e);if(t.type===g.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=ys(r,e);return e.tags[t.value](n)}throw new Error(`${K} tag not supported (${t.value})`)}throw new Error("unsupported")}function yp(r,e){if(!(r instanceof Uint8Array))throw new Error(`${K} data to decode must be a Uint8Array`);e=Object.assign({},YS,e);let t=e.tokenizer||new sl(r,e),n=ys(t,e);if(n===zi)throw new Error(`${K} did not find any content to decode`);if(n===il)throw new Error(`${K} got unexpected break`);return[n,r.subarray(t.pos())]}function kt(r,e){let[t,n]=yp(r,e);if(n.length>0)throw new Error(`${K} too many terminals, data makes no sense`);return t}var $r="/",lb=new TextEncoder().encode($r),al=lb[0],me=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=T(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==al)throw new Error("Invalid key")}toString(e="utf8"){return O(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join($r))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=lb),this._buf[0]!==al){let e=new Uint8Array(this._buf.byteLength+1);e.fill(al,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===al;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split($r).slice(1)}type(){return JS(this.baseNamespace())}name(){return QS(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith($r)||(e+=$r),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r($r):new r(e.slice(0,-1).join($r))}child(e){return this.toString()===$r?e:e.toString()===$r?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...e_(e.map(t=>t.namespaces()))])}};function JS(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function QS(r){let e=r.split(":");return e[e.length-1]}function e_(r){return[].concat(...r)}function cl({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*t_(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],s=H.asCID(n);s!=null?yield[o.join("/"),s]:typeof n=="object"&&(yield*bp(n,o))}else{let t=H.asCID(e);t!=null?yield[r.join("/"),t]:yield*bp(e,r)}}function*bp(r,e){if(r==null||r instanceof Uint8Array)return;let t=H.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let s=[...e,n];yield*t_(s,o)}}function*r_(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&H.asCID(n)==null&&(yield*xp(n,o))}else yield*xp(e,r)}function*xp(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let o=[...e,t];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&H.asCID(n)==null&&(yield*r_(o,n))}}function n_(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(i=>`[${JSON.stringify(i)}]`).join("")}`);let s=H.asCID(t);if(s!=null)return{value:s,remaining:e.slice(n+1).join("/")}}return{value:t}}var vp=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:cl(),bytes:cl(),value:cl(),asBlock:cl()})}links(){return bp(this.value,[])}tree(){return xp(this.value,[])}get(e="/"){return n_(this.value,e.split("/").filter(Boolean))}};function ub({bytes:r,cid:e,value:t,codec:n}){let o=t!==void 0?t:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new vp({cid:e,bytes:r,value:o})}var hb="/pin/",fb="/pinned-block/",Ep=wr,db=1;function ll(r){return r.version===0&&(r=r.toV1()),new me(`${hb}${r.toString(Ep)}`)}var ul=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=ll(e);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let s=new zt({concurrency:db});for await(let a of this.#e(e,s,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>Z(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Sn(i),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),s=await this.blockstore.get(e,n),i=ub({bytes:s,cid:e,codec:o});yield e;for(let[,a]of i.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new me(`${fb}${Ep.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=kt(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Sn(s),n),n.onProgress?.(new j("helia:pin:add",e))}}async*rm(e,t={}){let n=ll(e),o=await this.datastore.get(n,t),s=kt(o);await this.datastore.delete(n,t);let i=new zt({concurrency:db});for await(let a of this.#e(e,i,{...t,depth:s.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>Z(l,e.bytes)),!0),{...t,depth:s.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:hb+(e.cid!=null?`${e.cid.toString(wr)}`:"")},e)){let o=H.parse(t.toString().substring(5),wr),s=kt(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new me(`${fb}${Ep.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=ll(e),o=await this.datastore.get(n,t);return kt(o)}async setMetadata(e,t,n){let o=ll(e),s=await this.datastore.get(o,n),i=kt(s);i.metadata=t??{},await this.datastore.put(o,Sn(i),n)}};var Ap=1,Sp=5;var Gi=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},_n=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},Wi=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},ji=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var o_=5,fl=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??o_,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await pr(...this.routers)}async stop(){await mr(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new _n("No content routers available");let n=new Lo({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of Bt(n.toGenerator(),...io(this.routers,"findProviders").map(s=>s.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let s=await this.findPeer(o.id,t);return s.multiaddrs.length===0?null:s}catch(s){return this.log.error("could not load multiaddrs for peer %p",o.id,s),null}},{peerId:o.id,signal:t.signal}).catch(s=>{this.log.error("could not load multiaddrs for peer %p",o.id,s)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new _n("No content routers available");await Promise.all(io(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(io(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(io(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(io(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new _n("No peer routers available");let n=this,o=Bt(...io(this.routers,"findPeer").map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s;throw new Ie("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new _n("No peer routers available");for await(let n of Bt(...io(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function io(r,e){return r.filter(t=>t[e]!=null)}var dl=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var hl=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new gt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function s_(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var pl=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=s_(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new gt),this.cleanup())}async join(e={}){let t=new hl(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Le(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function _p(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Yi=class extends tt{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=_p(this.emitEmpty.bind(this),1),this.emitIdle=_p(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new dl;let n=new pl(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new gt)}),this.clear()}async onEmpty(e){this.size!==0&&await gr(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await gr(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await gr(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=Ws({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new gt("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var ml="lock:worker:request-read",gl="lock:worker:abort-read-request",yl="lock:worker:release-read",wl="lock:master:grant-read",bl="lock:master:error-read",xl="lock:worker:request-write",vl="lock:worker:abort-write-request",El="lock:worker:release-write",Al="lock:master:grant-write",Sl="lock:master:error-write",_l="lock:worker:finalize",Il="mortice",pb={singleProcess:!1};var Ip=(r,e,t,n,o,s,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===o&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(f=>{let d=h=>{if(h?.data==null)return;let p={type:h.data.type,name:h.data.name,identifier:h.data.identifier};p.type===a&&p.identifier===u.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),u.type===s&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===_l&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var mb=(r=10)=>Math.random().toString().substring(2,r+2);var Cl=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Il)}readLock(e){return this.sendRequest(ml,gl,wl,bl,yl,e)}writeLock(e){return this.sendRequest(xl,vl,Al,Sl,El,e)}finalize(){this.channel.postMessage({type:_l,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=mb();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",f)})}};var gb=r=>{if(r=Object.assign({},pb,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Il),n=new tt;return t.addEventListener("message",Ip(n,t,"requestReadLock","abortReadLockRequest",ml,gl,bl,yl,wl)),t.addEventListener("message",Ip(n,t,"requestWriteLock","abortWriteLockRequest",xl,vl,Sl,El,Al)),n}return new Cl(r.name)};var ao=new Map,Zi;function yb(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function i_(r){if(Zi==null&&(Zi=gb(r),!yb(Zi))){let e=Zi;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=ao.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=ao.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=ao.get(n);o?.finalize()})}return Zi}async function Cp(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new gt)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var wb=(r,e)=>{let t=ao.get(r);if(t!=null)return t;let n=i_(e);if(yb(n))return t=n,ao.set(r,t),t;let o=new Yi({concurrency:1}),s;return t={async readLock(i){if(s!=null)return Cp(s,i);s=new Yi({concurrency:e.concurrency,autoStart:!1});let a=s,c=Cp(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,Cp(o,i)},finalize:()=>{ao.delete(r)},queue:o},ao.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var a_={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Xi(r){let e=Object.assign({},a_,r);return wb(e.name,e)}var kl=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Xi({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await pr(this.child),this.started=!0}async stop(){await mr(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let s of e){if(await o.pins.isPinned(s))throw new Error("CID was pinned");yield s}}(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var kp=new me("/version"),bb=1;async function xb(r){if(!await r.has(kp)){await r.put(kp,T(`${bb}`));return}let e=await r.get(kp),t=O(e);if(parseInt(t,10)!==bb)throw new Error("Unknown datastore version, a datastore migration may be required")}var Pp={};Ee(Pp,{code:()=>Bp,decode:()=>g_,decodeOptions:()=>h_,encode:()=>m_,encodeOptions:()=>f_,name:()=>p_,toByteView:()=>Eb});var vb=42;function Eb(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function c_(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=H.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new I(g.tag,vb),new I(g.bytes,t)]}function l_(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function u_(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var Tp={float64:!0,typeEncoders:{Object:c_,undefined:l_,number:u_}},f_={...Tp,typeEncoders:{...Tp.typeEncoders}};function d_(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return H.decode(r.subarray(1))}var Tl={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Tl.tags[vb]=d_;var h_={...Tl,tags:Tl.tags.slice()},p_="dag-cbor",Bp=113,m_=r=>Sn(r,Tp),g_=r=>kt(Eb(r),Tl);var Up={};Ee(Up,{code:()=>Mp,decode:()=>Sb,encode:()=>Ab,format:()=>C_,name:()=>I_,parse:()=>T_,stringify:()=>C_});var Dp=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===g.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===g.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[g.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s);e.push(o)}[g.negint.major](e,t){this[g.uint.major](e,t)}[g.bytes.major](e,t){throw new Error(`${Vr} unsupported type: Uint8Array`)}[g.string.major](e,t){this.prefix(e);let n=Yc(JSON.stringify(t.value));e.push(n.length>32?Vi(n):n)}[g.array.major](e,t){this.prefix(e),this.inRecursive.push({type:g.array,elements:0}),e.push([91])}[g.map.major](e,t){this.prefix(e),this.inRecursive.push({type:g.map,elements:0}),e.push([123])}[g.tag.major](e,t){}[g.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(i.type===g.array)e.push([93]);else if(i.type===g.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${Vr} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],s=!1;for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i),!s&&(o[i]===46||o[i]===101||o[i]===69)&&(s=!0);s||(o.push(46),o.push(48)),e.push(o)}};function y_(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Vr} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==g.string||n.type!==g.string)throw new Error(`${Vr} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Vr} unexpected duplicate map keys, this is not supported`)}var w_={addBreakTokens:!0,mapSorter:y_};function Lp(r,e){return e=Object.assign({},w_,e),gp(r,new Dp,e)}var ws=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${K} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${K} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new I(g.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${K} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${K} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let s=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(s);return n?new I(g.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new I(i>=0?g.uint:g.negint,i,this._pos-e):new I(i>=0?g.uint:g.negint,BigInt(s),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${K} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let s=this._pos,i=0;s<this.data.length&&i<65536;s++,i++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,s));return this._pos=s+1,new I(g.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${K} unexpected end of unicode escape sequence at position ${this._pos}`);let s=0;for(let i=0;i<4;i++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${K} unexpected unicode escape character at position ${this._pos}`);s=s*16+a,this._pos++}return s},o=()=>{let s=this.ch(),i=null,a=s>239?4:s>223?3:s>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${K} unexpected unicode sequence at position ${this._pos}`);let c,l,u,f;switch(a){case 1:s<128&&(i=s);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(s&31)<<6|c&63,f>127&&(i=f));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(f=(s&15)<<12|(c&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(i=f));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(f=(s&15)<<18|(c&63)<<12|(l&63)<<6|u&63,f>65535&&f<1114112&&(i=f))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let s=this.ch(),i;switch(s){case 92:if(this._pos++,this.done())throw new Error(`${K} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${K} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new I(g.string,up(t),this._pos-e);default:if(s<32)throw new Error(`${K} invalid control character at position ${this._pos}`);s<128?(t.push(s),this._pos++):o()}}throw new Error(`${K} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new I(g.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new I(g.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new I(g.null,null,4);case 102:return this.expect([102,97,108,115,101]),new I(g.false,!1,5);case 116:return this.expect([116,114,117,101]),new I(g.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${K} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new I(g.break,void 0,1);if(this.ch()!==44)throw new Error(`${K} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new I(g.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new I(g.break,void 0,1);if(this.ch()!==44)throw new Error(`${K} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new I(g.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${K} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${K} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Np(r,e){return e=Object.assign({tokenizer:new ws(r,e)},e),kt(r,e)}function x_(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function v_(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=H.asCID(r);if(!e)return null;let t=e.toString();return[new I(g.map,1/0,1),new I(g.string,"/",1),new I(g.string,t,t.length),new I(g.break,void 0,1)]}function Bl(r){let e=Ye.encode(r).slice(1);return[new I(g.map,1/0,1),new I(g.string,"/",1),new I(g.map,1/0,1),new I(g.string,"bytes",5),new I(g.string,e,e.length),new I(g.break,void 0,1),new I(g.break,void 0,1)]}function nr(r){return Bl(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function E_(r){return Bl(new Uint8Array(r))}function A_(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function S_(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var __={typeEncoders:{Object:v_,Buffer:Bl,Uint8Array:Bl,Int8Array:nr,Uint16Array:nr,Int16Array:nr,Uint32Array:nr,Int32Array:nr,Float32Array:nr,Float64Array:nr,Uint8ClampedArray:nr,BigInt64Array:nr,BigUint64Array:nr,DataView:nr,ArrayBuffer:E_,undefined:A_,number:S_}},Rp=class extends ws{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===g.map){let t=this._next();if(t.type===g.string&&t.value==="/"){let n=this._next();if(n.type===g.string){if(this._next().type!==g.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new I(g.tag,42,0)}if(n.type===g.map){let o=this._next();if(o.type===g.string&&o.value==="bytes"){let s=this._next();if(s.type===g.string){for(let a=0;a<2;a++)if(this._next().type!==g.break)throw new Error("Invalid encoded Bytes form");let i=Ye.decode(`m${s.value}`);return new I(g.bytes,i,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Op={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Op.tags[42]=H.parse;var I_="dag-json",Mp=297,Ab=r=>Lp(r,__),Sb=r=>{let e=x_(r),t=Object.assign(Op,{tokenizer:new Rp(e,Op)});return Np(e,t)},C_=r=>k_.decode(Ab(r));var k_=new TextDecoder,T_=r=>Sb(B_.encode(r)),B_=new TextEncoder;var qp={};Ee(qp,{code:()=>Hp,createLink:()=>Nb,createNode:()=>Lb,decode:()=>H_,encode:()=>$_,name:()=>K_,prepare:()=>Kp,validate:()=>$p});var P_=new TextDecoder;function Fp(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Pl(r,e){let t;[t,e]=Fp(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function _b(r,e){let t;return[t,e]=Fp(r,e),[t&7,t>>3,e]}function D_(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=_b(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Pl(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Pl(r,n),e.Name=P_.decode(i)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=Fp(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Ib(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=_b(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=Pl(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Pl(r,t),n.push(D_(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let i={};return s&&(i.Data=s),i.Links=n||[],i}var kb=new TextEncoder,Cb=2**32,L_=2**31;function N_(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=Ji(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=kb.encode(r.Name);t-=n.length,e.set(n,t),t=Ji(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=Ji(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function Tb(r){let e=O_(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=Ji(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let s=N_(r.Links[o],t.subarray(0,n));n-=s,n=Ji(t,n,s)-1,t[n]=18}return t}function R_(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+bs(t)}if(typeof r.Name=="string"){let t=kb.encode(r.Name).length;e+=1+t+bs(t)}return typeof r.Tsize=="number"&&(e+=1+bs(r.Tsize)),e}function O_(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+bs(t)}if(r.Links)for(let t of r.Links){let n=R_(t);e+=1+n+bs(n)}return e}function Ji(r,e,t){e-=bs(t);let n=e;for(;t>=L_;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function bs(r){return r%2===0&&r++,Math.floor((M_(r)+6)/7)}function M_(r){let e=0;return r>=Cb&&(r=Math.floor(r/Cb),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+U_[r]}var U_=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var F_=["Data","Links"],V_=["Hash","Name","Tsize"],Vp=new TextEncoder;function Pb(r,e){if(r===e)return 0;let t=r.Name?Vp.encode(r.Name):[],n=e.Name?Vp.encode(e.Name):[],o=t.length,s=n.length;for(let i=0,a=Math.min(o,s);i<a;++i)if(t[i]!==n[i]){o=t[i],s=n[i];break}return o<s?-1:s<o?1:0}function Bb(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Db(r){if(typeof r.asCID=="object"){let t=H.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=H.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=H.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=H.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function Kp(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=Vp.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(Db),e.Links.sort(Pb);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function $p(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Bb(r,F_))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!Bb(t,V_))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&Pb(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function Lb(r,e=[]){return Kp({Data:r,Links:e})}function Nb(r,e,t){return Db({Hash:t,Name:r,Tsize:e})}function Rb(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var K_="dag-pb",Hp=112;function $_(r){$p(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),Tb(e)}function H_(r){let e=Rb(r),t=Ib(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=H.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}function xs(r){return r?.then!=null}function Ob(r=[],e){let t={[Hp]:qp,[Xs]:Js,[Bp]:Pp,[Mp]:Up,[qd]:lc};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);xs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new ji(`Could not load codec for ${n}`)}}function Mb(r=[],e){let t={[Yt.code]:Yt,[fc.code]:fc,[Ze.code]:Ze};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);xs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Wi(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var Ft=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var Hr=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:o}of e)await this.put(n,o,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var Dl=0,Ll=class extends Hr{child;constructor(e){super(),this.child=e}put(e,t,n){return e.multihash.code===Dl||this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}get(e,t){if(e.multihash.code===Dl)return t?.signal?.throwIfAborted(),e.multihash.digest;if(this.child==null)throw t?.signal?.throwIfAborted(),new Ft;return this.child.get(e,t)}has(e,t){return e.multihash.code===Dl?(t?.signal?.throwIfAborted(),!0):this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===Dl){t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}getAll(e){return this.child!=null?this.child.getAll(e):(e?.signal?.throwIfAborted(),[])}};function q_(r){return r[Symbol.asyncIterator]!=null}function z_(r,e){let t=0;if(q_(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Uo(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var or=z_;function G_(r){return r[Symbol.asyncIterator]!=null}function Ub(r){return r?.then!=null}function W_(r,e){let t=0;if(G_(r))return async function*(){for await(let c of r){let l=e(c,t++);Ub(l)&&await l,yield c}}();let n=Uo(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();if(typeof e(o,t++)?.then=="function")return async function*(){yield o;for(let c of n){let l=e(c,t++);Ub(l)&&await l,yield c}}();let a=e;return function*(){yield o;for(let c of n)a(c,t++),yield c}()}var zp=W_;var Nl=class{child;getHasher;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Ll(e.blockstore),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new j("blocks:put:duplicate",e)),e):(n.onProgress?.(new j("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new j("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=or(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new j("blocks:put-many:duplicate",s)),!i}),o=zp(n,async({cid:s,block:i})=>{t.onProgress?.(new j("blocks:put-many:providers:notify",s)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(s,i,t)))});t.onProgress?.(new j("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new j("blocks:get:providers:get",e));let o=await Fb(e,this.components.blockBrokers,n,{...t,log:this.log});return t.onProgress?.(new j("blocks:get:blockstore:put",e)),await this.child.put(e,o,t),t.onProgress?.(new j("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(e,o,t))),o}return t.onProgress?.(new j("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new j("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(zp(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let o=await this.getHasher(n.multihash.code);t.onProgress?.(new j("blocks:get-many:providers:get",n));let s=await Fb(n,this.components.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new j("blocks:get-many:blockstore:put",n)),await this.child.put(n,s,t),t.onProgress?.(new j("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(n,s,t)))}}))}async delete(e,t={}){t.onProgress?.(new j("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new j("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of e)yield n}(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new j("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},Rl=class extends Nl{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await pr(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await mr(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new Gp({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},Gp=class extends Nl{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=de([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=de([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=de([this.closeController.signal,t.signal]);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=de([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=de([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=de([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=de([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=de([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function j_(r){return typeof r.retrieve=="function"}var Y_=(r,e)=>{if(e==null)throw new B(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t);if(xs(o)?n=await o:n=o,!Z(n.digest,r.multihash.digest))throw new cn("Hash of downloaded block did not match multihash from passed CID")}};async function Fb(r,e,t,n){let o=Y_(r,t),s=new AbortController,i=de([s.signal,n.signal]);s.signal;let a=[];for(let c of e)j_(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:i,validateFn:async f=>{await o(f),l=!0}});return l||await o(u),u}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{s.abort(),i.clear()}}var Qi=class extends tt{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(e,t){super(),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=no(this.maxProviders),this.initialProviders=t.providers??[]}async retrieve(e,t={}){let n=Ye.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let s=Q();if(this.requests.set(n,s.promise),this.providers.length===0){let u=!1;this.initialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.initialPeerSearchComplete,u&&this.log("found initial session peers for %c",e)}let i=!1,a=new zt({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",u=>{this.log.error("error querying provider %o, evicting from session",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),a.addEventListener("success",u=>{i=!0,s.resolve(u.detail.result)}),a.addEventListener("idle",()=>{if(i||t.signal?.aborted===!0){this.log.trace("session idle, found block");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let f=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(f)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(u=>{this.log.error("could not find new providers for %c",e,u),s.reject(u)})});let c=u=>{a.add(async()=>this.queryProvider(e,u.detail,t),{provider:u.detail}).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,f)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async u=>a.add(async()=>this.queryProvider(e,u,t),{provider:u}))).catch(u=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,u)});let l=()=>{s.reject(new mt(t.signal?.reason??"Session aborted")),a.abort()};t.signal?.addEventListener("abort",l);try{return await s.promise}finally{this.removeEventListener("provider",c),t.signal?.removeEventListener("abort",l),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=Q(),s=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e),this.initialProviders.length>0)for(;s<t&&this.initialProviders.length>0;){let i=this.initialProviders.pop();if(i==null)break;let a=await this.convertToProvider(i,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",s,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),s++,s===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",s);break}}if(s<this.maxProviders)for await(let i of this.findNewProviders(e,n)){if(s===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",s,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),s++,s===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",s);break}}if(this.log("found %d/%d new session peers",s,this.maxProviders),s<t)throw new Gi(`Found ${s} of ${t} ${this.name} providers for ${e}`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",e,i.errors??i),o.reject(i)}),o.promise}};var Ml=class{libp2p;blockstore;datastore;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??vn(),this.log=this.logger.forComponent("helia"),this.getHasher=Mb(e.hashers,e.loadHasher),this.getCodec=Ob(e.codecs,e.loadCodec),this.dns=e.dns??Wc(),this.metrics=e.metrics,this.libp2p=e.libp2p;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,libp2p:this.libp2p,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new fl(t,{routers:(e.routers??[]).flatMap(o=>{let s=[o];return o[on]!=null&&s.push(o[on]),o[sn]!=null&&s.push(o[sn]),s}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new Rl(t);this.pins=new ul(e.datastore,n,this.getCodec),this.blockstore=new kl(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await xb(this.datastore),await pr(this.blockstore,this.datastore,this.routing,this.libp2p)}async stop(){await mr(this.blockstore,this.datastore,this.routing,this.libp2p)}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await Ys(o.deleteMany(async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new j("helia:gc:deleted",s))}catch(i){n.log.error("Error during gc",i),e.onProgress?.(new j("helia:gc:error",i))}}()))}finally{t()}this.log("gc finished")}};var Wp=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Je(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Wp({name:e,metrics:t}):n=new Map,n}var Fe=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},qr=class extends Error{static name="ValidationError";name="ValidationError"},ea=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Ul=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Fl=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Vb=45,Z_=15,vs=new Fl;function Vl(r){if(!(r.length>Z_))return vs.new(r).parseWith(()=>vs.readIPv4Addr())}function Kl(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Vb))return vs.new(r).parseWith(()=>vs.readIPv6Addr())}function Es(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Vb)return;let t=vs.new(r).parseWith(()=>vs.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function sr(r){return!!Vl(r)}function $l(r){return!!Kl(r)}function Yp(r){return e=>O(e,r)}function Zp(r){return e=>T(e,r)}function As(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function co(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Kb(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=T(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=co(n);return We([t,o],t.length+o.length)}function $b(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ke.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=co(n);return We([t,o],t.length+o.length)}function Xp(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=O(e,"base32"),o=As(t);return`${n}:${o}`}var Jp=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Fe("Invalid byte value in IP address");e[n]=o}),e},Hb=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=sr(t[n]),i;s&&(i=Jp(t[n]),t[n]=O(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,O(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Fe("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},qb=function(r){if(r.byteLength!==4)throw new Fe("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},zb=function(r){if(r.byteLength!==16)throw new Fe("IPv6 address was incorrect length");let e=[];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")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Fe(`Invalid IPv6 address "${t}"`)}};function Gb(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Fe(`Invalid IPv6 address "${r}"`)}}var jp=Object.values(ri).map(r=>r.decoder),X_=function(){let r=jp[0].or(jp[1]);return jp.slice(2).forEach(e=>r=r.or(e)),r}();function Wb(r){return X_.decode(r)}function jb(r){return e=>r.encoder.encode(e)}function J_(r){if(parseInt(r).toString()!==r)throw new qr("Value must be an integer")}function Q_(r){if(r<0)throw new qr("Value must be a positive integer, or zero")}function eI(r){return e=>{if(e>r)throw new qr(`Value must be smaller than or equal to ${r}`)}}function tI(...r){return e=>{for(let t of r)t(e)}}var ta=tI(J_,Q_,eI(65535));var De=-1,Qp=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Ul(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},dt=new Qp,gI=[{code:4,name:"ip4",size:32,valueToBytes:Jp,bytesToValue:qb,validate:r=>{if(!sr(r))throw new qr(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:co,bytesToValue:As,validate:ta},{code:273,name:"udp",size:16,valueToBytes:co,bytesToValue:As,validate:ta},{code:33,name:"dccp",size:16,valueToBytes:co,bytesToValue:As,validate:ta},{code:41,name:"ip6",size:128,valueToBytes:Hb,bytesToValue:zb,stringToValue:Gb,validate:r=>{if(!$l(r))throw new qr(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:De},{code:43,name:"ipcidr",size:8,bytesToValue:Yp("base10"),valueToBytes:Zp("base10")},{code:53,name:"dns",size:De,resolvable:!0},{code:54,name:"dns4",size:De,resolvable:!0},{code:55,name:"dns6",size:De,resolvable:!0},{code:56,name:"dnsaddr",size:De,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:co,bytesToValue:As,validate:ta},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:De,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:De,bytesToValue:Yp("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Zp("base58btc")(r):H.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Xp,valueToBytes:Kb},{code:445,name:"onion3",size:296,bytesToValue:Xp,valueToBytes:$b},{code:446,name:"garlic64",size:De},{code:447,name:"garlic32",size:De},{code:448,name:"tls"},{code:449,name:"sni",size:De},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:De,bytesToValue:jb(Vd),valueToBytes:Wb},{code:480,name:"http"},{code:481,name:"http-path",size:De,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:De}];gI.forEach(r=>{dt.addProtocol(r)});function Yb(r){let e=[],t=0;for(;t<r.length;){let n=Rn(r,t),o=dt.getProtocol(n),s=Ce(n),i=yI(o,r,t+s),a=0;i>0&&o.size===De&&(a=Ce(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??O(f)}e.push(l),t+=c}return e}function Zb(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=dt.getProtocol(n.code),s=Ce(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??T(n.value),a=i.byteLength,o.size===De&&(c=Ce(a)));let l=new Uint8Array(s+c+a),u=0;No(n.code,l,u),u+=s,i!=null&&(o.size===De&&(No(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return We(t,e)}function Xb(r){if(r.charAt(0)!=="/")throw new Fe('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=dt.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Fe(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Fe(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Fe("Incomplete multiaddr");return e}function Jb(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=dt.getProtocol(e.code);if(t==null)throw new Fe(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function yI(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Rn(e,t)}var wI=Symbol.for("nodejs.util.inspect.custom"),lm=Symbol.for("@multiformats/multiaddr"),bI=[53,54,55,56],cm=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}};function xI(r){if(r==null&&(r="/"),Cn(r))return r.getComponents();if(r instanceof Uint8Array)return Yb(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Xb(r);if(Array.isArray(r))return r;throw new Fe("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Gl=class r{[lm]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=xI(e),t.validate!==!1&&vI(this)}get bytes(){return this.#r==null&&(this.#r=Zb(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Jb(this.#e)),this.#t}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="";for(let{code:a,name:c,value:l}of this.#e)a===42&&(s=`%${l??""}`),bI.includes(a)&&(t="tcp",o=443,n=`${l??""}${s}`,e=a===55?6:4),(a===6||a===273)&&(t=c==="tcp"?"tcp":"udp",o=parseInt(l??"")),(a===4||a===41)&&(t="tcp",n=`${l??""}${s}`,e=a===41?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:t})=>{let n=dt.getProtocol(e);return{code:e,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#e.map(({code:e})=>e)}protoNames(){return this.#e.map(({name:e})=>e)}tuples(){return this.#e.map(({code:e,value:t})=>{if(t==null)return[e];let n=dt.getProtocol(e),o=[e];return t!=null&&o.push(n.valueToBytes?.(t)??T(t)),o})}stringTuples(){return this.#e.map(({code:e,value:t})=>t==null?[e]:[e,t])}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new ea(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:n,value:o})=>{n===421&&e.push([n,o]),n===290&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?O(ie.decode(`z${n}`),"base58btc"):O(H.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let e of this.#e)if(dt.getProtocol(e.code).path)return e.value??null;return null}equals(e){return Z(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=Qb.get(t.name);if(n==null)throw new cm(`no available resolver for ${t.name}`);return(await n(this,e)).map(s=>X(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(this.#e.length!==2||this.#e[0].code!==4&&this.#e[0].code!==41||this.#e[1].code!==6&&this.#e[1].code!==273)}[wI](){return`Multiaddr(${this.toString()})`}};function vI(r){r.getComponents().forEach(e=>{let t=dt.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function ex(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function tx(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function um(r){switch(r.length){case uo:return r.join(".");case fo:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function rx(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function nx(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var uo=4,fo=16,oM=parseInt("0xFFFF",16),EI=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function na(r,e){e.length===fo&&r.length===uo&&ex(e,0,11)&&(e=e.slice(12)),e.length===uo&&r.length===fo&&tx(r,EI,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function ox(r,e){if(typeof e=="string"&&(e=Es(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function fm(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=uo,o=Vl(e);if(o==null&&(n=fo,o=Kl(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=dm(s,8*n);return{network:na(o,i),mask:i}}function dm(r,e){if(e!==8*uo&&e!==8*fo)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var Cs=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=fm(e));else{let n=Es(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=Es(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=dm(o,8*n.length);this.network=na(n,this.mask)}}contains(e){return ox({network:this.network,mask:this.mask},e)}toString(){let e=rx(this.mask),t=e!==-1?String(e):nx(this.mask);return um(this.network)+"/"+t}};function hm(r){let e,t;if(r.getComponents().forEach(n=>{(n.name==="ip4"||n.name==="ip6")&&(t=n.value),n.name==="ipcidr"&&(e=n.value)}),e==null||t==null)throw new Error("Invalid multiaddr");return new Cs(t,e)}var Qb=new Map;function Cn(r){return!!r?.[lm]}function X(r){return new Gl(r)}function Wl(r){let e=dt.getProtocol(r);return{code:e.code,size:e.size??0,name:e.name,resolvable:!!e.resolvable,path:!!e.path}}var AI=[6,53,56,54,55];function sx(r){return cx("sni",r)?.value}function ix(r){let e=cx("tcp",r)?.value;return e==null?"":`:${e}`}function cx(r,e){return e.find(t=>t.name===r)}function ax(r){return r.some(({code:e})=>e===448)}function ar(r,e){let t=lx[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var lx={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${ar(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${ar(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${ar(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${ar(t,e)}`},http:(r,e)=>{let t=ax(e),n=sx(e),o=ix(e);if(t&&n!=null)return`https://${n}${o}`;let s=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=ar(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ar(t,e),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return ar(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return ar(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ar(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=ax(e),n=sx(e),o=ix(e);if(t&&n!=null)return`wss://${n}${o}`;let s=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=ar(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ar(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function jl(r,e){let n=X(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=lx[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return e?.assumeHttp!==!1&&AI.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 fx=nn(ux(),1),SI=["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"],_I=SI.map(r=>new fx.Netmask(r));function pm(r){for(let e of _I)if(e.contains(r))return!0;return!1}function II(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function CI(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return pm(o)}function kI(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function TI(r){let e=r.split(":"),t=e[e.length-1];return pm(t)}function BI(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 Sr(r){if(sr(r))return pm(r);if(II(r))return CI(r);if(kI(r))return TI(r);if($l(r))return BI(r)}var pe=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),q=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),te=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Qe=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),ae=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function fe(...r){function e(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 t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var PI=q(421),dx=fe(PI),Zl=q(54),Xl=q(55),Jl=q(56),gm=q(53),GM=fe(Zl,te(q(421))),WM=fe(Xl,te(q(421))),jM=fe(Jl,te(q(421))),hx=fe(Qe(gm,Jl,Zl,Xl),te(q(421))),px=ae(q(4),te(q(43))),mx=ae(te(q(42)),q(41),te(q(43))),ym=Qe(px,mx),ho=Qe(ym,gm,Zl,Xl,Jl),YM=fe(Qe(ym,ae(Qe(gm,Jl,Zl,Xl),te(q(421))))),wm=fe(px),bm=fe(mx),ZM=fe(ym),xm=ae(ho,q(6)),sa=ae(ho,q(273)),ia=fe(ae(xm,te(q(421)))),XM=fe(sa),vm=ae(sa,pe(460),te(q(421))),Ql=ae(sa,pe(461),te(q(421))),DI=Qe(vm,Ql),JM=fe(vm),gx=fe(Ql),mm=Qe(ho,xm,sa,vm,Ql),yx=Qe(ae(mm,pe(477),te(q(421)))),po=fe(yx),wx=Qe(ae(mm,pe(478),te(q(421))),ae(mm,pe(448),te(q(449)),pe(477),te(q(421)))),aa=fe(wx),bx=ae(sa,pe(280),te(q(466)),te(q(466)),te(q(421))),Em=fe(bx),xx=ae(Ql,pe(465),te(q(466)),te(q(466)),te(q(421))),Am=fe(xx),Yl=Qe(yx,wx,ae(xm,te(q(421))),ae(DI,te(q(421))),ae(ho,te(q(421))),bx,xx,q(421)),QM=fe(Yl),LI=ae(Yl,pe(290),q(421)),ca=fe(LI),NI=Qe(ae(Yl,pe(290),pe(281),te(q(421))),ae(Yl,pe(281),te(q(421))),ae(pe(281),te(q(421)))),Sm=fe(NI),RI=Qe(ae(ho,q(6),pe(480),te(q(421))),ae(ho,pe(480),te(q(421)))),vx=fe(RI),OI=ae(ho,Qe(ae(q(6,"443"),pe(480)),ae(q(6),pe(443)),ae(q(6),pe(448),pe(480)),ae(pe(448),pe(480)),pe(448),pe(443)),te(q(421))),Ex=fe(OI),MI=Qe(ae(q(777),te(q(421)))),eU=fe(MI),UI=Qe(ae(q(400),te(q(421)))),tU=fe(UI);function _m(r,e,t){return r.filter(n=>{if(Ex.matches(n)||e&&vx.matches(n))return t||hx.matches(n)?!0:Sr(n.toOptions().host)===!1;if(!e&&t){let{host:o}=n.toOptions();if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*eu(r,e,t,n,o,s={}){for await(let i of e.findProviders(r,s)){let a=_m(i.multiaddrs,n,o);if(a.length===0)continue;let c=jl(a[0]);yield new ks(c,{logger:t,transformRequestInit:s.transformRequestInit})}}async function Ax(r,e,t){let{signal:n,log:o}=t??{},s=r.headers.get("content-length");if(s!=null){let c=parseInt(s,10);if(c>e)throw o?.error("content-length header (%d) is greater than the limit (%d)",c,e),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 (${e}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new ee;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>e)throw new Error(`Response body is greater than the limit (${e}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var ks=class{url;#e=0;#t=0;#r=0;#a=0;#i=new Map;log;transformRequestInit;constructor(e,{logger:t,transformRequestInit:n}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#l(e){let t=e.multihash.bytes;return Ye.encode(t)}async getRawBlock(e,{signal:t,maxSize:n=Sx}={}){let o=new URL(this.url.toString());if(o.pathname=`/ipfs/${e.toString()}`,o.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let s=this.#l(e),i=new AbortController,a=()=>{i.abort()};t?.addEventListener("abort",a);try{let c=this.#i.get(s);if(c==null){this.#e++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},u=this.transformRequestInit!=null?await this.transformRequestInit(l):l;c=fetch(o.toString(),u).then(async f=>{if(this.log("GET %s %d",o,f.status),!f.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);let d=await Ax(f,n,{signal:i.signal,log:this.log});return this.#a++,d}),this.#i.set(s,c)}return await c}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",a),this.#i.delete(s)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#a/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#a,pendingResponses:this.#i.size}}};var Im=class extends Qi{routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??tu,this.allowLocal=t.allowLocal??ru,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let o=await t.getRawBlock(e,n);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*eu(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t){if(hr(e))return;let n=_m(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(n.length===0)return;let o=jl(n[0]);return new ks(o,{logger:this.logger,transformRequestInit:this.transformRequestInit})}};function _x(r,e){return new Im(r,e)}var nu=class{allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??tu,this.allowLocal=t.allowLocal??ru,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let o of eu(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,o.url);try{let s=await o.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s",e,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s",e,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return _x({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var tu=!1,ru=!1,Sx=2097152;function Cm(r={}){return e=>new nu(e,r)}async function*ou(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var qI=nn(Tm(),1);var cr=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},su=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},Ts=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},iu=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},au=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},cu=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},la=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var lr;(function(r){let e;(function(o){o.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(o){o[o.EOL=0]="EOL"})(t||(t={})),function(o){o.codec=()=>si(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=Oe((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.value!=null&&(s.uint32(10),s.bytes(o.value)),o.signatureV1!=null&&(s.uint32(18),s.bytes(o.signatureV1)),o.validityType!=null&&(s.uint32(24),r.ValidityType.codec().encode(o.validityType,s)),o.validity!=null&&(s.uint32(34),s.bytes(o.validity)),o.sequence!=null&&(s.uint32(40),s.uint64(o.sequence)),o.ttl!=null&&(s.uint32(48),s.uint64(o.ttl)),o.pubKey!=null&&(s.uint32(58),s.bytes(o.pubKey)),o.signatureV2!=null&&(s.uint32(66),s.bytes(o.signatureV2)),o.data!=null&&(s.uint32(74),s.bytes(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Re(o,r.codec()),r.decode=(o,s)=>Ne(o,r.codec(),s)})(lr||(lr={}));var FI=Et("ipns:utils"),Ix=T("/ipns/");var VI=0,KI=18;function Cx(r){let e;if(r.pubKey!=null)try{e=bn(r.pubKey)}catch(t){throw FI.error(t),t}if(e!=null)return e}function kx(r){let e=T("ipns-signature:");return We([e,r])}function ua(r){return"signatureV1"in r?lr.encode({value:T(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:T(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):lr.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function kn(r){let e=lr.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw new cr("Missing data or signatureV2");let t=Tx(e.data),n=$I(t.Value),o=O(t.Validity);if(e.value!=null&&e.signatureV1!=null)return HI(e),{value:n,validityType:lr.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:lr.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function fa(r){return We([Ix,r.bytes])}function Bs(r){let e=wt(r.slice(Ix.length));if(!lu(e,VI)&&!lu(e,KI))throw new cn("Multihash in IPNS key was not identity or sha2-256");return e}function Tx(r){let e=kt(r);if(e.ValidityType===0)e.ValidityType=lr.ValidityType.EOL;else throw new Ts("The validity type is unsupported");return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e}function $I(r){let e=O(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${H.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${H.parse(e).toV1().toString()}`}catch{}throw new au("Value must be a valid content path starting with /")}function HI(r){if(r.data==null)throw new cu("Record data is missing");let e=Tx(r.data);if(!Z(e.Value,r.value??new Uint8Array(0)))throw new cr('Field "value" did not match between protobuf and CBOR');if(!Z(e.Validity,r.validity??new Uint8Array(0)))throw new cr('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new cr('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new cr('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new cr('Field "ttl" did not match between protobuf and CBOR')}function lu(r,e){return r.code===e}var ZU=Et("ipns"),XU=300*1e9,zI="/ipns/",JU=zI.length;var Bx=nn(Tm(),1);var uu=Et("ipns:validator"),GI=1024*10;async function WI(r,e){let t=kn(e),n;try{let o=kx(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw uu.error("record signature verification failed"),new cr("Record signature verification failed");if(t.validityType===lr.ValidityType.EOL){if(Bx.default.fromString(t.validity).toDate().getTime()<Date.now())throw uu.error("record has expired"),new su("record has expired")}else if(t.validityType!=null)throw uu.error("the validity type is unsupported"),new Ts("The validity type is unsupported");uu("ipns record for %s is valid",t.value)}async function Px(r,e){if(e.byteLength>GI)throw new iu("The record is too large");let t=Bs(r),n;lu(t,0)&&(n=Rc(t));let o=kn(e),s=Cx(o)??n;if(s==null)throw new la("Could not extract public key from IPNS record or routing key");let i=fa(s.toMultihash());if(!Z(i,r))throw new la("Embedded public key did not match routing key");await WI(s,e)}var fu=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*da(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),Oo(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new fu("Incoming message too long");let i=o.split(t);o=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var Ps=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},ur=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function jI(r){return r[Symbol.asyncIterator]!=null}function YI(r){if(jI(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var Dx=YI;var Lx=T("/ipns/");function Nx(r){return Z(r.subarray(0,Lx.byteLength),Lx)}var du=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*sc(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!Nx(e))return;let o=Bs(e),s=H.createV1(114,o),i=kn(t);await this.client.putIPNS(s,i,n)}async get(e,t){if(!Nx(e))throw new Ie("Not found");let n=Bs(e),o=H.createV1(114,n);try{let s=await this.client.getIPNS(o,t);return ua(s)}catch(s){throw s.name==="BadResponseError"?new Ie("Not found"):s}}},hu=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await Dx(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new Ie("Not found")}async*getClosestPeers(e,t={}){}};var Ve=Et("delegated-routing-v1-http-api-client"),pu={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},mu=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new oo({concurrency:t.concurrentRequests??pu.concurrentRequests}),this.inFlightRequests=new Map,this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??pu.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new du(this),this.peerRouting=new hu(this),this.cacheName=t.cacheName??pu.cacheName,this.cacheTTL=t.cacheTTL??pu.cacheTTL}get[on](){return this.contentRouting}get[sn](){return this.peerRouting}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&Ve("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){Ve("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=de([this.shutDownController.signal,n,t.signal]);let s=Q(),i=Q();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.clientUrl}routing/v1/providers/${e.toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(l==null)throw new ur("No response received");if(!l.ok)throw l.status===404?new Ie("No matching records found"):l.status===422?new Ps("Request does not conform to schema or semantic constraints"):new ur(`Unexpected status code: ${l.status}`);if(l.body==null)throw new ur("Routing response had no body");let u=l.headers.get("Content-Type");if(u==null)throw new ur("No Content-Type header received");if(u?.startsWith("application/json")){let f=await l.json();for(let d of f.Providers){let h=this.#e(d);h!=null&&(yield h)}}else if(u.includes("application/x-ndjson"))for await(let f of da(ou(l.body))){let d=this.#e(f);d!=null&&(yield d)}else throw new ur(`Unsupported Content-Type: ${u}`)}finally{o.clear(),i.resolve(),Ve("getProviders finished: %c",e)}}async*getPeers(e,t={}){Ve("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=de([this.shutDownController.signal,n,t.signal]);let s=Q(),i=Q();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(l.status===404)throw new Ie("No matching records found");if(l.status===422)throw new Ps("Request does not conform to schema or semantic constraints");if(l.body==null)throw new ur("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let f=await l.json();for(let d of f.Peers){let h=this.#e(d);h!=null&&(yield h)}}else for await(let f of da(ou(l.body))){let d=this.#e(f);d!=null&&(yield d)}}catch(a){Ve.error("getPeers errored:",a)}finally{o.clear(),i.resolve(),Ve("getPeers finished: %c",e)}}async getIPNS(e,t={}){Ve("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),o=de([this.shutDownController.signal,n,t.signal]);let s=Q(),i=Q();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.clientUrl}routing/v1/ipns/${e}`;try{await s.promise;let c={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o},l=await this.#r(a,c);if(Ve("getIPNS GET %s %d",a,l.status),l.status===404)throw new Ie("No matching records found");if(l.status===422)throw new Ps("Request does not conform to schema or semantic constraints");if(l.body==null)throw new ur("GET ipns response had no body");let u=await l.arrayBuffer(),f=new Uint8Array(u,0,u.byteLength);return t.validate!==!1&&await Px(fa(e.multihash),f),kn(f)}catch(c){throw Ve.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),i.resolve(),Ve("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){Ve("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=de([this.shutDownController.signal,o,n.signal]);let i=Q(),a=Q();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e}`;try{await i.promise;let l=ua(t),u={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:s},f=await this.#r(c,u);if(Ve("putIPNS PUT %s %d",c,f.status),f.status!==200)throw new ur("PUT ipns response had status other than 200")}catch(l){throw Ve.error("putIPNS PUT %s error:",c,l.stack),l}finally{s.clear(),a.resolve(),Ve("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(X)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:Rt(e.ID),Addrs:n,Protocols:t}}catch(t){Ve.error("could not conform record to peer schema",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#r(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return Ve("returning cached response for %s",o),c;await this.cache?.delete(e)}}let s=this.inFlightRequests.get(o);if(s!=null){let c=await s;return Ve("deduplicating outgoing request for %s",o),c.clone()}let i=fetch(e,t).then(async c=>{if(this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,u=new Headers(c.headers);u.set("x-cache-expires",l.toString());let f=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:u});await this.cache.put(e,f)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}};function Rx(r,e={}){return new mu(new URL(r),e)}var Ox="[a-fA-F\\d:]",Tn=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Ox})|(?<=${Ox})(?=\\s|$))`:"",fr="(?: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}",Se="[a-fA-F\\d]{1,4}",gu=`
2
+ "use strict";var HeliaHttp=(()=>{var I1=Object.create;var Ua=Object.defineProperty;var C1=Object.getOwnPropertyDescriptor;var _1=Object.getOwnPropertyNames;var T1=Object.getPrototypeOf,k1=Object.prototype.hasOwnProperty;var xr=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),_e=(r,e)=>{for(var t in e)Ua(r,t,{get:e[t],enumerable:!0})},Wg=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _1(e))!k1.call(r,o)&&o!==t&&Ua(r,o,{get:()=>e[o],enumerable:!(n=C1(e,o))||n.enumerable});return r};var vn=(r,e,t)=>(t=r!=null?I1(T1(r)):{},Wg(e||!r||!r.__esModule?Ua(t,"default",{value:r,enumerable:!0}):t,r)),P1=r=>Wg(Ua({},"__esModule",{value:!0}),r);var ww=xr(Ei=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var l,u,f,d;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[l,u,f,d].join(".")},i=function(c){var l,u,f,d,h,m;for(l=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}m=e(c),h=m[0],u=m[1],c=c.substring(u),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var l,u,f,d,h;for(d=0,l=10,u="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,l=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,l=8,u="7")),h=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)d=d*l+(t(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")d=d*l+(10+t(c[f])-s)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*l+(10+t(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===h)throw new Error("empty octet");return[d,f]},r=(function(){function c(l,u){var f,d,h,m;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(m=l.split("/",2),l=m[0],u=m[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(g){throw f=g,new Error("Invalid mask: "+u)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(g){throw f=g,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,f,d;for(d=i(this.first),f=i(this.last),u=0;d<=f;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),Ei.ip2long=i,Ei.long2ip=a,Ei.Netmask=r}).call(Ei)});var jb=xr((F5,zp)=>{"use strict";var dC=Object.prototype.hasOwnProperty,ct="~";function qi(){}Object.create&&(qi.prototype=Object.create(null),new qi().__proto__||(ct=!1));function hC(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Wb(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new hC(t,n||r,o),i=ct?ct+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function ul(r,e){--r._eventsCount===0?r._events=new qi:delete r._events[e]}function rt(){this._events=new qi,this._eventsCount=0}rt.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)dC.call(t,n)&&e.push(ct?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};rt.prototype.listeners=function(e){var t=ct?ct+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};rt.prototype.listenerCount=function(e){var t=ct?ct+e:e,n=this._events[t];return n?n.fn?1:n.length:0};rt.prototype.emit=function(e,t,n,o,s,i){var a=ct?ct+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};rt.prototype.on=function(e,t,n){return Wb(this,e,t,n,!1)};rt.prototype.once=function(e,t,n){return Wb(this,e,t,n,!0)};rt.prototype.removeListener=function(e,t,n,o){var s=ct?ct+e:e;if(!this._events[s])return this;if(!t)return ul(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&ul(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:ul(this,s)}return this};rt.prototype.removeAllListeners=function(e){var t;return e?(t=ct?ct+e:e,this._events[t]&&ul(this,t)):(this._events=new qi,this._eventsCount=0),this};rt.prototype.off=rt.prototype.removeListener;rt.prototype.addListener=rt.prototype.on;rt.prefixed=ct;rt.EventEmitter=rt;typeof zp<"u"&&(zp.exports=rt)});var Xb=xr((aO,Zb)=>{Zb.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var rg=xr((C9,tg)=>{var I9=(function(){typeof tg<"u"&&(tg.exports=g);var r=86400,e=3200,t=146097*e/400,n=r*t,o=1e3*n,s=864e13,i=4294967296,a=1e6,c="000000000",l=Math.trunc||function(b){var v=b-b%1;return v==0&&(b<0||b===0&&1/b!=1/0)?-0:v},u=g.prototype,f=(g.fromDate=function(b){return new g(+b)},g.fromInt64BE=N(0,1,2,3,0,4),g.fromInt64LE=N(3,2,1,0,4,0),g.fromString=function(R){var v,L=new g,R=(R+="").replace(/^\s*[+\-]?\d+/,function(E){var E=+E,S=1970+(E-1970)%400;return L.year=E-S,S}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function(k,E,S){return E<0&&(S*=-1),v=6e4*(60*+E+ +S),""}).replace(/\.\d+$/,function(k){return L.nano=+(k+c).substr(1,9),""}).split(/\D+/);if(1<R.length?R[1]--:R[1]=0,L.time=v=Date.UTC.apply(Date,R)-(v||0),isNaN(v))throw new TypeError("Invalid Date");return y(L)},g.fromTimeT=function(b){return P(b,0)},u.year=0,u.time=0,u.nano=0,u.addNano=function(b){return this.nano+=+b||0,this},u.getNano=function(){var b=y(this);return(b.time%1e3*a+ +b.nano+1e9)%1e9},u.getTimeT=function(){var v=y(this),b=Math.floor(v.time/1e3),v=v.year;return v&&(b+=v*t*r/e),b},u.getYear=function(){return this.toDate().getUTCFullYear()+this.year},u.toDate=function(){return x(y(this).time)},u.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},u.toString=function(b){var v=this,L=v.toDate(),R={H:function(){return G(L.getUTCHours())},L:function(){return Y(L.getUTCMilliseconds(),3)},M:function(){return G(L.getUTCMinutes())},N:function(){return Y(v.getNano(),9)},S:function(){return G(L.getUTCSeconds())},Y:function(){var k=v.getYear();return 999999<k?"+"+k:9999<k?"+"+Y(k,6):0<=k?Y(k,4):-999999<=k?"-"+Y(-k,6):k},a:function(){return h[L.getUTCDay()]},b:function(){return d[L.getUTCMonth()]},d:function(){return G(L.getUTCDate())},e:function(){return(function(k){return(9<k?"":" ")+(0|k)})(L.getUTCDate())},m:function(){return G(L.getUTCMonth()+1)}};return(function k(E){return E.replace(/%./g,function(S){var _=S[1],w=m[_],_=R[_];return w?k(w):_?_():S})})(b||f)},u.writeInt64BE=A(0,1,2,3,0,4),u.writeInt64LE=A(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m={"%":"%",F:"%Y-%m-%d",n:`
3
+ `,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return g;function g(b,v,L){var R=this;if(!(R instanceof g))return new g(b,v,L);R.time=+b||0,R.nano=+v||0,R.year=+L||0,y(R)}function y(b){var v,L,R,k=b.year,E=b.time,S=b.nano,w=((S<0||a<=S)&&(S-=(L=Math.floor(S/a))*a,E+=L,L=1),k%e);return(E<-s||s<E||w)&&((v=l(E/o))&&(k+=v*e,E-=v*o),(R=x(E)).setUTCFullYear(w+R.getUTCFullYear()),R=(E=+R)+(v=l((k-=w)/e))*o,v&&-s<=R&&R<=s&&(k-=v*e,E=R),L=1),L&&(b.year=k,b.time=E,b.nano=S),b}function x(b){var v=new Date(0);return v.setTime(b),v}function P(k,R){k=+k||0;var L=l((R=(R|0)*i)/n)+l(k/n),R=R%n+k%n,k=l(R/n);return k&&(L+=k,R-=k*n),new g(1e3*R,0,L*e)}function A(b,v,L,R,k,E){return function(w,_){var M=y(this);w=w||new Array(8),H(w,_|=0);var $=Math.floor(M.time/1e3),M=M.year*(t*r/e),O=l(M/i)+l($/i),M=M%i+$%i,$=Math.floor(M/i);return $&&(O+=$,M-=$*i),S(w,_+k,O),S(w,_+E,M),w};function S(w,_,O){w[_+b]=O>>24&255,w[_+v]=O>>16&255,w[_+L]=O>>8&255,w[_+R]=255&O}}function N(b,v,L,R,k,E){return function(w,_){H(w,_|=0);var O=S(w,_+k);return P(S(w,_+E),O)};function S(w,_){return 16777216*w[_+b]+(w[_+v]<<16|w[_+L]<<8|w[_+R])}}function H(b,v){if(b=b&&b.length,b==null)throw new TypeError("Invalid Buffer");if(b<v+8)throw new RangeError("Out of range")}function G(b){return(9<b?"":"0")+(0|b)}function Y(b,v){return(c+(0|b)).substr(-v)}})()});var AE=xr((UW,SE)=>{"use strict";function Fk(r){return r>=55296&&r<=56319}function $k(r){return r>=56320&&r<=57343}SE.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var o=t.length,s=0,i,a,c=0;c<o;c+=1){if(i=t.charCodeAt(c),a=t[c],Fk(i)&&$k(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),s+=e(a),s===n)return t.slice(0,c+1);if(s>n)return t.slice(0,c-a.length+1)}return t}});var CE=xr((FW,IE)=>{"use strict";function Vk(r){return r>=55296&&r<=56319}function Kk(r){return r>=56320&&r<=57343}IE.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,o=null,s=null,i=0;i<t;i++)o=e.charCodeAt(i),Kk(o)?s!=null&&Vk(s)?n+=1:n+=3:o<=127?n+=1:o>=128&&o<=2047?n+=2:o>=2048&&o<=65535&&(n+=3),s=o;return n}});var TE=xr(($W,_E)=>{"use strict";var Hk=AE(),qk=CE();_E.exports=Hk.bind(null,qk)});var BE=xr((VW,PE)=>{"use strict";var zk=TE(),Gk=/[\/\?<>\\:\*\|"]/g,Wk=/[\x00-\x1f\x80-\x9f]/g,jk=/^\.+$/,Yk=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,Zk=/[\. ]+$/;function kE(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(Gk,e).replace(Wk,e).replace(jk,e).replace(Yk,e).replace(Zk,e);return zk(t,255)}PE.exports=function(r,e){var t=e&&e.replacement||"",n=kE(r,t);return t===""?n:kE(n,"")}});var DE=xr(Ds=>{"use strict";var Jk="[object ArrayBuffer]",$r=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Jk}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},Og="string",Qk=/^[0-9a-f\s]+$/i,e6=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,t6=/^[a-zA-Z0-9-_]+$/,vf=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=$r.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},Nt=class{static toString(e,t=!1){let n=$r.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},Ef=class r{static isHex(e){return typeof e===Og&&Qk.test(e)}static isBase64(e){return typeof e===Og&&e6.test(e)}static isBase64Url(e){return typeof e===Og&&t6.test(e)}static ToString(e,t="utf8"){let n=$r.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Nt.toString(n,!0);case"utf16":case"utf16be":return Nt.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Nt.fromString(e,!0);case"utf16":case"utf16be":return Nt.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=$r.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return vf.fromString(e);case"utf16":case"utf16be":return Nt.fromString(e);case"utf16le":case"usc2":return Nt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return vf.toString(e);case"utf16":case"utf16be":return Nt.toString(e);case"utf16le":case"usc2":return Nt.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=$r.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=$r.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return Nt.toString(e,t)}static FromUtf16String(e,t=!1){return Nt.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};Ef.DEFAULT_UTF8_ENCODING="utf8";function r6(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function n6(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function o6(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}Ds.BufferSourceConverter=$r;Ds.Convert=Ef;Ds.assign=r6;Ds.combine=n6;Ds.isEqual=o6});var v6={};_e(v6,{DEFAULT_SESSION_MAX_PROVIDERS:()=>rm,DEFAULT_SESSION_MIN_PROVIDERS:()=>tm,InsufficientProvidersError:()=>Wi,InvalidCodecError:()=>nm,NoRoutersAvailableError:()=>mn,UnknownCodecError:()=>Yi,UnknownHashAlgorithmError:()=>ji,createHeliaHTTP:()=>x6,heliaDefaults:()=>A1});var jg=Symbol.for("@libp2p/connection");var bo=Symbol.for("@libp2p/content-routing");var mt=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var C=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},xo=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Os=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var En=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}};var Rt=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},vo=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Wr=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Fa=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Eo=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},$a=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Va=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Ka=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},vr=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var So=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}};var Ms=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Ha=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},qa=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Ot=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var za=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}};var pd=Symbol.for("@libp2p/peer-discovery");var Ga=Symbol.for("@libp2p/peer-id");function sr(r){return!!r?.[Ga]}var Ao=Symbol.for("@libp2p/peer-routing");var md="keep-alive";function Wa(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function ir(...r){let e=[];for(let t of r)Wa(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function ar(...r){let e=[];for(let t of r)Wa(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var D6=Symbol.for("@libp2p/transport");var Us;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Us||(Us={}));var De=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var Sn=Symbol.for("@libp2p/service-capabilities"),gd=Symbol.for("@libp2p/service-dependencies");function me(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Z=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Fs=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},$s=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},ja=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Yg={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new ja("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Te=Yg;var Ed={};_e(Ed,{base58btc:()=>ee,base58flickr:()=>M1});var h8=new Uint8Array(0);function Zg(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Mt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Xg(r){return new TextEncoder().encode(r)}function Jg(r){return new TextDecoder().decode(r)}function B1(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(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 g=0,y=0,x=0,P=m.length;x!==P&&m[x]===0;)x++,g++;for(var A=(P-x)*u+1>>>0,N=new Uint8Array(A);x!==P;){for(var H=m[x],G=0,Y=A-1;(H!==0||G<y)&&Y!==-1;Y--,G++)H+=256*N[Y]>>>0,N[Y]=H%a>>>0,H=H/a>>>0;if(H!==0)throw new Error("Non-zero carry");y=G,x++}for(var b=A-y;b!==A&&N[b]===0;)b++;for(var v=c.repeat(g);b<A;++b)v+=r.charAt(N[b]);return v}function d(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var g=0;if(m[g]!==" "){for(var y=0,x=0;m[g]===c;)y++,g++;for(var P=(m.length-g)*l+1>>>0,A=new Uint8Array(P);m[g];){var N=t[m.charCodeAt(g)];if(N===255)return;for(var H=0,G=P-1;(N!==0||H<x)&&G!==-1;G--,H++)N+=a*A[G]>>>0,A[G]=N%256>>>0,N=N/256>>>0;if(N!==0)throw new Error("Non-zero carry");x=H,g++}if(m[g]!==" "){for(var Y=P-x;Y!==P&&A[Y]===0;)Y++;for(var b=new Uint8Array(y+(P-Y)),v=y;Y!==P;)b[v++]=A[Y++];return b}}}function h(m){var g=d(m);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var D1=B1,L1=D1,Qg=L1;var wd=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},bd=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ey(this,e)}},xd=class{decoders;constructor(e){this.decoders=e}or(e){return ey(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ey(r,e){return new xd({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var vd=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new wd(e,t,n),this.decoder=new bd(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Io({name:r,prefix:e,encode:t,decode:n}){return new vd(r,e,t,n)}function jr({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Qg(t,r);return Io({prefix:e,name:r,encode:n,decode:s=>Mt(o(s))})}function N1(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function R1(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function O1(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Ae({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=O1(n);return Io({prefix:e,name:r,encode(s){return R1(s,n,t)},decode(s){return N1(s,o,t,r)}})}var ee=jr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),M1=jr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Sd={};_e(Sd,{base32:()=>ge,base32hex:()=>V1,base32hexpad:()=>H1,base32hexpadupper:()=>q1,base32hexupper:()=>K1,base32pad:()=>F1,base32padupper:()=>$1,base32upper:()=>U1,base32z:()=>z1});var ge=Ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),U1=Ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),F1=Ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$1=Ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),V1=Ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),K1=Ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),H1=Ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),q1=Ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),z1=Ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ad={};_e(Ad,{base36:()=>cr,base36upper:()=>G1});var cr=jr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),G1=jr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var W1=ny,ty=128,j1=127,Y1=~j1,Z1=Math.pow(2,31);function ny(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Z1;)e[t++]=r&255|ty,r/=128;for(;r&Y1;)e[t++]=r&255|ty,r>>>=7;return e[t]=r|0,ny.bytes=t-n+1,e}var X1=Id,J1=128,ry=127;function Id(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Id.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&ry)<<o:(i&ry)*Math.pow(2,o),o+=7}while(i>=J1);return Id.bytes=s-n,t}var Q1=Math.pow(2,7),eS=Math.pow(2,14),tS=Math.pow(2,21),rS=Math.pow(2,28),nS=Math.pow(2,35),oS=Math.pow(2,42),sS=Math.pow(2,49),iS=Math.pow(2,56),aS=Math.pow(2,63),cS=function(r){return r<Q1?1:r<eS?2:r<tS?3:r<rS?4:r<nS?5:r<oS?6:r<sS?7:r<iS?8:r<aS?9:10},lS={encode:W1,decode:X1,encodingLength:cS},uS=lS,Vs=uS;function Ks(r,e=0){return[Vs.decode(r,e),Vs.decode.bytes]}function Co(r,e,t=0){return Vs.encode(r,e,t),e}function _o(r){return Vs.encodingLength(r)}function lr(r,e){let t=e.byteLength,n=_o(r),o=n+_o(t),s=new Uint8Array(o+t);return Co(r,s,0),Co(t,s,n),s.set(e,o),new To(r,t,e,s)}function Xe(r){let e=Mt(r),[t,n]=Ks(e),[o,s]=Ks(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new To(t,o,i,e)}function oy(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Zg(r.bytes,t.bytes)}}var To=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function sy(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return dS(t,Cd(r),e??ee.encoder);default:return hS(t,Cd(r),e??ge.encoder)}}var iy=new WeakMap;function Cd(r){let e=iy.get(r);if(e==null){let t=new Map;return iy.set(r,t),t}return e}var V=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Hs)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==pS)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=lr(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&oy(e.multihash,n.multihash)}toString(e){return sy(this,e)}toJSON(){return{"/":sy(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??ay(n,o,s.bytes))}else if(t[mS]===!0){let{version:n,multihash:o,code:s}=t,i=Xe(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Hs)throw new Error(`Version 0 CID must use dag-pb (code: ${Hs}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=ay(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Hs,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Mt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new To(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Ks(e.subarray(t));return t+=d,f},o=n(),s=Hs;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=fS(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Cd(s).set(n,e),s}};function fS(r,e){switch(r[0]){case"Q":{let t=e??ee;return[ee.prefix,t.decode(`${ee.prefix}${r}`)]}case ee.prefix:{let t=e??ee;return[ee.prefix,t.decode(r)]}case ge.prefix:{let t=e??ge;return[ge.prefix,t.decode(r)]}case cr.prefix:{let t=e??cr;return[cr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function dS(r,e,t){let{prefix:n}=t;if(n!==ee.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function hS(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Hs=112,pS=18;function ay(r,e,t){let n=_o(r),o=n+_o(e),s=new Uint8Array(o+t.byteLength);return Co(r,s,0),Co(e,s,n),s.set(t,o),s}var mS=Symbol.for("@ipld/js-cid/CID");var _d={};_e(_d,{identity:()=>ke});var cy=0,gS="identity",ly=Mt;function yS(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return lr(cy,ly(r))}var ke={code:cy,name:gS,encode:ly,digest:yS};function W(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Ie(r=0){return new Uint8Array(r)}function Je(r=0){return new Uint8Array(r)}function ye(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=Je(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var fy=Symbol.for("@achingbrain/uint8arraylist");function uy(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function ko(r){return!!r?.[fy]}var ae=class r{bufs;length;[fy]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(ko(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(ko(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=uy(this.bufs,e);return t.buf[t.index]}set(e,t){let n=uy(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(ko(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:o}=this._subList(e,t);return ye(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:ye(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ko(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Je(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=Ie(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=Ie(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=Ie(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Je(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=Ie(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=Ie(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=Ie(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=Ie(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=Ie(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!W(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Td={};_e(Td,{base10:()=>wS});var wS=jr({prefix:"9",name:"base10",alphabet:"0123456789"});var kd={};_e(kd,{base16:()=>bS,base16upper:()=>xS});var bS=Ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),xS=Ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Pd={};_e(Pd,{base2:()=>vS});var vS=Ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Bd={};_e(Bd,{base256emoji:()=>CS});var dy=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}"),ES=dy.reduce((r,e,t)=>(r[t]=e,r),[]),SS=dy.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function AS(r){return r.reduce((e,t)=>(e+=ES[t],e),"")}function IS(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=SS[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var CS=Io({prefix:"\u{1F680}",name:"base256emoji",encode:AS,decode:IS});var Dd={};_e(Dd,{base64:()=>Pe,base64pad:()=>_S,base64url:()=>qs,base64urlpad:()=>TS});var Pe=Ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_S=Ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),qs=Ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),TS=Ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ld={};_e(Ld,{base8:()=>kS});var kS=Ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Nd={};_e(Nd,{identity:()=>PS});var PS=Io({prefix:"\0",name:"identity",encode:r=>Jg(r),decode:r=>Xg(r)});var Za={};_e(Za,{code:()=>Rd,decode:()=>RS,encode:()=>NS,name:()=>LS});var BS=new TextEncoder,DS=new TextDecoder,LS="json",Rd=512;function NS(r){return BS.encode(JSON.stringify(r))}function RS(r){return JSON.parse(DS.decode(r))}var Gs={};_e(Gs,{code:()=>zs,decode:()=>US,encode:()=>MS,name:()=>OS});var OS="raw",zs=85;function MS(r){return Mt(r)}function US(r){return Mt(r)}var Ud={};_e(Ud,{sha256:()=>gt,sha512:()=>Xa});var FS=20;function Md({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Od(r,e,t,n,o)}var Od=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??FS,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?hy(n,this.code,t?.truncate):n.then(o=>hy(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function hy(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return lr(e,r)}function my(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var gt=Md({name:"sha2-256",code:18,encode:my("SHA-256")}),Xa=Md({name:"sha2-512",code:19,encode:my("SHA-512")});var An={...Nd,...Pd,...Ld,...Td,...kd,...Sd,...Ad,...Ed,...Dd,...Bd},aP={...Ud,..._d};function yy(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var gy=yy("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Fd=yy("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Je(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),$S={utf8:gy,"utf-8":gy,hex:An.base16,latin1:Fd,ascii:Fd,binary:Fd,...An},Ja=$S;function T(r,e="utf8"){let t=Ja[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function B(r,e="utf8"){let t=Ja[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var VS=parseInt("11111",2),$d=parseInt("10000000",2),KS=parseInt("01111111",2),wy={0:Ws,1:Ws,2:HS,3:GS,4:WS,5:zS,6:qS,16:Ws,22:Ws,48:Ws};function _t(r,e={offset:0}){let t=r[e.offset]&VS;if(e.offset++,wy[t]!=null)return wy[t](r,e);throw new Error("No decoder for tag "+t)}function js(r,e){let t=0;if((r[e.offset]&$d)===$d){let n=r[e.offset]&KS,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function Ws(r,e){js(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=_t(r,e);if(n===null)break;t.push(n)}return t}function HS(r,e){let t=js(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function qS(r,e){let t=js(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function zS(r,e){return e.offset++,null}function GS(r,e){let t=js(r,e),n=r[e.offset];e.offset++;let o=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function WS(r,e){let t=js(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function jS(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new ae;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Qa(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=jS(r.byteLength);return new ae(Uint8Array.from([e.byteLength|$d]),e)}function st(r){let e=new ae,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new ae(Uint8Array.from([2]),Qa(e),e)}function Ys(r){let e=Uint8Array.from([0]),t=new ae(e,r);return new ae(Uint8Array.from([3]),Qa(t),t)}function by(r){return new ae(Uint8Array.from([4]),Qa(r),r)}function Ft(r,e=48){let t=new ae;for(let n of r)t.append(n);return new ae(Uint8Array.from([e]),Qa(t),t)}var xy="1.2.840.10045.3.1.7",vy="1.3.132.0.34",Ey="1.3.132.0.35";async function Sy(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function Ay(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Iy(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var YS=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ZS=Uint8Array.from([6,5,43,129,4,0,34]),XS=Uint8Array.from([6,5,43,129,4,0,35]),Cy={ext:!0,kty:"EC",crv:"P-256"},_y={ext:!0,kty:"EC",crv:"P-384"},Ty={ext:!0,kty:"EC",crv:"P-521"},Po=32,Bo=48,Do=66;function ky(r){let e=_t(r);return Vd(e)}function Vd(r){let e=r[1],t=B(e,"base64url"),n=r[2][1][0],o=1,s,i;if(e.byteLength===Po)return s=B(n.subarray(o,o+Po),"base64url"),i=B(n.subarray(o+Po),"base64url"),new Cn({...Cy,key_ops:["sign"],d:t,x:s,y:i});if(e.byteLength===Bo)return s=B(n.subarray(o,o+Bo),"base64url"),i=B(n.subarray(o+Bo),"base64url"),new Cn({..._y,key_ops:["sign"],d:t,x:s,y:i});if(e.byteLength===Do)return s=B(n.subarray(o,o+Do),"base64url"),i=B(n.subarray(o+Do),"base64url"),new Cn({...Ty,key_ops:["sign"],d:t,x:s,y:i});throw new C(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function Kd(r){let e=_t(r);return Py(e)}function Py(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===Po*2+1)return n=B(e.subarray(t,t+Po),"base64url"),o=B(e.subarray(t+Po),"base64url"),new In({...Cy,key_ops:["verify"],x:n,y:o});if(e.byteLength===Bo*2+1)return n=B(e.subarray(t,t+Bo),"base64url"),o=B(e.subarray(t+Bo),"base64url"),new In({..._y,key_ops:["verify"],x:n,y:o});if(e.byteLength===Do*2+1)return n=B(e.subarray(t,t+Do),"base64url"),o=B(e.subarray(t+Do),"base64url"),new In({...Ty,key_ops:["verify"],x:n,y:o});throw new C(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function By(r){return Ft([st(Uint8Array.from([1])),by(T(r.d??"","base64url")),Ft([Ly(r.crv)],160),Ft([Ys(new ae(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function Dy(r){return Ft([st(Uint8Array.from([1])),Ft([Ly(r.crv)],160),Ft([Ys(new ae(Uint8Array.from([4]),T(r.x??"","base64url"),T(r.y??"","base64url")))],161)]).subarray()}function Ly(r){if(r==="P-256")return YS;if(r==="P-384")return ZS;if(r==="P-521")return XS;throw new C(`Invalid curve ${r}`)}async function Ny(r="P-256"){let e=await Sy(r);return new Cn(e.privateKey)}var In=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Dy(this.jwk)),this._raw}toMultihash(){return ke.digest(Tt(this))}toCID(){return V.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async verify(e,t,n){return Iy(this.jwk,t,e,n)}},Cn=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new In({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=By(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}async sign(e,t){return Ay(this.jwk,e,t)}};function _n(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ut(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function Q(r,e,t=""){let n=_n(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Lo(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ut(r.outputLen),ut(r.blockLen)}function No(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Oy(r,e){Q(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function ft(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Tn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function $t(r,e){return r<<32-e|r>>>e}function ec(r,e){return r<<e|r>>>32-e>>>0}var My=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",JS=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Sr(r){if(Q(r),My)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=JS[r[t]];return e}var Er={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ry(r){if(r>=Er._0&&r<=Er._9)return r-Er._0;if(r>=Er.A&&r<=Er.F)return r-(Er.A-10);if(r>=Er.a&&r<=Er.f)return r-(Er.a-10)}function Ar(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(My)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=Ry(r.charCodeAt(s)),a=Ry(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}var QS=async()=>{};async function Uy(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let s=Date.now()-n;s>=0&&s<e||(await QS(),n+=s)}}function e2(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Hd(r,e=""){return typeof r=="string"?e2(r):Q(r,void 0,e)}function dt(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Q(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function Fy(r,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new Error("options must be object or undefined");return Object.assign(r,e)}function Zs(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Yr(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var qd=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function tc(r,e,t){return r&e^~r&t}function rc(r,e,t){return r&e^r&t^e&t}var kn=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Tn(this.buffer)}update(e){No(this),Q(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Tn(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){No(this),Oy(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,ft(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Tn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ir=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Fe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var nc=BigInt(4294967295),$y=BigInt(32);function t2(r,e=!1){return e?{h:Number(r&nc),l:Number(r>>$y&nc)}:{h:Number(r>>$y&nc)|0,l:Number(r&nc)|0}}function Vy(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=t2(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var zd=(r,e,t)=>r>>>t,Gd=(r,e,t)=>r<<32-t|e>>>t,Pn=(r,e,t)=>r>>>t|e<<32-t,Bn=(r,e,t)=>r<<32-t|e>>>t,Xs=(r,e,t)=>r<<64-t|e>>>t-32,Js=(r,e,t)=>r>>>t-32|e<<64-t;function ur(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Ky=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Hy=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,qy=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),zy=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Gy=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Wy=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var n2=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Zr=new Uint32Array(64),Wd=class extends kn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)Zr[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=Zr[f-15],h=Zr[f-2],m=$t(d,7)^$t(d,18)^d>>>3,g=$t(h,17)^$t(h,19)^h>>>10;Zr[f]=g+Zr[f-7]+m+Zr[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=$t(a,6)^$t(a,11)^$t(a,25),h=u+d+tc(a,c,l)+n2[f]+Zr[f]|0,g=($t(n,2)^$t(n,13)^$t(n,22))+rc(n,o,s)|0;u=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){ft(Zr)}destroy(){this.set(0,0,0,0,0,0,0,0),ft(this.buffer)}},jd=class extends Wd{A=Ir[0]|0;B=Ir[1]|0;C=Ir[2]|0;D=Ir[3]|0;E=Ir[4]|0;F=Ir[5]|0;G=Ir[6]|0;H=Ir[7]|0;constructor(){super(32)}};var jy=Vy(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),o2=jy[0],s2=jy[1],Xr=new Uint32Array(80),Jr=new Uint32Array(80),Yd=class extends kn{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:h,Gl:m,Hh:g,Hl:y}=this;return[e,t,n,o,s,i,a,c,l,u,f,d,h,m,g,y]}set(e,t,n,o,s,i,a,c,l,u,f,d,h,m,g,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=m|0,this.Hh=g|0,this.Hl=y|0}process(e,t){for(let A=0;A<16;A++,t+=4)Xr[A]=e.getUint32(t),Jr[A]=e.getUint32(t+=4);for(let A=16;A<80;A++){let N=Xr[A-15]|0,H=Jr[A-15]|0,G=Pn(N,H,1)^Pn(N,H,8)^zd(N,H,7),Y=Bn(N,H,1)^Bn(N,H,8)^Gd(N,H,7),b=Xr[A-2]|0,v=Jr[A-2]|0,L=Pn(b,v,19)^Xs(b,v,61)^zd(b,v,6),R=Bn(b,v,19)^Js(b,v,61)^Gd(b,v,6),k=qy(Y,R,Jr[A-7],Jr[A-16]),E=zy(k,G,L,Xr[A-7],Xr[A-16]);Xr[A]=E|0,Jr[A]=k|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:h,Fl:m,Gh:g,Gl:y,Hh:x,Hl:P}=this;for(let A=0;A<80;A++){let N=Pn(f,d,14)^Pn(f,d,18)^Xs(f,d,41),H=Bn(f,d,14)^Bn(f,d,18)^Js(f,d,41),G=f&h^~f&g,Y=d&m^~d&y,b=Gy(P,H,Y,s2[A],Jr[A]),v=Wy(b,x,N,G,o2[A],Xr[A]),L=b|0,R=Pn(n,o,28)^Xs(n,o,34)^Xs(n,o,39),k=Bn(n,o,28)^Js(n,o,34)^Js(n,o,39),E=n&s^n&a^s&a,S=o&i^o&c^i&c;x=g|0,P=y|0,g=h|0,y=m|0,h=f|0,m=d|0,{h:f,l:d}=ur(l|0,u|0,v|0,L|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let w=Ky(L,k,S);n=Hy(w,v,R,E),o=w|0}({h:n,l:o}=ur(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ur(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ur(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=ur(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=ur(this.Eh|0,this.El|0,f|0,d|0),{h,l:m}=ur(this.Fh|0,this.Fl|0,h|0,m|0),{h:g,l:y}=ur(this.Gh|0,this.Gl|0,g|0,y|0),{h:x,l:P}=ur(this.Hh|0,this.Hl|0,x|0,P|0),this.set(n,o,s,i,a,c,l,u,f,d,h,m,g,y,x,P)}roundClean(){ft(Xr,Jr)}destroy(){ft(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Zd=class extends Yd{Ah=Fe[0]|0;Al=Fe[1]|0;Bh=Fe[2]|0;Bl=Fe[3]|0;Ch=Fe[4]|0;Cl=Fe[5]|0;Dh=Fe[6]|0;Dl=Fe[7]|0;Eh=Fe[8]|0;El=Fe[9]|0;Fh=Fe[10]|0;Fl=Fe[11]|0;Gh=Fe[12]|0;Gl=Fe[13]|0;Hh=Fe[14]|0;Hl=Fe[15]|0;constructor(){super(64)}};var Qr=Zs(()=>new jd,qd(1));var en=Zs(()=>new Zd,qd(3));var Jd=BigInt(0),Xd=BigInt(1);function Cr(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function Yy(r){if(typeof r=="bigint"){if(!oc(r))throw new Error("positive bigint expected, got "+r)}else ut(r);return r}function Qs(r){let e=Yy(r).toString(16);return e.length&1?"0"+e:e}function Zy(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Jd:BigInt("0x"+r)}function Ro(r){return Zy(Sr(r))}function Dn(r){return Zy(Sr(ic(Q(r)).reverse()))}function sc(r,e){ut(e),r=Yy(r);let t=Ar(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Qd(r,e){return sc(r,e).reverse()}function ic(r){return Uint8Array.from(r)}var oc=r=>typeof r=="bigint"&&Jd<=r;function i2(r,e,t){return oc(r)&&oc(e)&&oc(t)&&e<=r&&r<t}function ei(r,e,t,n){if(!i2(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function eh(r){let e;for(e=0;r>Jd;r>>=Xd,e+=1);return e}var ti=r=>(Xd<<BigInt(r))-Xd;function Xy(r,e,t){if(ut(r,"hashLen"),ut(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=y=>new Uint8Array(y),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,f=()=>{c.fill(1),l.fill(0),u=0},d=(...y)=>t(l,dt(c,...y)),h=(y=o)=>{l=d(s,y),c=d(),y.length!==0&&(l=d(i,y),c=d())},m=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,x=[];for(;y<e;){c=d();let P=c.slice();x.push(P),y+=c.length}return dt(...x)};return(y,x)=>{f(),h(y);let P;for(;!(P=x(m()));)h();return f(),P}}function tn(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}function Oo(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var it=BigInt(0),Le=BigInt(1),Ln=BigInt(2),e0=BigInt(3),t0=BigInt(4),r0=BigInt(5),a2=BigInt(7),n0=BigInt(8),c2=BigInt(9),o0=BigInt(16);function Ce(r,e){let t=r%e;return t>=it?t:e+t}function we(r,e,t){let n=r;for(;e-- >it;)n*=n,n%=t;return n}function Jy(r,e){if(r===it)throw new Error("invert: expected non-zero number");if(e<=it)throw new Error("invert: expected positive modulus, got "+e);let t=Ce(r,e),n=e,o=it,s=Le,i=Le,a=it;for(;t!==it;){let l=n/t,u=n%t,f=o-i*l,d=s-a*l;n=t,t=u,o=i,s=a,i=f,a=d}if(n!==Le)throw new Error("invert: does not exist");return Ce(o,e)}function rh(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function s0(r,e){let t=(r.ORDER+Le)/t0,n=r.pow(e,t);return rh(r,n,e),n}function l2(r,e){let t=(r.ORDER-r0)/n0,n=r.mul(e,Ln),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,Ln),o),a=r.mul(s,r.sub(i,r.ONE));return rh(r,a,e),a}function u2(r){let e=Mo(r),t=i0(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+a2)/o0;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),f=a.mul(l,o),d=a.mul(l,s),h=a.eql(a.sqr(u),c),m=a.eql(a.sqr(f),c);l=a.cmov(l,u,h),u=a.cmov(d,f,m);let g=a.eql(a.sqr(u),c),y=a.cmov(l,u,g);return rh(a,y,c),y}}function i0(r){if(r<e0)throw new Error("sqrt is not defined for small field");let e=r-Le,t=0;for(;e%Ln===it;)e/=Ln,t++;let n=Ln,o=Mo(r);for(;Qy(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return s0;let s=o.pow(n,e),i=(e+Le)/Ln;return function(c,l){if(c.is0(l))return l;if(Qy(c,l)!==1)throw new Error("Cannot find square root");let u=t,f=c.mul(c.ONE,s),d=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let m=1,g=c.sqr(d);for(;!c.eql(g,c.ONE);)if(m++,g=c.sqr(g),m===u)throw new Error("Cannot find square root");let y=Le<<BigInt(u-m-1),x=c.pow(f,y);u=m,f=c.sqr(x),d=c.mul(d,f),h=c.mul(h,x)}return h}}function f2(r){return r%t0===e0?s0:r%n0===r0?l2:r%o0===c2?u2(r):i0(r)}var a0=(r,e)=>(Ce(r,e)&Le)===Le,d2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function nh(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=d2.reduce((n,o)=>(n[o]="function",n),e);return tn(r,t),r}function h2(r,e,t){if(t<it)throw new Error("invalid exponent, negatives unsupported");if(t===it)return r.ONE;if(t===Le)return e;let n=r.ONE,o=e;for(;t>it;)t&Le&&(n=r.mul(n,o)),o=r.sqr(o),t>>=Le;return n}function ri(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function Qy(r,e){let t=(r.ORDER-Le)/Ln,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function p2(r,e){e!==void 0&&ut(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var th=class{ORDER;BITS;BYTES;isLE;ZERO=it;ONE=Le;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=it)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=p2(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Ce(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return it<=e&&e<this.ORDER}is0(e){return e===it}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Le)===Le}neg(e){return Ce(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Ce(e*e,this.ORDER)}add(e,t){return Ce(e+t,this.ORDER)}sub(e,t){return Ce(e-t,this.ORDER)}mul(e,t){return Ce(e*t,this.ORDER)}pow(e,t){return h2(this,e,t)}div(e,t){return Ce(e*Jy(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Jy(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=f2(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Qd(e,this.BYTES):sc(e,this.BYTES)}fromBytes(e,t=!1){Q(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Dn(e):Ro(e);if(a&&(c=Ce(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ri(this,e)}cmov(e,t,n){return n?t:e}};function Mo(r,e={}){return new th(r,e)}function c0(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function oh(r){let e=c0(r);return e+Math.ceil(e/2)}function sh(r,e,t=!1){Q(r);let n=r.length,o=c0(e),s=oh(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Dn(r):Ro(r),a=Ce(i,e-Le)+Le;return t?Qd(a,o):sc(a,o)}var Uo=BigInt(0),Nn=BigInt(1);function ni(r,e){let t=e.negate();return r?t:e}function Rn(r,e){let t=ri(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function d0(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function ih(r,e){d0(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=ti(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function l0(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=Nn);let l=e*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:h,offsetF:l}}var ah=new WeakMap,h0=new WeakMap;function ch(r){return h0.get(r)||1}function u0(r){if(r!==Uo)throw new Error("invalid wNAF")}var Fo=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let o=e;for(;t>Uo;)t&Nn&&(n=n.add(o)),o=o.double(),t>>=Nn;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=ih(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=ih(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:h}=l0(n,a,i);n=c,u?s=s.add(ni(d,t[h])):o=o.add(ni(f,t[l]))}return u0(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=ih(e,this.bits);for(let i=0;i<s.windows&&n!==Uo;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=l0(n,i,s);if(n=a,!l){let f=t[c];o=o.add(u?f.negate():f)}}return u0(n),o}getPrecomputes(e,t,n){let o=ah.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),ah.set(t,o))),o}cached(e,t,n){let o=ch(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=ch(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){d0(t,this.bits),h0.set(e,t),ah.delete(e)}hasCache(e){return ch(e)!==1}};function p0(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>Uo||n>Uo;)t&Nn&&(s=s.add(o)),n&Nn&&(i=i.add(o)),o=o.double(),t>>=Nn,n>>=Nn;return{p1:s,p2:i}}function f0(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return nh(e),e}else return Mo(r,{isLE:t})}function ac(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Uo))throw new Error(`CURVE.${c} must be positive bigint`)}let o=f0(e.p,t.Fp,n),s=f0(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function cc(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var rn=BigInt(0),Ne=BigInt(1),lh=BigInt(2),m2=BigInt(8);function g2(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function m0(r,e={}){let t=ac("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;tn(e,{},{uvRatio:"function"});let a=lh<<BigInt(o.BYTES*8)-Ne,c=y=>n.create(y),l=e.uvRatio||((y,x)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,x))}}catch{return{isValid:!1,value:rn}}});if(!g2(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(y,x,P=!1){let A=P?Ne:rn;return ei("coordinate "+y,x,A,a),x}function f(y){if(!(y instanceof m))throw new Error("EdwardsPoint expected")}let d=Oo((y,x)=>{let{X:P,Y:A,Z:N}=y,H=y.is0();x==null&&(x=H?m2:n.inv(N));let G=c(P*x),Y=c(A*x),b=n.mul(N,x);if(H)return{x:rn,y:Ne};if(b!==Ne)throw new Error("invZ was invalid");return{x:G,y:Y}}),h=Oo(y=>{let{a:x,d:P}=s;if(y.is0())throw new Error("bad point: ZERO");let{X:A,Y:N,Z:H,T:G}=y,Y=c(A*A),b=c(N*N),v=c(H*H),L=c(v*v),R=c(Y*x),k=c(v*c(R+b)),E=c(L+c(P*c(Y*b)));if(k!==E)throw new Error("bad point: equation left != right (1)");let S=c(A*N),w=c(H*G);if(S!==w)throw new Error("bad point: equation left != right (2)");return!0});class m{static BASE=new m(s.Gx,s.Gy,Ne,c(s.Gx*s.Gy));static ZERO=new m(rn,Ne,Ne,rn);static Fp=n;static Fn=o;X;Y;Z;T;constructor(x,P,A,N){this.X=u("x",x),this.Y=u("y",P),this.Z=u("z",A,!0),this.T=u("t",N),Object.freeze(this)}static CURVE(){return s}static fromAffine(x){if(x instanceof m)throw new Error("extended point not allowed");let{x:P,y:A}=x||{};return u("x",P),u("y",A),new m(P,A,Ne,c(P*A))}static fromBytes(x,P=!1){let A=n.BYTES,{a:N,d:H}=s;x=ic(Q(x,A,"point")),Cr(P,"zip215");let G=ic(x),Y=x[A-1];G[A-1]=Y&-129;let b=Dn(G),v=P?a:n.ORDER;ei("point.y",b,rn,v);let L=c(b*b),R=c(L-Ne),k=c(H*L-N),{isValid:E,value:S}=l(R,k);if(!E)throw new Error("bad point: invalid y coordinate");let w=(S&Ne)===Ne,_=(Y&128)!==0;if(!P&&S===rn&&_)throw new Error("bad point: x=0 and x_0=1");return _!==w&&(S=c(-S)),m.fromAffine({x:S,y:b})}static fromHex(x,P=!1){return m.fromBytes(Ar(x),P)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,P=!0){return g.createCache(this,x),P||this.multiply(lh),this}assertValidity(){h(this)}equals(x){f(x);let{X:P,Y:A,Z:N}=this,{X:H,Y:G,Z:Y}=x,b=c(P*Y),v=c(H*N),L=c(A*Y),R=c(G*N);return b===v&&L===R}is0(){return this.equals(m.ZERO)}negate(){return new m(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:x}=s,{X:P,Y:A,Z:N}=this,H=c(P*P),G=c(A*A),Y=c(lh*c(N*N)),b=c(x*H),v=P+A,L=c(c(v*v)-H-G),R=b+G,k=R-Y,E=b-G,S=c(L*k),w=c(R*E),_=c(L*E),O=c(k*R);return new m(S,w,O,_)}add(x){f(x);let{a:P,d:A}=s,{X:N,Y:H,Z:G,T:Y}=this,{X:b,Y:v,Z:L,T:R}=x,k=c(N*b),E=c(H*v),S=c(Y*A*R),w=c(G*L),_=c((N+H)*(b+v)-k-E),O=w-S,M=w+S,$=c(E-P*k),K=c(_*O),z=c(M*$),J=c(_*$),ve=c(O*M);return new m(K,z,ve,J)}subtract(x){return this.add(x.negate())}multiply(x){if(!o.isValidNot0(x))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:P,f:A}=g.cached(this,x,N=>Rn(m,N));return Rn(m,[P,A])[0]}multiplyUnsafe(x,P=m.ZERO){if(!o.isValid(x))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return x===rn?m.ZERO:this.is0()||x===Ne?this:g.unsafe(this,x,A=>Rn(m,A),P)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(x){return d(this,x)}clearCofactor(){return i===Ne?this:this.multiplyUnsafe(i)}toBytes(){let{x,y:P}=this.toAffine(),A=n.toBytes(P);return A[A.length-1]|=x&Ne?128:0,A}toHex(){return Sr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new Fo(m,o.BITS);return m.BASE.precompute(8),m}function g0(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');tn(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||Yr,c=t.adjustScalarBytes||(b=>b),l=t.domain||((b,v,L)=>{if(Cr(L,"phflag"),v.length||L)throw new Error("Contexts/pre-hash are not supported");return b});function u(b){return i.create(Dn(b))}function f(b){let v=A.secretKey;Q(b,A.secretKey,"secretKey");let L=Q(e(b),2*v,"hashedSecretKey"),R=c(L.slice(0,v)),k=L.slice(v,2*v),E=u(R);return{head:R,prefix:k,scalar:E}}function d(b){let{head:v,prefix:L,scalar:R}=f(b),k=o.multiply(R),E=k.toBytes();return{head:v,prefix:L,scalar:R,point:k,pointBytes:E}}function h(b){return d(b).pointBytes}function m(b=Uint8Array.of(),...v){let L=dt(...v);return u(e(l(L,Q(b,void 0,"context"),!!n)))}function g(b,v,L={}){b=Q(b,void 0,"message"),n&&(b=n(b));let{prefix:R,scalar:k,pointBytes:E}=d(v),S=m(L.context,R,b),w=o.multiply(S).toBytes(),_=m(L.context,w,E,b),O=i.create(S+_*k);if(!i.isValid(O))throw new Error("sign failed: invalid s");let M=dt(w,i.toBytes(O));return Q(M,A.signature,"result")}let y={zip215:!0};function x(b,v,L,R=y){let{context:k,zip215:E}=R,S=A.signature;b=Q(b,S,"signature"),v=Q(v,void 0,"message"),L=Q(L,A.publicKey,"publicKey"),E!==void 0&&Cr(E,"zip215"),n&&(v=n(v));let w=S/2,_=b.subarray(0,w),O=Dn(b.subarray(w,S)),M,$,K;try{M=r.fromBytes(L,E),$=r.fromBytes(_,E),K=o.multiplyUnsafe(O)}catch{return!1}if(!E&&M.isSmallOrder())return!1;let z=m(k,$.toBytes(),M.toBytes(),v);return $.add(M.multiplyUnsafe(z)).subtract(K).clearCofactor().is0()}let P=s.BYTES,A={secretKey:P,publicKey:P,signature:2*P,seed:P};function N(b=a(A.seed)){return Q(b,A.seed,"seed")}function H(b){return _n(b)&&b.length===i.BYTES}function G(b,v){try{return!!r.fromBytes(b,v)}catch{return!1}}let Y={getExtendedPublicKey:d,randomSecretKey:N,isValidSecretKey:H,isValidPublicKey:G,toMontgomery(b){let{y:v}=r.fromBytes(b),L=A.publicKey,R=L===32;if(!R&&L!==57)throw new Error("only defined for 25519 and 448");let k=R?s.div(Ne+v,Ne-v):s.div(v-Ne,v+Ne);return s.toBytes(k)},toMontgomerySecret(b){let v=A.secretKey;Q(b,v);let L=e(b.subarray(0,v));return c(L).subarray(0,v)}};return Object.freeze({keygen:cc(N,h),getPublicKey:h,sign:g,verify:x,utils:Y,Point:r,lengths:A})}var y2=BigInt(1),y0=BigInt(2);var w2=BigInt(5),b2=BigInt(8),uh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),x2={p:uh,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:b2,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function v2(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=uh,a=r*r%s*r%s,c=we(a,y0,s)*a%s,l=we(c,y2,s)*r%s,u=we(l,w2,s)*l%s,f=we(u,e,s)*u%s,d=we(f,t,s)*f%s,h=we(d,n,s)*d%s,m=we(h,o,s)*h%s,g=we(m,o,s)*h%s,y=we(g,e,s)*u%s;return{pow_p_5_8:we(y,y0,s)*r%s,b2:a}}function E2(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var w0=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function S2(r,e){let t=uh,n=Ce(e*e*e,t),o=Ce(n*n*e,t),s=v2(r*o).pow_p_5_8,i=Ce(r*n*s,t),a=Ce(e*i*i,t),c=i,l=Ce(i*w0,t),u=a===r,f=a===Ce(-r,t),d=a===Ce(-r*w0,t);return u&&(i=c),(f||d)&&(i=l),a0(i,t)&&(i=Ce(-i,t)),{isValid:u||f,value:i}}var A2=m0(x2,{uvRatio:S2});function I2(r){return g0(A2,en,Object.assign({adjustScalarBytes:E2},r))}var oi=I2({});var On=32,yt=64,fh=32;var $o,b0=(async()=>{try{return await Te.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function x0(){let r=oi.utils.randomSecretKey(),e=oi.getPublicKey(r);return{privateKey:P2(r,e),publicKey:e}}async function C2(r,e){let t;r.length===yt?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:B(r.subarray(32),"base64url"),d:B(t,"base64url"),ext:!0,key_ops:["sign"]},o=await Te.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await Te.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function _2(r,e){let t=r.subarray(0,fh);return oi.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function v0(r,e){return $o==null&&($o=await b0),$o?C2(r,e):_2(r,e)}async function T2(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Te.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Te.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function k2(r,e,t){return oi.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function E0(r,e,t){return $o==null&&($o=await b0),$o?T2(r,e,t):k2(r,e,t)}function P2(r,e){let t=new Uint8Array(yt);for(let n=0;n<fh;n++)t[n]=r[n],t[fh+n]=e[n];return t}function Vo(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var si=class{type="Ed25519";raw;constructor(e){this.raw=Ho(e,On)}toMultihash(){return ke.digest(Tt(this))}toCID(){return V.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=E0(this.raw,t,e);return Vo(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}},Ko=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Ho(e,yt),this.publicKey=new si(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=v0(this.raw,e);return Vo(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function dh(r){if(r.length>yt){r=Ho(r,yt+On);let n=r.subarray(0,yt),o=r.subarray(yt,r.length);return new Ko(n,o)}r=Ho(r,yt);let e=r.subarray(0,yt),t=r.subarray(On);return new Ko(e,t)}function hh(r){return r=Ho(r,On),new si(r)}async function A0(){let{privateKey:r,publicKey:e}=x0();return new Ko(r,e)}function Ho(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new C(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var B2=Math.pow(2,7),D2=Math.pow(2,14),L2=Math.pow(2,21),ph=Math.pow(2,28),mh=Math.pow(2,35),gh=Math.pow(2,42),yh=Math.pow(2,49),ce=128,Qe=127;function be(r){if(r<B2)return 1;if(r<D2)return 2;if(r<L2)return 3;if(r<ph)return 4;if(r<mh)return 5;if(r<gh)return 6;if(r<yh)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function _r(r,e,t=0){switch(be(r)){case 8:e[t++]=r&255|ce,r/=128;case 7:e[t++]=r&255|ce,r/=128;case 6:e[t++]=r&255|ce,r/=128;case 5:e[t++]=r&255|ce,r/=128;case 4:e[t++]=r&255|ce,r>>>=7;case 3:e[t++]=r&255|ce,r>>>=7;case 2:e[t++]=r&255|ce,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function N2(r,e,t=0){switch(be(r)){case 8:e.set(t++,r&255|ce),r/=128;case 7:e.set(t++,r&255|ce),r/=128;case 6:e.set(t++,r&255|ce),r/=128;case 5:e.set(t++,r&255|ce),r/=128;case 4:e.set(t++,r&255|ce),r>>>=7;case 3:e.set(t++,r&255|ce),r>>>=7;case 2:e.set(t++,r&255|ce),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function wh(r,e){let t=r[e],n=0;if(n+=t&Qe,t<ce||(t=r[e+1],n+=(t&Qe)<<7,t<ce)||(t=r[e+2],n+=(t&Qe)<<14,t<ce)||(t=r[e+3],n+=(t&Qe)<<21,t<ce)||(t=r[e+4],n+=(t&Qe)*ph,t<ce)||(t=r[e+5],n+=(t&Qe)*mh,t<ce)||(t=r[e+6],n+=(t&Qe)*gh,t<ce)||(t=r[e+7],n+=(t&Qe)*yh,t<ce))return n;throw new RangeError("Could not decode varint")}function R2(r,e){let t=r.get(e),n=0;if(n+=t&Qe,t<ce||(t=r.get(e+1),n+=(t&Qe)<<7,t<ce)||(t=r.get(e+2),n+=(t&Qe)<<14,t<ce)||(t=r.get(e+3),n+=(t&Qe)<<21,t<ce)||(t=r.get(e+4),n+=(t&Qe)*ph,t<ce)||(t=r.get(e+5),n+=(t&Qe)*mh,t<ce)||(t=r.get(e+6),n+=(t&Qe)*gh,t<ce)||(t=r.get(e+7),n+=(t&Qe)*yh,t<ce))return n;throw new RangeError("Could not decode varint")}function nn(r,e,t=0){return e==null&&(e=Je(be(r))),e instanceof Uint8Array?_r(r,e,t):N2(r,e,t)}function fr(r,e=0){return r instanceof Uint8Array?wh(r,e):R2(r,e)}var bh=new Float32Array([-0]),on=new Uint8Array(bh.buffer);function I0(r,e,t){bh[0]=r,e[t]=on[0],e[t+1]=on[1],e[t+2]=on[2],e[t+3]=on[3]}function C0(r,e){return on[0]=r[e],on[1]=r[e+1],on[2]=r[e+2],on[3]=r[e+3],bh[0]}var xh=new Float64Array([-0]),et=new Uint8Array(xh.buffer);function _0(r,e,t){xh[0]=r,e[t]=et[0],e[t+1]=et[1],e[t+2]=et[2],e[t+3]=et[3],e[t+4]=et[4],e[t+5]=et[5],e[t+6]=et[6],e[t+7]=et[7]}function T0(r,e){return et[0]=r[e],et[1]=r[e+1],et[2]=r[e+2],et[3]=r[e+3],et[4]=r[e+4],et[5]=r[e+5],et[6]=r[e+6],et[7]=r[e+7],xh[0]}var O2=BigInt(Number.MAX_SAFE_INTEGER),M2=BigInt(Number.MIN_SAFE_INTEGER),wt=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return Mn;if(e<O2&&e>M2)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>k0&&(o=0n,++n>k0&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Mn;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):Mn}},Mn=new wt(0,0);Mn.toBigInt=function(){return 0n};Mn.zzEncode=Mn.zzDecode=function(){return this};Mn.length=function(){return 1};var k0=4294967296n;function P0(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function B0(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function vh(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Vt(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function lc(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Eh=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Vt(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Vt(this,4);return lc(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Vt(this,4);return lc(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Vt(this,4);let e=C0(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Vt(this,4);let e=T0(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw Vt(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return B0(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Vt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Vt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new wt(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw Vt(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Vt(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Vt(this,8);let e=lc(this.buf,this.pos+=4),t=lc(this.buf,this.pos+=4);return new wt(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=wh(this.buf,this.pos);return this.pos+=be(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Sh(r){return new Eh(r instanceof Uint8Array?r:r.subarray())}function $e(r,e,t){let n=Sh(r);return e.decode(n,void 0,t)}function Ah(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return Je(i);o+i>e&&(n=Je(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Un=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Ih(){}var _h=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},U2=Ah();function F2(r){return globalThis.Buffer!=null?Je(r):U2(r)}var ai=class{len;head;tail;states;constructor(){this.len=0,this.head=new Un(Ih,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Un(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Th((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(uc,10,wt.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=wt.fromBigInt(e);return this._push(uc,t.length(),t)}uint64Number(e){return this._push(_r,be(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=wt.fromBigInt(e).zzEncode();return this._push(uc,t.length(),t)}sint64Number(e){let t=wt.fromNumber(e).zzEncode();return this._push(uc,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ch,1,e?1:0)}fixed32(e){return this._push(ii,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=wt.fromBigInt(e);return this._push(ii,4,t.lo)._push(ii,4,t.hi)}fixed64Number(e){let t=wt.fromNumber(e);return this._push(ii,4,t.lo)._push(ii,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(I0,4,e)}double(e){return this._push(_0,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Ch,1,0):this.uint32(t)._push(V2,t,e)}string(e){let t=P0(e);return t!==0?this.uint32(t)._push(vh,t,e):this._push(Ch,1,0)}fork(){return this.states=new _h(this),this.head=this.tail=new Un(Ih,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Un(Ih,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=F2(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Ch(r,e,t){e[t]=r&255}function $2(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Th=class extends Un{next;constructor(e,t){super($2,e,t),this.next=void 0}};function uc(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function ii(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function V2(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(ai.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(K2,e,r),this},ai.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(H2,e,r),this});function K2(r,e,t){e.set(r,t)}function H2(r,e,t){r.length<40?vh(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(T(r),t)}function kh(){return new ai}function Ve(r,e){let t=kh();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var zo;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(zo||(zo={}));function fc(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function ci(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return fc("enum",zo.VARINT,t,n)}function Ke(r,e){return fc("message",zo.LENGTH_DELIMITED,r,e)}var Fn=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},li=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var fe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(fe||(fe={}));var Ph;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ph||(Ph={}));(function(r){r.codec=()=>ci(Ph)})(fe||(fe={}));var dr;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),fe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Ve(t,r.codec()),r.decode=(t,n)=>$e(t,r.codec(),n)})(dr||(dr={}));var ui;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),fe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Ve(t,r.codec()),r.decode=(t,n)=>$e(t,r.codec(),n)})(ui||(ui={}));function Kt(r){if(isNaN(r)||r<=0)throw new C("random bytes length must be a Number bigger than 0");return Yr(r)}var di={};_e(di,{MAX_RSA_KEY_SIZE:()=>Bh,generateRSAKeyPair:()=>$h,jwkToJWKKeyPair:()=>O0,jwkToPkcs1:()=>W2,jwkToPkix:()=>Rh,jwkToRSAPrivateKey:()=>Fh,pkcs1MessageToJwk:()=>Lh,pkcs1MessageToRSAPrivateKey:()=>dc,pkcs1ToJwk:()=>G2,pkcs1ToRSAPrivateKey:()=>Oh,pkixMessageToJwk:()=>Nh,pkixMessageToRSAPublicKey:()=>Uh,pkixToJwk:()=>j2,pkixToRSAPublicKey:()=>Mh});var Go=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=di.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return V.createV1(114,this._multihash)}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return R0(this.jwk,t,e,n)}},fi=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=di.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){return N0(this.jwk,e,t)}};var Bh=8192,Dh=18,q2=1062,z2=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function G2(r){let e=_t(r);return Lh(e)}function Lh(r){return{n:B(r[1],"base64url"),e:B(r[2],"base64url"),d:B(r[3],"base64url"),p:B(r[4],"base64url"),q:B(r[5],"base64url"),dp:B(r[6],"base64url"),dq:B(r[7],"base64url"),qi:B(r[8],"base64url"),kty:"RSA"}}function W2(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new C("JWK was missing components");return Ft([st(Uint8Array.from([0])),st(T(r.n,"base64url")),st(T(r.e,"base64url")),st(T(r.d,"base64url")),st(T(r.p,"base64url")),st(T(r.q,"base64url")),st(T(r.dp,"base64url")),st(T(r.dq,"base64url")),st(T(r.qi,"base64url"))]).subarray()}function j2(r){let e=_t(r,{offset:0});return Nh(e)}function Nh(r){let e=_t(r[1],{offset:0});return{kty:"RSA",n:B(e[0],"base64url"),e:B(e[1],"base64url")}}function Rh(r){if(r.n==null||r.e==null)throw new C("JWK was missing components");return Ft([z2,Ys(Ft([st(T(r.n,"base64url")),st(T(r.e,"base64url"))]))]).subarray()}function Oh(r){let e=_t(r);return dc(e)}function dc(r){let e=Lh(r);return Fh(e)}function Mh(r,e){if(r.byteLength>=q2)throw new xo("Key size is too large");let t=_t(r,{offset:0});return Uh(t,r,e)}function Uh(r,e,t){let n=Nh(r);if(t==null){let o=Qr(dr.encode({Type:fe.RSA,Data:e}));t=lr(Dh,o)}return new Go(n,t)}function Fh(r){if(U0(r)>Bh)throw new C("Key size is too large");let e=O0(r),t=Qr(dr.encode({Type:fe.RSA,Data:Rh(e.publicKey)})),n=lr(Dh,t);return new fi(e.privateKey,new Go(e.publicKey,n))}async function $h(r){if(r>Bh)throw new C("Key size is too large");let e=await M0(r),t=Qr(dr.encode({Type:fe.RSA,Data:Rh(e.publicKey)})),n=lr(Dh,t);return new fi(e.privateKey,new Go(e.publicKey,n))}function O0(r){if(r==null)throw new C("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function M0(r,e){let t=await Te.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await Y2(t,e);return{privateKey:n[0],publicKey:n[1]}}async function N0(r,e,t){let n=await Te.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Te.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function R0(r,e,t,n){let o=await Te.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Te.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function Y2(r,e){if(r.privateKey==null||r.publicKey==null)throw new C("Private and public key are required");let t=await Promise.all([Te.get().subtle.exportKey("jwk",r.privateKey),Te.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function U0(r){if(r.kty!=="RSA")throw new C("invalid key type");if(r.n==null)throw new C("invalid key modulus");return T(r.n,"base64url").length*8}var hc=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(Lo(e),Q(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),ft(o)}update(e){return No(this),this.iHash.update(e),this}digestInto(e){No(this),Q(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},hi=(r,e,t)=>new hc(r,e).update(t).digest();hi.create=(r,e)=>new hc(r,e);var F0=(r,e)=>(r+(r>=0?e:-e)/$0)/e;function Z2(r,e,t){let[[n,o],[s,i]]=e,a=F0(i*r,t),c=F0(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,f=l<Tr,d=u<Tr;f&&(l=-l),d&&(u=-u);let h=ti(Math.ceil(eh(t)/2))+Wo;if(l<Tr||l>=h||u<Tr||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}function Kh(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Vh(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Cr(t.lowS,"lowS"),Cr(t.prehash,"prehash"),t.format!==void 0&&Kh(t.format),t}var Hh=class extends Error{constructor(e=""){super(e)}},sn={Err:Hh,_tlv:{encode:(r,e)=>{let{Err:t}=sn;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=Qs(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?Qs(o.length/2|128):"";return Qs(r)+s+o+e},decode(r,e){let{Err:t}=sn,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=sn;if(r<Tr)throw new e("integer: negative integers are not allowed");let t=Qs(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=sn;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ro(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=sn,o=Q(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=sn,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},Tr=BigInt(0),Wo=BigInt(1),$0=BigInt(2),pc=BigInt(3),X2=BigInt(4);function V0(r,e={}){let t=ac("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;tn(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=H0(n,o);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(k,E,S){let{x:w,y:_}=E.toAffine(),O=n.toBytes(w);if(Cr(S,"isCompressed"),S){u();let M=!n.isOdd(_);return dt(K0(M),O)}else return dt(Uint8Array.of(4),O,n.toBytes(_))}function d(k){Q(k,void 0,"Point");let{publicKey:E,publicKeyUncompressed:S}=l,w=k.length,_=k[0],O=k.subarray(1);if(w===E&&(_===2||_===3)){let M=n.fromBytes(O);if(!n.isValid(M))throw new Error("bad point: is not on curve, wrong x");let $=g(M),K;try{K=n.sqrt($)}catch(ve){let pe=ve instanceof Error?": "+ve.message:"";throw new Error("bad point: is not on curve, sqrt error"+pe)}u();let z=n.isOdd(K);return(_&1)===1!==z&&(K=n.neg(K)),{x:M,y:K}}else if(w===S&&_===4){let M=n.BYTES,$=n.fromBytes(O.subarray(0,M)),K=n.fromBytes(O.subarray(M,M*2));if(!y($,K))throw new Error("bad point: is not on curve");return{x:$,y:K}}else throw new Error(`bad point: got length ${w}, expected compressed=${E} or uncompressed=${S}`)}let h=e.toBytes||f,m=e.fromBytes||d;function g(k){let E=n.sqr(k),S=n.mul(E,k);return n.add(n.add(S,n.mul(k,s.a)),s.b)}function y(k,E){let S=n.sqr(E),w=g(k);return n.eql(S,w)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let x=n.mul(n.pow(s.a,pc),X2),P=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(x,P)))throw new Error("bad curve params: a or b");function A(k,E,S=!1){if(!n.isValid(E)||S&&n.is0(E))throw new Error(`bad point coordinate ${k}`);return E}function N(k){if(!(k instanceof v))throw new Error("Weierstrass Point expected")}function H(k){if(!c||!c.basises)throw new Error("no endo");return Z2(k,c.basises,o.ORDER)}let G=Oo((k,E)=>{let{X:S,Y:w,Z:_}=k;if(n.eql(_,n.ONE))return{x:S,y:w};let O=k.is0();E==null&&(E=O?n.ONE:n.inv(_));let M=n.mul(S,E),$=n.mul(w,E),K=n.mul(_,E);if(O)return{x:n.ZERO,y:n.ZERO};if(!n.eql(K,n.ONE))throw new Error("invZ was invalid");return{x:M,y:$}}),Y=Oo(k=>{if(k.is0()){if(e.allowInfinityPoint&&!n.is0(k.Y))return;throw new Error("bad point: ZERO")}let{x:E,y:S}=k.toAffine();if(!n.isValid(E)||!n.isValid(S))throw new Error("bad point: x or y not field elements");if(!y(E,S))throw new Error("bad point: equation left != right");if(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function b(k,E,S,w,_){return S=new v(n.mul(S.X,k),S.Y,S.Z),E=ni(w,E),S=ni(_,S),E.add(S)}class v{static BASE=new v(s.Gx,s.Gy,n.ONE);static ZERO=new v(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(E,S,w){this.X=A("x",E),this.Y=A("y",S,!0),this.Z=A("z",w),Object.freeze(this)}static CURVE(){return s}static fromAffine(E){let{x:S,y:w}=E||{};if(!E||!n.isValid(S)||!n.isValid(w))throw new Error("invalid affine point");if(E instanceof v)throw new Error("projective point not allowed");return n.is0(S)&&n.is0(w)?v.ZERO:new v(S,w,n.ONE)}static fromBytes(E){let S=v.fromAffine(m(Q(E,void 0,"point")));return S.assertValidity(),S}static fromHex(E){return v.fromBytes(Ar(E))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(E=8,S=!0){return R.createCache(this,E),S||this.multiply(pc),this}assertValidity(){Y(this)}hasEvenY(){let{y:E}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(E)}equals(E){N(E);let{X:S,Y:w,Z:_}=this,{X:O,Y:M,Z:$}=E,K=n.eql(n.mul(S,$),n.mul(O,_)),z=n.eql(n.mul(w,$),n.mul(M,_));return K&&z}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{a:E,b:S}=s,w=n.mul(S,pc),{X:_,Y:O,Z:M}=this,$=n.ZERO,K=n.ZERO,z=n.ZERO,J=n.mul(_,_),ve=n.mul(O,O),pe=n.mul(M,M),se=n.mul(_,O);return se=n.add(se,se),z=n.mul(_,M),z=n.add(z,z),$=n.mul(E,z),K=n.mul(w,pe),K=n.add($,K),$=n.sub(ve,K),K=n.add(ve,K),K=n.mul($,K),$=n.mul(se,$),z=n.mul(w,z),pe=n.mul(E,pe),se=n.sub(J,pe),se=n.mul(E,se),se=n.add(se,z),z=n.add(J,J),J=n.add(z,J),J=n.add(J,pe),J=n.mul(J,se),K=n.add(K,J),pe=n.mul(O,M),pe=n.add(pe,pe),J=n.mul(pe,se),$=n.sub($,J),z=n.mul(pe,ve),z=n.add(z,z),z=n.add(z,z),new v($,K,z)}add(E){N(E);let{X:S,Y:w,Z:_}=this,{X:O,Y:M,Z:$}=E,K=n.ZERO,z=n.ZERO,J=n.ZERO,ve=s.a,pe=n.mul(s.b,pc),se=n.mul(S,O),Ee=n.mul(w,M),Ue=n.mul(_,$),or=n.add(S,w),Se=n.add(O,M);or=n.mul(or,Se),Se=n.add(se,Ee),or=n.sub(or,Se),Se=n.add(S,_);let Ze=n.add(O,$);return Se=n.mul(Se,Ze),Ze=n.add(se,Ue),Se=n.sub(Se,Ze),Ze=n.add(w,_),K=n.add(M,$),Ze=n.mul(Ze,K),K=n.add(Ee,Ue),Ze=n.sub(Ze,K),J=n.mul(ve,Se),K=n.mul(pe,Ue),J=n.add(K,J),K=n.sub(Ee,J),J=n.add(Ee,J),z=n.mul(K,J),Ee=n.add(se,se),Ee=n.add(Ee,se),Ue=n.mul(ve,Ue),Se=n.mul(pe,Se),Ee=n.add(Ee,Ue),Ue=n.sub(se,Ue),Ue=n.mul(ve,Ue),Se=n.add(Se,Ue),se=n.mul(Ee,Se),z=n.add(z,se),se=n.mul(Ze,Se),K=n.mul(or,K),K=n.sub(K,se),se=n.mul(or,Ee),J=n.mul(Ze,J),J=n.add(J,se),new v(K,z,J)}subtract(E){return this.add(E.negate())}is0(){return this.equals(v.ZERO)}multiply(E){let{endo:S}=e;if(!o.isValidNot0(E))throw new Error("invalid scalar: out of range");let w,_,O=M=>R.cached(this,M,$=>Rn(v,$));if(S){let{k1neg:M,k1:$,k2neg:K,k2:z}=H(E),{p:J,f:ve}=O($),{p:pe,f:se}=O(z);_=ve.add(se),w=b(S.beta,J,pe,M,K)}else{let{p:M,f:$}=O(E);w=M,_=$}return Rn(v,[w,_])[0]}multiplyUnsafe(E){let{endo:S}=e,w=this;if(!o.isValid(E))throw new Error("invalid scalar: out of range");if(E===Tr||w.is0())return v.ZERO;if(E===Wo)return w;if(R.hasCache(this))return this.multiply(E);if(S){let{k1neg:_,k1:O,k2neg:M,k2:$}=H(E),{p1:K,p2:z}=p0(v,w,O,$);return b(S.beta,K,z,_,M)}else return R.unsafe(w,E)}toAffine(E){return G(this,E)}isTorsionFree(){let{isTorsionFree:E}=e;return i===Wo?!0:E?E(v,this):R.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:E}=e;return i===Wo?this:E?E(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(E=!0){return Cr(E,"isCompressed"),this.assertValidity(),h(v,this,E)}toHex(E=!0){return Sr(this.toBytes(E))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let L=o.BITS,R=new Fo(v,e.endo?Math.ceil(L/2):L);return v.BASE.precompute(8),v}function K0(r){return Uint8Array.of(r?2:3)}function H0(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function J2(r,e={}){let{Fn:t}=r,n=e.randomBytes||Yr,o=Object.assign(H0(r.Fp,t),{seed:oh(t.ORDER)});function s(h){try{let m=t.fromBytes(h);return t.isValidNot0(m)}catch{return!1}}function i(h,m){let{publicKey:g,publicKeyUncompressed:y}=o;try{let x=h.length;return m===!0&&x!==g||m===!1&&x!==y?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return sh(Q(h,o.seed,"seed"),t.ORDER)}function c(h,m=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(m)}function l(h){let{secretKey:m,publicKey:g,publicKeyUncompressed:y}=o;if(!_n(h)||"_lengths"in t&&t._lengths||m===g)return;let x=Q(h,void 0,"key").length;return x===g||x===y}function u(h,m,g=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(h);return r.fromBytes(m).multiply(y).toBytes(g)}let f={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=cc(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:d,Point:r,utils:f,lengths:o})}function q0(r,e,t={}){Lo(e),tn(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||Yr,o=t.hmac||((S,w)=>hi(e,S,w)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h}=J2(r,t),m={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},g=a*$0<s.ORDER;function y(S){let w=a>>Wo;return S>w}function x(S,w){if(!i.isValidNot0(w))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return w}function P(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(S,w){Kh(w);let _=h.signature,O=w==="compact"?_:w==="recovered"?_+1:void 0;return Q(S,O)}class N{r;s;recovery;constructor(w,_,O){if(this.r=x("r",w),this.s=x("s",_),O!=null){if(P(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(w,_=m.format){A(w,_);let O;if(_==="der"){let{r:z,s:J}=sn.toSig(Q(w));return new N(z,J)}_==="recovered"&&(O=w[0],_="compact",w=w.subarray(1));let M=h.signature/2,$=w.subarray(0,M),K=w.subarray(M,M*2);return new N(i.fromBytes($),i.fromBytes(K),O)}static fromHex(w,_){return this.fromBytes(Ar(w),_)}assertRecovery(){let{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new N(this.r,this.s,w)}recoverPublicKey(w){let{r:_,s:O}=this,M=this.assertRecovery(),$=M===2||M===3?_+a:_;if(!s.isValid($))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let K=s.toBytes($),z=r.fromBytes(dt(K0((M&1)===0),K)),J=i.inv($),ve=G(Q(w,void 0,"msgHash")),pe=i.create(-ve*J),se=i.create(O*J),Ee=r.BASE.multiplyUnsafe(pe).add(z.multiplyUnsafe(se));if(Ee.is0())throw new Error("invalid recovery: point at infinify");return Ee.assertValidity(),Ee}hasHighS(){return y(this.s)}toBytes(w=m.format){if(Kh(w),w==="der")return Ar(sn.hexFromSig(this));let{r:_,s:O}=this,M=i.toBytes(_),$=i.toBytes(O);return w==="recovered"?(P(),dt(Uint8Array.of(this.assertRecovery()),M,$)):dt(M,$)}toHex(w){return Sr(this.toBytes(w))}}let H=t.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");let _=Ro(w),O=w.length*8-c;return O>0?_>>BigInt(O):_},G=t.bits2int_modN||function(w){return i.create(H(w))},Y=ti(c);function b(S){return ei("num < 2^"+c,S,Tr,Y),i.toBytes(S)}function v(S,w){return Q(S,void 0,"message"),w?Q(e(S),void 0,"prehashed message"):S}function L(S,w,_){let{lowS:O,prehash:M,extraEntropy:$}=Vh(_,m);S=v(S,M);let K=G(S),z=i.fromBytes(w);if(!i.isValidNot0(z))throw new Error("invalid private key");let J=[b(z),b(K)];if($!=null&&$!==!1){let Ee=$===!0?n(h.secretKey):$;J.push(Q(Ee,void 0,"extraEntropy"))}let ve=dt(...J),pe=K;function se(Ee){let Ue=H(Ee);if(!i.isValidNot0(Ue))return;let or=i.inv(Ue),Se=r.BASE.multiply(Ue).toAffine(),Ze=i.create(Se.x);if(Ze===Tr)return;let Ma=i.create(or*i.create(pe+Ze*z));if(Ma===Tr)return;let zg=(Se.x===Ze?0:2)|Number(Se.y&Wo),Gg=Ma;return O&&y(Ma)&&(Gg=i.neg(Ma),zg^=1),new N(Ze,Gg,g?void 0:zg)}return{seed:ve,k2sig:se}}function R(S,w,_={}){let{seed:O,k2sig:M}=L(S,w,_);return Xy(e.outputLen,i.BYTES,o)(O,M).toBytes(_.format)}function k(S,w,_,O={}){let{lowS:M,prehash:$,format:K}=Vh(O,m);if(_=Q(_,void 0,"publicKey"),w=v(w,$),!_n(S)){let z=S instanceof N?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+z)}A(S,K);try{let z=N.fromBytes(S,K),J=r.fromBytes(_);if(M&&z.hasHighS())return!1;let{r:ve,s:pe}=z,se=G(w),Ee=i.inv(pe),Ue=i.create(se*Ee),or=i.create(ve*Ee),Se=r.BASE.multiplyUnsafe(Ue).add(J.multiplyUnsafe(or));return Se.is0()?!1:i.create(Se.x)===ve}catch{return!1}}function E(S,w,_={}){let{prehash:O}=Vh(_,m);return w=v(w,O),N.fromBytes(S,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h,Point:r,sign:R,verify:k,recoverPublicKey:E,Signature:N,hash:e})}var zh={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Q2={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var z0=BigInt(2);function eA(r){let e=zh.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=we(u,t,e)*u%e,d=we(f,t,e)*u%e,h=we(d,z0,e)*l%e,m=we(h,o,e)*h%e,g=we(m,s,e)*m%e,y=we(g,a,e)*g%e,x=we(y,c,e)*y%e,P=we(x,a,e)*g%e,A=we(P,t,e)*u%e,N=we(A,i,e)*m%e,H=we(N,n,e)*l%e,G=we(H,z0,e);if(!qh.eql(qh.sqr(G),r))throw new Error("Cannot find square root");return G}var qh=Mo(zh.p,{sqrt:eA}),tA=V0(zh,{Fp:qh,endo:Q2}),Ht=q0(tA,Qr);var G0=32;function W0(r,e,t){let n=gt.digest(e instanceof Uint8Array?e:e.subarray());if(Vo(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),Ht.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new Fs(String(o))});try{return Ht.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new Fs(String(o))}}function j0(r,e,t,n){let o=gt.digest(t instanceof Uint8Array?t:t.subarray());if(Vo(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Ht.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new $s(String(s))});try{return n?.signal?.throwIfAborted(),Ht.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new $s(String(s))}}var pi=class{type="secp256k1";raw;_key;constructor(e){this._key=X0(e),this.raw=Y0(this._key)}toMultihash(){return ke.digest(Tt(this))}toCID(){return V.createV1(114,this.toMultihash())}toString(){return ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}verify(e,t,n){return j0(this._key,t,e,n)}},mi=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Z0(e),this.publicKey=new pi(t??J0(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:W(this.raw,e.raw)}sign(e,t){return W0(this.raw,e,t)}};function Gh(r){return new mi(r)}function Wh(r){return new pi(r)}async function Q0(){let r=rA();return new mi(r)}function Y0(r){return Ht.Point.fromBytes(r).toBytes()}function Z0(r){try{return Ht.getPublicKey(r,!0),r}catch(e){throw new Os(String(e))}}function X0(r){try{return Ht.Point.fromBytes(r),r}catch(e){throw new xo(String(e))}}function J0(r){try{return Ht.getPublicKey(r,!0)}catch(e){throw new Os(String(e))}}function rA(){return Ht.utils.randomSecretKey()}async function mc(r,e){if(r==="Ed25519")return A0();if(r==="secp256k1")return Q0();if(r==="RSA")return $h(nA(e));if(r==="ECDSA")return Ny(oA(e));throw new Ot}function an(r,e){let{Type:t,Data:n}=dr.decode(r),o=n??new Uint8Array;switch(t){case fe.RSA:return Mh(o,e);case fe.Ed25519:return hh(o);case fe.secp256k1:return Wh(o);case fe.ECDSA:return Kd(o);default:throw new Ot}}function jo(r){let{Type:e,Data:t}=dr.decode(r.digest),n=t??new Uint8Array;switch(e){case fe.Ed25519:return hh(n);case fe.secp256k1:return Wh(n);case fe.ECDSA:return Kd(n);default:throw new Ot}}function Tt(r){return dr.encode({Type:fe[r.type],Data:r.raw})}function ew(r){let e=ui.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case fe.RSA:return Oh(t);case fe.Ed25519:return dh(t);case fe.secp256k1:return Gh(t);case fe.ECDSA:return ky(t);default:throw new Ot}}function tw(r){if(r.byteLength===yt)return dh(r);if(r.byteLength===G0)return Gh(r);let e=_t(r),t=e[2]?.[0];if(t===xy||t===vy||t===Ey)return Vd(e);if(e.length>8)return dc(e);throw new C("Could not extract private key from raw bytes")}function $n(r){return ui.encode({Type:fe[r.type],Data:r.raw})}function nA(r){return r==null?2048:parseInt(r,10)}function oA(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new C("Unsupported curve, should be P-256, P-384 or P-521")}var gi=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),cn=new Uint32Array(80),jh=class extends kn{A=gi[0]|0;B=gi[1]|0;C=gi[2]|0;D=gi[3]|0;E=gi[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s}=this;return[e,t,n,o,s]}set(e,t,n,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0}process(e,t){for(let c=0;c<16;c++,t+=4)cn[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)cn[c]=ec(cn[c-3]^cn[c-8]^cn[c-14]^cn[c-16],1);let{A:n,B:o,C:s,D:i,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=tc(o,s,i),u=1518500249):c<40?(l=o^s^i,u=1859775393):c<60?(l=rc(o,s,i),u=2400959708):(l=o^s^i,u=3395469782);let f=ec(n,5)+l+a+u+cn[c]|0;a=i,i=s,s=ec(o,30),o=n,n=f}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,this.set(n,o,s,i,a)}roundClean(){ft(cn)}destroy(){this.set(0,0,0,0,0),ft(this.buffer)}},rw=Zs(()=>new jh);function nw(r,e,t,n){Lo(r);let o=Fy({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(ut(s,"c"),ut(i,"dkLen"),ut(a,"asyncTick"),s<1)throw new Error("iterations (c) must be >= 1");let c=Hd(e,"password"),l=Hd(t,"salt"),u=new Uint8Array(i),f=hi.create(r,c),d=f._cloneInto().update(l);return{c:s,dkLen:i,asyncTick:a,DK:u,PRF:f,PRFSalt:d}}function ow(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),ft(o),t}function sw(r,e,t,n){let{c:o,dkLen:s,DK:i,PRF:a,PRFSalt:c}=nw(r,e,t,n),l,u=new Uint8Array(4),f=Tn(u),d=new Uint8Array(a.outputLen);for(let h=1,m=0;m<s;h++,m+=a.outputLen){let g=i.subarray(m,m+a.outputLen);f.setInt32(0,h,!1),(l=c._cloneInto(l)).update(u).digestInto(d),g.set(d.subarray(0,g.length));for(let y=1;y<o;y++){a._cloneInto(l).update(d).digestInto(d);for(let x=0;x<g.length;x++)g[x]^=d[x]}}return ow(a,c,i,l,d)}async function gc(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=nw(r,e,t,n),u,f=new Uint8Array(4),d=Tn(f),h=new Uint8Array(c.outputLen);for(let m=1,g=0;g<s;m++,g+=c.outputLen){let y=a.subarray(g,g+c.outputLen);d.setInt32(0,m,!1),(u=l._cloneInto(u)).update(f).digestInto(h),y.set(h.subarray(0,y.length)),await Uy(o-1,i,()=>{c._cloneInto(u).update(h).digestInto(h);for(let x=0;x<y.length;x++)y[x]^=h[x]})}return ow(c,l,a,u,h)}var iw={sha1:rw,"sha2-256":Qr,"sha2-512":en};function yi(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(iw).join(" / ");throw new C(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let s=iw[o],i=sw(s,r,e,{c:t,dkLen:n});return Pe.encode(i).substring(1)}var Yh={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},aw={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},cw=new globalThis.TextEncoder;function sA(r,e){let t=Yh[e],n=aw[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function iA(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=Yh[e],o=aw[e],s=r;for(;s.length>0;){let i=cw.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function Zh(r,{size:e=32,utf8Buffer:t}={}){if(!Yh[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return iA(r,e,t);r=cw.encode(r)}return sA(r,e)}var wi={hash:r=>Number(Zh(r,{size:32})),hashV:(r,e)=>aA(wi.hash(r,e))};function aA(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),T(e,"base16")}var Xh=64,qt=class{fp;h;seed;constructor(e,t,n,o=2){if(o>Xh)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=Ie(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?W(this.fp,e.fp):!1}};function Vn(r,e){return Math.floor(Math.random()*(e-r))+r}var Kn=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof qt))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof qt))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof qt))throw new TypeError("Invalid Fingerprint");let t=Vn(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof qt))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var cA=500,bi=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??wi,this.seed=e.seed??Vn(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=T(e));let t=new qt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Kn(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Kn(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Vn(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Kn(this.bucketSize));for(let a=0;a<cA;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Kn(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=T(e));let t=new qt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=T(e));let t=new qt(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},lA={1:.5,2:.84,4:.95,8:.98};function uA(r=.001){return r>.002?2:r>1e-5?4:8}function lw(r,e=.001){let t=uA(e),n=lA[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Xh);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var yc=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??wi,this.seed=e.seed??Vn(0,Math.pow(2,10)),this.filterSeries=[new bi({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=T(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new bi({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=T(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function Hn(r,e=.001,t){return new yc({...lw(r,e),...t??{}})}function te(r){let e=r.getComponents(),t={},n=0;if(e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n].name==="ip4"||e[n].name==="ip6"||e[n].name==="dns"||e[n].name==="dns4"||e[n].name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n].name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null)throw new C(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t}var wc=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var uw=45,fA=15,Yo=new wc;function bc(r){if(!(r.length>fA))return Yo.new(r).parseWith(()=>Yo.readIPv4Addr())}function xc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>uw))return Yo.new(r).parseWith(()=>Yo.readIPv6Addr())}function Zo(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>uw)return;let t=Yo.new(r).parseWith(()=>Yo.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function fw(r,e,t){let n=0;for(let o of r)if(!(n<e)){if(n>t)break;if(o!==255)return!1;n++}return!0}function dw(r,e,t,n){let o=0;for(let s of r)if(!(o<t)){if(o>n)break;if(s!==e[o])return!1;o++}return!0}function Jh(r){switch(r.length){case qn:return r.join(".");case zn:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function hw(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let o=t+1;o<r.length;o++)if(r[o]!=0)return-1;break}return e}function pw(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var qn=4,zn=16,iL=parseInt("0xFFFF",16),dA=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function xi(r,e){e.length===zn&&r.length===qn&&fw(e,0,11)&&(e=e.slice(12)),e.length===qn&&r.length===zn&&dw(r,dA,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=r[o]&e[o];return n}function mw(r,e){if(typeof e=="string"&&(e=Zo(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function Qh(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=qn,o=bc(e);if(o==null&&(n=zn,o=xc(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let s=parseInt(t,10);if(Number.isNaN(s)||String(s).length!==t.length||s<0||s>n*8)throw new Error("Failed to parse given CIDR: "+r);let i=ep(s,8*n);return{network:xi(o,i),mask:i}}function ep(r,e){if(e!==8*qn&&e!==8*zn)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let o=0;o<t;o++){if(r>=8){n[o]=255,r-=8;continue}n[o]=255-(255>>r),r=0}return n}var Gn=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=Qh(e));else{let n=Zo(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let s=Zo(t);if(s==null)throw new Error("Failed to parse mask");this.mask=s}else this.mask=ep(o,8*n.length);this.network=xi(n,this.mask)}}contains(e){return mw({network:this.network,mask:this.mask},e)}toString(){let e=hw(this.mask),t=e!==-1?String(e):pw(this.mask);return Jh(this.network)+"/"+t}};function gw(r){try{let e=te(r);switch(e.type){case"ip4":return e.host.startsWith("169.254.");case"ip6":return e.host.toLowerCase().startsWith("fe80");default:return!1}}catch{return!1}}function yw(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function vi(r){try{let e=te(r);switch(e.type){case"ip4":case"ip6":return yw(e.host);default:return!1}}catch{return!1}}function He(r){try{return te(r),!0}catch{return!1}}function at(r){return!!bc(r)}function Xo(r){return!!xc(r)}var bw=vn(ww(),1),hA=["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"],pA=hA.map(r=>new bw.Netmask(r));function tp(r){for(let e of pA)if(e.contains(r))return!0;return!1}function mA(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function gA(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return tp(o)}function yA(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function wA(r){let e=r.split(":"),t=e[e.length-1];return tp(t)}function bA(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 Jo(r){if(at(r))return tp(r);if(mA(r))return gA(r);if(yA(r))return wA(r);if(Xo(r))return bA(r)}function zt(r){try{let e=te(r);switch(e.type){case"ip4":case"ip6":return Jo(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function le(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var vc=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Qo=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new vc(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new vc(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var rp=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function es(r={}){return xA(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function xA(r,e){e=e??{};let t=e.onEnd,n=new Qo,o,s,i,a=le(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,x)=>{s=P=>{s=null,n.push(P);try{y(r(n))}catch(A){x(A)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=le()})}},l=y=>s!=null?s(y):(n.push(y),o),u=y=>(n=new Qo,s!=null?s({error:y}):(n.push({error:y}),o)),f=y=>{if(i)return o;if(e?.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})},d=y=>i?o:(i=!0,y!=null?u(y):l({done:!0})),h=()=>(n=new Qo,d(),{done:!0}),m=y=>(d(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:f,end:d,get readableLength(){return n.size},onEmpty:async y=>{let x=y?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let P,A;x!=null&&(P=new Promise((N,H)=>{A=()=>{H(new rp)},x.addEventListener("abort",A)}));try{await Promise.race([a.promise,P])}finally{A!=null&&x!=null&&x?.removeEventListener("abort",A)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(y){return g.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(y){return g.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:y=>g.onEmpty(y)},o}var Si=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},np=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},xw=r=>globalThis.DOMException===void 0?new np(r):new DOMException(r),vw=r=>{let e=r.reason===void 0?xw("This operation was aborted."):r.reason;return e instanceof Error?e:xw(e)};function Ai(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a,l=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&f(vw(h)),a=()=>{f(vw(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new Si;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){f(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${t} milliseconds`,f(d))},t),(async()=>{try{u(await r)}catch(h){f(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}var vA=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function EA(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=vA(r),f=async(...h)=>{let m=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(m))return}catch(g){n(),i(g);return}c.push(m),t.count===c.length&&(n(),s(c))},d=(...h)=>{n(),i(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,f);for(let h of t.rejectionEvents)a.includes(h)||u(h,d)};for(let h of a)l(h,f);for(let h of t.rejectionEvents)a.includes(h)||l(h,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=Ai(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Gt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=EA(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}function Ii(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Ec=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Sc=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Wn=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};function SA(r){return r.reason}async function kr(r,e,t){if(e==null)return r;let n=t?.translateError??SA;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Ac=class{deferred;signal;constructor(e){this.signal=e,this.deferred=le(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new mt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function AA(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ic=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=AA(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new mt),this.cleanup())}async join(e={}){let t=new Ac(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await kr(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Wt=class extends De{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Ii(this.emitEmpty.bind(this),1),this.emitIdle=Ii(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 e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Sc;let n=new Ic(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new mt)}),this.clear()}async onEmpty(e){this.size!==0&&await Gt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Gt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Gt(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=es({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new mt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var ts=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var IA=1.2,CA=2,_A=5e3,TA=6e4,kA=5e3,Cc=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??kA;this.success=new ts(t),this.failure=new ts(t),this.next=new ts(t),this.failureMultiplier=e.failureMultiplier??CA,this.timeoutMultiplier=e.timeoutMultiplier??IA,this.minTimeout=e.minTimeout??_A,this.maxTimeout=e.maxTimeout??TA,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=me([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var qe=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Pr=class extends Error{static name="ValidationError";name="ValidationError"},_c=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Tc=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function sp(r){return e=>B(e,r)}function ip(r){return e=>T(e,r)}function rs(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function jn(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Ew(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=T(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=jn(n);return ye([t,o],t.length+o.length)}function Sw(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ge.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=jn(n);return ye([t,o],t.length+o.length)}function ap(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=B(e,"base32"),o=rs(t);return`${n}:${o}`}var cp=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new qe("Invalid byte value in IP address");e[n]=o}),e},Aw=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=at(t[n]),i;s&&(i=cp(t[n]),t[n]=B(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,B(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new qe("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Iw=function(r){if(r.byteLength!==4)throw new qe("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Cw=function(r){if(r.byteLength!==16)throw new qe("IPv6 address was incorrect length");let e=[];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")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new qe(`Invalid IPv6 address "${t}"`)}};function _w(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new qe(`Invalid IPv6 address "${r}"`)}}var op=Object.values(An).map(r=>r.decoder),PA=(function(){let r=op[0].or(op[1]);return op.slice(2).forEach(e=>r=r.or(e)),r})();function Tw(r){return PA.decode(r)}function kw(r){return e=>r.encoder.encode(e)}function BA(r){if(parseInt(r).toString()!==r)throw new Pr("Value must be an integer")}function DA(r){if(r<0)throw new Pr("Value must be a positive integer, or zero")}function LA(r){return e=>{if(e>r)throw new Pr(`Value must be smaller than or equal to ${r}`)}}function NA(...r){return e=>{for(let t of r)t(e)}}var Ci=NA(BA,DA,LA(65535));var Re=-1,lp=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new Tc(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Dr=new lp,YA=[{code:4,name:"ip4",size:32,valueToBytes:cp,bytesToValue:Iw,validate:r=>{if(!at(r))throw new Pr(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:jn,bytesToValue:rs,validate:Ci},{code:273,name:"udp",size:16,valueToBytes:jn,bytesToValue:rs,validate:Ci},{code:33,name:"dccp",size:16,valueToBytes:jn,bytesToValue:rs,validate:Ci},{code:41,name:"ip6",size:128,valueToBytes:Aw,bytesToValue:Cw,stringToValue:_w,validate:r=>{if(!Xo(r))throw new Pr(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:Re},{code:43,name:"ipcidr",size:8,bytesToValue:sp("base10"),valueToBytes:ip("base10")},{code:53,name:"dns",size:Re},{code:54,name:"dns4",size:Re},{code:55,name:"dns6",size:Re},{code:56,name:"dnsaddr",size:Re},{code:132,name:"sctp",size:16,valueToBytes:jn,bytesToValue:rs,validate:Ci},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Re,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:Re,bytesToValue:sp("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ip("base58btc")(r):V.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ap,valueToBytes:Ew},{code:445,name:"onion3",size:296,bytesToValue:ap,valueToBytes:Sw},{code:446,name:"garlic64",size:Re},{code:447,name:"garlic32",size:Re},{code:448,name:"tls"},{code:449,name:"sni",size:Re},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Re,bytesToValue:kw(qs),valueToBytes:Tw},{code:480,name:"http"},{code:481,name:"http-path",size:Re,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:Re}];YA.forEach(r=>{Dr.addProtocol(r)});function Pw(r){let e=[],t=0;for(;t<r.length;){let n=fr(r,t),o=Dr.getProtocol(n),s=be(n),i=ZA(o,r,t+s),a=0;i>0&&o.size===Re&&(a=be(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??B(f)}e.push(l),t+=c}return e}function Bw(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Dr.getProtocol(n.code),s=be(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??T(n.value),a=i.byteLength,o.size===Re&&(c=be(a)));let l=new Uint8Array(s+c+a),u=0;_r(n.code,l,u),u+=s,i!=null&&(o.size===Re&&(_r(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return ye(t,e)}function Dw(r){if(r.charAt(0)!=="/")throw new qe('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Dr.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new qe(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new qe(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new qe("Incomplete multiaddr");return e}function Lw(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Dr.getProtocol(e.code);if(t==null)throw new qe(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function ZA(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:fr(e,t)}var XA=Symbol.for("nodejs.util.inspect.custom"),bp=Symbol.for("@multiformats/multiaddr");function JA(r){if(r==null&&(r="/"),un(r))return r.getComponents();if(r instanceof Uint8Array)return Pw(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),Dw(r);if(Array.isArray(r))return r;throw new qe("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Lc=class r{[bp]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=JA(e),t.validate!==!1&&QA(this)}get bytes(){return this.#r==null&&(this.#r=Bw(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Lw(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new _c(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}equals(e){return W(this.bytes,e.bytes)}[XA](){return`Multiaddr(${this.toString()})`}};function QA(r){r.getComponents().forEach(e=>{let t=Dr.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function un(r){return!!r?.[bp]}function oe(r){return new Lc(r)}var Nc=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function Nw(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Nc(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Nc(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var xp=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=le(),this.haveNext=le()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=le(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=le(),await Nw(this.readNext.promise,t?.signal,t)}};function Rw(){return new xp}function eI(r){return r[Symbol.asyncIterator]!=null}async function tI(r,e,t){try{await Promise.all(r.map(async n=>{for await(let o of n)await e.push(o,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*rI(r){let e=new AbortController,t=Rw();tI(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*nI(r){for(let e of r)yield*e}function oI(...r){let e=[];for(let t of r)eI(t)||e.push(t);return e.length===r.length?nI(e):rI(r)}var kt=oI;var iI=4194304,Rc=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ep=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Sp=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ap=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function aI(r){return typeof r?.closeRead=="function"}function cI(r){return typeof r?.close=="function"}function vp(r){return aI(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:cI(r)?r.status!=="open":!1}function lI(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Ip(r,e){let t=e?.maxBufferSize??iI,n=new ae,o,s=!1;if(!lI(r))throw new C("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let f=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${f} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new Rc("Stream was unwrapped");if(vp(r)){if(u?.bytes==null)return null;if(n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Wn(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let f=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=f){o.resolve();break}if(await kr(o.promise,u?.signal),vp(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let d=u?.bytes??n.byteLength;if(n.byteLength<d){if(vp(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,d),new Wn(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return l.read(u)}let h=n.sublist(0,d);return n.consume(d),h},async write(u,f){if(s===!0)throw new Rc("Stream was unwrapped");r.send(u)||await Gt(r,"drain",{signal:f?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function Oc(r,e={}){let t=Ip(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=be(e.maxDataLength));let n=e?.lengthDecoder??fr,o=e?.lengthEncoder??nn;return{async read(i){let a=-1,c=new ae;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(f){if(f instanceof RangeError)continue;throw f}if(a<0)throw new Ep("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ap(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Sp(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Wn(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Wn(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new ae(o(i.byteLength),i),a)},async writeV(i,a){let c=new ae(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}var uI=["string","number","bigint","symbol"],fI=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Ow(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(uI.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(dI(r))return"Buffer";let t=hI(r);return t||"Object"}function dI(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function hI(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(fI.includes(e))return e}var p=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};p.uint=new p(0,"uint",!0);p.negint=new p(1,"negint",!0);p.bytes=new p(2,"bytes",!0);p.string=new p(3,"string",!0);p.array=new p(4,"array",!1);p.map=new p(5,"map",!1);p.tag=new p(6,"tag",!1);p.float=new p(7,"float",!0);p.false=new p(7,"false",!0);p.true=new p(7,"true",!0);p.null=new p(7,"null",!0);p.undefined=new p(7,"undefined",!0);p.break=new p(7,"break",!0);var I=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var as=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",pI=new TextDecoder,mI=new TextEncoder;function Mc(r){return as&&globalThis.Buffer.isBuffer(r)}function Bi(r){return r instanceof Uint8Array?Mc(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var $w=as?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):Uw(r,e,t):(r,e,t)=>t-e>64?pI.decode(r.subarray(e,t)):Uw(r,e,t),Uc=as?r=>r.length>64?globalThis.Buffer.from(r):Mw(r):r=>r.length>64?mI.encode(r):Mw(r),pr=r=>Uint8Array.from(r),cs=as?(r,e,t)=>Mc(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Vw=as?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Bi(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},Kw=as?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function Hw(r,e){if(Mc(r)&&Mc(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function Mw(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function Uw(r,e,t){let n=[];for(;e<t;){let o=r[e],s=null,i=o>239?4:o>223?3:o>191?2:1;if(e+i<=t){let a,c,l,u;switch(i){case 1:o<128&&(s=o);break;case 2:a=r[e+1],(a&192)===128&&(u=(o&31)<<6|a&63,u>127&&(s=u));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(u=(o&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(s=u))}}s===null?(s=65533,i=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),e+=i}return Cp(n)}var Fw=4096;function Cp(r){let e=r.length;if(e<=Fw)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Fw));return t}var gI=256,Di=class{constructor(e=gI){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Kw(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=cs(n,0,this.cursor)}else t=Vw(this.chunks,this.cursor);return e&&this.reset(),t}};var F="CBOR decode error:",Lr="CBOR encode error:",Li=[];Li[23]=1;Li[24]=2;Li[25]=3;Li[26]=5;Li[27]=9;function Nr(r,e,t){if(r.length-e<t)throw new Error(`${F} not enough data for type`)}var Oe=[24,256,65536,4294967296,BigInt("18446744073709551616")];function bt(r,e,t){Nr(r,e,1);let n=r[e];if(t.strict===!0&&n<Oe[0])throw new Error(`${F} integer encoded in more bytes than necessary (strict decode)`);return n}function xt(r,e,t){Nr(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Oe[1])throw new Error(`${F} integer encoded in more bytes than necessary (strict decode)`);return n}function vt(r,e,t){Nr(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Oe[2])throw new Error(`${F} integer encoded in more bytes than necessary (strict decode)`);return n}function Et(r,e,t){Nr(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],s=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&s<Oe[3])throw new Error(`${F} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${F} integers outside of the safe integer range are not supported`)}function qw(r,e,t,n){return new I(p.uint,bt(r,e+1,n),2)}function zw(r,e,t,n){return new I(p.uint,xt(r,e+1,n),3)}function Gw(r,e,t,n){return new I(p.uint,vt(r,e+1,n),5)}function Ww(r,e,t,n){return new I(p.uint,Et(r,e+1,n),9)}function Pt(r,e){return ze(r,0,e.value)}function ze(r,e,t){if(t<Oe[0]){let n=Number(t);r.push([e|n])}else if(t<Oe[1]){let n=Number(t);r.push([e|24,n])}else if(t<Oe[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Oe[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<Oe[4]){let o=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=s&255,s=s>>8,o[7]=s&255,s=s>>8,o[6]=s&255,s=s>>8,o[5]=s&255,o[4]=i&255,i=i>>8,o[3]=i&255,i=i>>8,o[2]=i&255,i=i>>8,o[1]=i&255,r.push(o)}else throw new Error(`${F} encountered BigInt larger than allowable range`)}}Pt.encodedSize=function(e){return ze.encodedSize(e.value)};ze.encodedSize=function(e){return e<Oe[0]?1:e<Oe[1]?2:e<Oe[2]?3:e<Oe[3]?5:9};Pt.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function jw(r,e,t,n){return new I(p.negint,-1-bt(r,e+1,n),2)}function Yw(r,e,t,n){return new I(p.negint,-1-xt(r,e+1,n),3)}function Zw(r,e,t,n){return new I(p.negint,-1-vt(r,e+1,n),5)}var _p=BigInt(-1),Xw=BigInt(1);function Jw(r,e,t,n){let o=Et(r,e+1,n);if(typeof o!="bigint"){let s=-1-o;if(s>=Number.MIN_SAFE_INTEGER)return new I(p.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${F} integers outside of the safe integer range are not supported`);return new I(p.negint,_p-BigInt(o),9)}function Fc(r,e){let t=e.value,n=typeof t=="bigint"?t*_p-Xw:t*-1-1;ze(r,e.type.majorEncoded,n)}Fc.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*_p-Xw:t*-1-1;return n<Oe[0]?1:n<Oe[1]?2:n<Oe[2]?3:n<Oe[3]?5:9};Fc.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Ni(r,e,t,n){Nr(r,e,t+n);let o=cs(r,e+t,e+t+n);return new I(p.bytes,o,t+n)}function Qw(r,e,t,n){return Ni(r,e,1,t)}function eb(r,e,t,n){return Ni(r,e,2,bt(r,e+1,n))}function tb(r,e,t,n){return Ni(r,e,3,xt(r,e+1,n))}function rb(r,e,t,n){return Ni(r,e,5,vt(r,e+1,n))}function nb(r,e,t,n){let o=Et(r,e+1,n);if(typeof o=="bigint")throw new Error(`${F} 64-bit integer bytes lengths not supported`);return Ni(r,e,9,o)}function $c(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===p.string?Uc(r.value):r.value),r.encodedBytes}function ls(r,e){let t=$c(e);ze(r,e.type.majorEncoded,t.length),r.push(t)}ls.encodedSize=function(e){let t=$c(e);return ze.encodedSize(t.length)+t.length};ls.compareTokens=function(e,t){return wI($c(e),$c(t))};function wI(r,e){return r.length<e.length?-1:r.length>e.length?1:Hw(r,e)}function Ri(r,e,t,n,o){let s=t+n;Nr(r,e,s);let i=new I(p.string,$w(r,e+t,e+s),s);return o.retainStringBytes===!0&&(i.byteValue=cs(r,e+t,e+s)),i}function ob(r,e,t,n){return Ri(r,e,1,t,n)}function sb(r,e,t,n){return Ri(r,e,2,bt(r,e+1,n),n)}function ib(r,e,t,n){return Ri(r,e,3,xt(r,e+1,n),n)}function ab(r,e,t,n){return Ri(r,e,5,vt(r,e+1,n),n)}function cb(r,e,t,n){let o=Et(r,e+1,n);if(typeof o=="bigint")throw new Error(`${F} 64-bit integer string lengths not supported`);return Ri(r,e,9,o,n)}var lb=ls;function us(r,e,t,n){return new I(p.array,n,t)}function ub(r,e,t,n){return us(r,e,1,t)}function fb(r,e,t,n){return us(r,e,2,bt(r,e+1,n))}function db(r,e,t,n){return us(r,e,3,xt(r,e+1,n))}function hb(r,e,t,n){return us(r,e,5,vt(r,e+1,n))}function pb(r,e,t,n){let o=Et(r,e+1,n);if(typeof o=="bigint")throw new Error(`${F} 64-bit integer array lengths not supported`);return us(r,e,9,o)}function mb(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${F} indefinite length items not allowed`);return us(r,e,1,1/0)}function Vc(r,e){ze(r,p.array.majorEncoded,e.value)}Vc.compareTokens=Pt.compareTokens;Vc.encodedSize=function(e){return ze.encodedSize(e.value)};function fs(r,e,t,n){return new I(p.map,n,t)}function gb(r,e,t,n){return fs(r,e,1,t)}function yb(r,e,t,n){return fs(r,e,2,bt(r,e+1,n))}function wb(r,e,t,n){return fs(r,e,3,xt(r,e+1,n))}function bb(r,e,t,n){return fs(r,e,5,vt(r,e+1,n))}function xb(r,e,t,n){let o=Et(r,e+1,n);if(typeof o=="bigint")throw new Error(`${F} 64-bit integer map lengths not supported`);return fs(r,e,9,o)}function vb(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${F} indefinite length items not allowed`);return fs(r,e,1,1/0)}function Kc(r,e){ze(r,p.map.majorEncoded,e.value)}Kc.compareTokens=Pt.compareTokens;Kc.encodedSize=function(e){return ze.encodedSize(e.value)};function Eb(r,e,t,n){return new I(p.tag,t,1)}function Sb(r,e,t,n){return new I(p.tag,bt(r,e+1,n),2)}function Ab(r,e,t,n){return new I(p.tag,xt(r,e+1,n),3)}function Ib(r,e,t,n){return new I(p.tag,vt(r,e+1,n),5)}function Cb(r,e,t,n){return new I(p.tag,Et(r,e+1,n),9)}function Hc(r,e){ze(r,p.tag.majorEncoded,e.value)}Hc.compareTokens=Pt.compareTokens;Hc.encodedSize=function(e){return ze.encodedSize(e.value)};var AI=20,II=21,CI=22,_I=23;function _b(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${F} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new I(p.null,null,1):new I(p.undefined,void 0,1)}function Tb(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${F} indefinite length items not allowed`);return new I(p.break,void 0,1)}function Tp(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${F} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${F} Infinity values are not supported`)}return new I(p.float,r,e)}function kb(r,e,t,n){return Tp(kp(r,e+1),3,n)}function Pb(r,e,t,n){return Tp(Pp(r,e+1),5,n)}function Bb(r,e,t,n){return Tp(Rb(r,e+1),9,n)}function qc(r,e,t){let n=e.value;if(n===!1)r.push([p.float.majorEncoded|AI]);else if(n===!0)r.push([p.float.majorEncoded|II]);else if(n===null)r.push([p.float.majorEncoded|CI]);else if(n===void 0)r.push([p.float.majorEncoded|_I]);else{let o,s=!1;(!t||t.float64!==!0)&&(Lb(n),o=kp(jt,1),n===o||Number.isNaN(n)?(jt[0]=249,r.push(jt.slice(0,3)),s=!0):(Nb(n),o=Pp(jt,1),n===o&&(jt[0]=250,r.push(jt.slice(0,5)),s=!0))),s||(TI(n),o=Rb(jt,1),jt[0]=251,r.push(jt.slice(0,9)))}}qc.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){Lb(n);let o=kp(jt,1);if(n===o||Number.isNaN(n))return 3;if(Nb(n),o=Pp(jt,1),n===o)return 5}return 9};var Db=new ArrayBuffer(9),Bt=new DataView(Db,1),jt=new Uint8Array(Db,0);function Lb(r){if(r===1/0)Bt.setUint16(0,31744,!1);else if(r===-1/0)Bt.setUint16(0,64512,!1);else if(Number.isNaN(r))Bt.setUint16(0,32256,!1);else{Bt.setFloat32(0,r);let e=Bt.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Bt.setUint16(0,31744,!1);else if(t===0)Bt.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Bt.setUint16(0,0):o<-14?Bt.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Bt.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function kp(r,e){if(r.length-e<2)throw new Error(`${F} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,s;return n===0?s=o*2**-24:n!==31?s=(o+1024)*2**(n-25):s=o===0?1/0:NaN,t&32768?-s:s}function Nb(r){Bt.setFloat32(0,r,!1)}function Pp(r,e){if(r.length-e<4)throw new Error(`${F} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function TI(r){Bt.setFloat64(0,r,!1)}function Rb(r,e){if(r.length-e<8)throw new Error(`${F} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}qc.compareTokens=Pt.compareTokens;function ie(r,e,t){throw new Error(`${F} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function zc(r){return()=>{throw new Error(`${F} ${r}`)}}var D=[];for(let r=0;r<=23;r++)D[r]=ie;D[24]=qw;D[25]=zw;D[26]=Gw;D[27]=Ww;D[28]=ie;D[29]=ie;D[30]=ie;D[31]=ie;for(let r=32;r<=55;r++)D[r]=ie;D[56]=jw;D[57]=Yw;D[58]=Zw;D[59]=Jw;D[60]=ie;D[61]=ie;D[62]=ie;D[63]=ie;for(let r=64;r<=87;r++)D[r]=Qw;D[88]=eb;D[89]=tb;D[90]=rb;D[91]=nb;D[92]=ie;D[93]=ie;D[94]=ie;D[95]=zc("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)D[r]=ob;D[120]=sb;D[121]=ib;D[122]=ab;D[123]=cb;D[124]=ie;D[125]=ie;D[126]=ie;D[127]=zc("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)D[r]=ub;D[152]=fb;D[153]=db;D[154]=hb;D[155]=pb;D[156]=ie;D[157]=ie;D[158]=ie;D[159]=mb;for(let r=160;r<=183;r++)D[r]=gb;D[184]=yb;D[185]=wb;D[186]=bb;D[187]=xb;D[188]=ie;D[189]=ie;D[190]=ie;D[191]=vb;for(let r=192;r<=215;r++)D[r]=Eb;D[216]=Sb;D[217]=Ab;D[218]=Ib;D[219]=Cb;D[220]=ie;D[221]=ie;D[222]=ie;D[223]=ie;for(let r=224;r<=243;r++)D[r]=zc("simple values are not supported");D[244]=ie;D[245]=ie;D[246]=ie;D[247]=_b;D[248]=zc("simple values are not supported");D[249]=kb;D[250]=Pb;D[251]=Bb;D[252]=ie;D[253]=ie;D[254]=ie;D[255]=Tb;var Yt=[];for(let r=0;r<24;r++)Yt[r]=new I(p.uint,r,1);for(let r=-1;r>=-24;r--)Yt[31-r]=new I(p.negint,r,1);Yt[64]=new I(p.bytes,new Uint8Array(0),1);Yt[96]=new I(p.string,"",1);Yt[128]=new I(p.array,0,1);Yt[160]=new I(p.map,0,1);Yt[244]=new I(p.false,!1,1);Yt[245]=new I(p.true,!0,1);Yt[246]=new I(p.null,null,1);function Ob(r){switch(r.type){case p.false:return pr([244]);case p.true:return pr([245]);case p.null:return pr([246]);case p.bytes:return r.value.length?void 0:pr([64]);case p.string:return r.value===""?pr([96]):void 0;case p.array:return r.value===0?pr([128]):void 0;case p.map:return r.value===0?pr([160]):void 0;case p.uint:return r.value<24?pr([Number(r.value)]):void 0;case p.negint:if(r.value>=-24)return pr([31-Number(r.value)])}}var PI={float64:!1,mapSorter:LI,quickEncodeToken:Ob};function BI(){let r=[];return r[p.uint.major]=Pt,r[p.negint.major]=Fc,r[p.bytes.major]=ls,r[p.string.major]=lb,r[p.array.major]=Vc,r[p.map.major]=Kc,r[p.tag.major]=Hc,r[p.float.major]=qc,r}var Mb=BI(),Bp=new Di,Wc=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Lr} object contains circular references`);return new r(t,e)}},fn={null:new I(p.null,null),undefined:new I(p.undefined,void 0),true:new I(p.true,!0),false:new I(p.false,!1),emptyArray:new I(p.array,0),emptyMap:new I(p.map,0)},dn={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new I(p.float,r):r>=0?new I(p.uint,r):new I(p.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new I(p.uint,r):new I(p.negint,r)},Uint8Array(r,e,t,n){return new I(p.bytes,r)},string(r,e,t,n){return new I(p.string,r)},boolean(r,e,t,n){return r?fn.true:fn.false},null(r,e,t,n){return fn.null},undefined(r,e,t,n){return fn.undefined},ArrayBuffer(r,e,t,n){return new I(p.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new I(p.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[fn.emptyArray,new I(p.break)]:fn.emptyArray;n=Wc.createCheck(n,r);let o=[],s=0;for(let i of r)o[s++]=Gc(i,t,n);return t.addBreakTokens?[new I(p.array,r.length),o,new I(p.break)]:[new I(p.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",s=o?r.keys():Object.keys(r),i=o?r.size:s.length;if(!i)return t.addBreakTokens===!0?[fn.emptyMap,new I(p.break)]:fn.emptyMap;n=Wc.createCheck(n,r);let a=[],c=0;for(let l of s)a[c++]=[Gc(l,t,n),Gc(o?r.get(l):r[l],t,n)];return DI(a,t),t.addBreakTokens?[new I(p.map,i),a,new I(p.break)]:[new I(p.map,i),a]}};dn.Map=dn.Object;dn.Buffer=dn.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))dn[`${r}Array`]=dn.DataView;function Gc(r,e={},t){let n=Ow(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||dn[n];if(typeof o=="function"){let i=o(r,n,e,t);if(i!=null)return i}let s=dn[n];if(!s)throw new Error(`${Lr} unsupported type: ${n}`);return s(r,n,e,t)}function DI(r,e){e.mapSorter&&r.sort(e.mapSorter)}function LI(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,s=Mb[o].compareTokens(t,n);return s===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),s}function Ub(r,e,t,n){if(Array.isArray(e))for(let o of e)Ub(r,o,t,n);else t[e.type.major](r,e,n)}function Dp(r,e,t){let n=Gc(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let s=e[n.type.major];if(s.encodedSize){let i=s.encodedSize(n,t),a=new Di(i);if(s(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return Bi(a.chunks[0])}}return Bp.reset(),Ub(Bp,n,e,t),Bp.toBytes(!0)}function hn(r,e){return e=Object.assign({},PI,e),Dp(r,Mb,e)}var NI={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},jc=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Yt[e];if(t===void 0){let n=D[e];if(!n)throw new Error(`${F} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},Oi=Symbol.for("DONE"),Yc=Symbol.for("BREAK");function RI(r,e,t){let n=[];for(let o=0;o<r.value;o++){let s=ds(e,t);if(s===Yc){if(r.value===1/0)break;throw new Error(`${F} got unexpected break to lengthed array`)}if(s===Oi)throw new Error(`${F} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=s}return n}function OI(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},s=n?new Map:void 0;for(let i=0;i<r.value;i++){let a=ds(e,t);if(a===Yc){if(r.value===1/0)break;throw new Error(`${F} got unexpected break to lengthed map`)}if(a===Oi)throw new Error(`${F} found map but not enough entries (got ${i} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${F} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&s.has(a)||!n&&a in o))throw new Error(`${F} found repeat map key "${a}"`);let c=ds(e,t);if(c===Oi)throw new Error(`${F} found map but not enough entries (got ${i} [no value], expected ${r.value})`);n?s.set(a,c):o[a]=c}return n?s:o}function ds(r,e){if(r.done())return Oi;let t=r.next();if(t.type===p.break)return Yc;if(t.type.terminal)return t.value;if(t.type===p.array)return RI(t,r,e);if(t.type===p.map)return OI(t,r,e);if(t.type===p.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=ds(r,e);return e.tags[t.value](n)}throw new Error(`${F} tag not supported (${t.value})`)}throw new Error("unsupported")}function Lp(r,e){if(!(r instanceof Uint8Array))throw new Error(`${F} data to decode must be a Uint8Array`);e=Object.assign({},NI,e);let t=e.tokenizer||new jc(r,e),n=ds(t,e);if(n===Oi)throw new Error(`${F} did not find any content to decode`);if(n===Yc)throw new Error(`${F} got unexpected break`);return[n,r.subarray(t.pos())]}function St(r,e){let[t,n]=Lp(r,e);if(n.length>0)throw new Error(`${F} too many terminals, data makes no sense`);return t}var Zc=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},hs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Xc=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Mi=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Jc(r){return r[Symbol.asyncIterator]!=null}function Fb(r,e){if(r.byteLength>e)throw new hs("Message length too long")}var el=r=>{let e=be(r),t=Je(e);return nn(r,t),el.bytes=e,t};el.bytes=0;function tl(r,e){e=e??{};let t=e.lengthEncoder??el,n=e?.maxDataLength??4194304;function*o(s){Fb(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Jc(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}tl.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??el,n=e?.maxDataLength??4194304;return Fb(r,n),new ae(t(r.byteLength),r)};var Xn;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Xn||(Xn={}));var Op=r=>{let e=fr(r);return Op.bytes=be(e),e};Op.bytes=0;function Rp(r,e){let t=new ae,n=Xn.LENGTH,o=-1,s=e?.lengthDecoder??Op,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Xn.LENGTH)try{if(o=s(t),o<0)throw new Zc("Invalid message length");if(o>a)throw new hs("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=Xn.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new Xc("Message length length too long");break}throw l}if(n===Xn.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=Xn.LENGTH}}}return Jc(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Mi("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Mi("Unexpected end of input")})()}Rp.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return Rp(n,{...e??{},onLength:s=>{t=s}})};function UI(r,e){if(typeof r=="string")return FI(r);if(typeof r=="number")return KI(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var rl=UI;function FI(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<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(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,o=parseFloat(t),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 Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function $I(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function VI(r){let e=Math.abs(r);return e>=315576e5?Jn(r,e,315576e5,"year"):e>=26298e5?Jn(r,e,26298e5,"month"):e>=6048e5?Jn(r,e,6048e5,"week"):e>=864e5?Jn(r,e,864e5,"day"):e>=36e5?Jn(r,e,36e5,"hour"):e>=6e4?Jn(r,e,6e4,"minute"):e>=1e3?Jn(r,e,1e3,"second"):`${r} ms`}function KI(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?VI(r):$I(r)}function Jn(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function Mp(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=rl,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,d=null,h,m;function g(...y){if(!g.enabled)return;let x=g,P=Number(new Date),A=P-(f||P);x.diff=A,x.prev=f,x.curr=P,f=P,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let N=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(G,Y)=>{if(G==="%%")return"%";N++;let b=t.formatters[Y];if(typeof b=="function"){let v=y[N];G=b.call(x,v),y.splice(N,1),N--}return G}),t.formatArgs.call(x,y),(x.log||t.log).apply(x,y)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,m=t.enabled(u)),m),set:y=>{d=y}}),typeof t.init=="function"&&t.init(g),g}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function s(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(u))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var nl=YI(),HI=["#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 qI(){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 zI(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+rl(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var GI=console.debug??console.log??(()=>{});function WI(r){try{r?nl?.setItem("debug",r):nl?.removeItem("debug")}catch{}}function jI(){let r;try{r=nl?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function YI(){try{return localStorage}catch{}}function ZI(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var $b=Mp({formatArgs:zI,save:WI,load:jI,useColors:qI,setupFormatters:ZI,colors:HI,storage:nl,log:GI});var X=$b;X.formatters.b=r=>r==null?"undefined":ee.baseEncode(r);X.formatters.t=r=>r==null?"undefined":ge.baseEncode(r);X.formatters.m=r=>r==null?"undefined":Pe.baseEncode(r);X.formatters.p=r=>r==null?"undefined":r.toString();X.formatters.c=r=>r==null?"undefined":r.toString();X.formatters.k=r=>r==null?"undefined":r.toString();X.formatters.a=r=>r==null?"undefined":r.toString();X.formatters.e=r=>{if(r==null)return"undefined";let e=Vb(r.message),t=Vb(r.stack);return e!=null&&t!=null?t.includes(e)?t:`${e}
4
+ ${t}`:t??e??r.toString()};function XI(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function pn(){return{forComponent(r){return ps(r)}}}function ps(r){let e=XI(`${r}:trace`);return X.enabled(`${r}:trace`)&&X.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=X(`${r}:trace`)),Object.assign(X(r),{error:X(`${r}:error`),trace:e,newScope:t=>ps(`${r}:${t}`)})}function Vb(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var ms=class extends Wt{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};var ol=class extends Wt{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};var sl=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Up}consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new Ec("Rate limit exceeded",i);return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Up=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var Fp=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function tt(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Fp({name:e,metrics:t}):n=new Map,n}function JI(r){return r[Symbol.asyncIterator]!=null}function QI(r){if(JI(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Ui=QI;function eC(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var gs=eC;function tC(r){return r[Symbol.asyncIterator]!=null}function rC(r,e){let t=0;if(tC(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=gs(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){yield await i;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield i;for(let c of n)yield a(c,t++)})()}var il=rC;function nC(r){return r[Symbol.asyncIterator]!=null}function oC(r,e){return nC(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var al=oC;var At=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function cl(r,e,t,n){let o=new At(n?.errorMessage);n?.errorCode!=null&&(o.code=n.errorCode);let s=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(o):new Promise((i,a)=>{function c(){Vp(t,"abort",f),Vp(r,e,l),Vp(r,s,u)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),i(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(o)};$p(t,"abort",f),$p(r,e,l),$p(r,s,u)})}function $p(r,e,t){r!=null&&(Kb(r)?r.addEventListener(e,t):r.addListener(e,t))}function Vp(r,e,t){r!=null&&(Kb(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function Kb(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}var Hb=Symbol.for("nodejs.util.inspect.custom"),sC=114,Fi=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ga]=!0;toString(){return this.string==null&&(this.string=ee.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return V.createV1(sC,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return W(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return W(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Hb](){return`PeerId(${this.toString()})`}},$i=class extends Fi{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Vi=class extends Fi{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Ki=class extends Fi{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},iC=2336,Hi=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ke.digest(T(this.url))}[Hb](){return`PeerId(${this.url})`}[Ga]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return V.createV1(iC,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=B(e)),e.toString()===this.toString())}};var aC=114,qb=2336;function mr(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Xe(ee.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Qn(V.parse(r));if(e==null)throw new C('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Xe(e.decode(r))}return ys(t)}function Kp(r){if(r.type==="Ed25519")return new Vi({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Ki({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new $i({multihash:r.toCID().multihash,publicKey:r});throw new Ot}function zb(r){return Kp(r.publicKey)}function ys(r){if(lC(r))return new $i({multihash:r});if(cC(r))try{let e=jo(r);if(e.type==="Ed25519")return new Vi({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Ki({multihash:r,publicKey:e})}catch{let t=B(r.digest);return new Hi(new URL(t))}throw new Eo("Supplied PeerID Multihash is invalid")}function Qn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==aC&&r.code!==qb)throw new Fa("Supplied PeerID CID is invalid");if(r.code===qb){let e=B(r.multihash.digest);return new Hi(new URL(e))}return ys(r.multihash)}function cC(r){return r.code===ke.code}function lC(r){return r.code===gt.code}function eo(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function ll(r){let e=Xe(ee.decode(`z${r}`));return ys(e)}var Dt=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return eo(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return eo(this.map.values(),e=>e.key)}values(){return eo(this.map.values(),e=>e.value)}get size(){return this.map.size}};var to=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return eo(this.set.entries(),e=>{let t=ll(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ll(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return eo(this.set.values(),e=>ll(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var Hp=class extends Dt{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function qp(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Hp({name:e,metrics:t}):n=new Dt,n}function uC(r){return r[Symbol.asyncIterator]!=null}function fC(r){if(uC(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=ye([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return ye(e,t)}var Gb=fC;var Gp=vn(jb(),1);function Wp(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var zi=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=Wp(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}setPriority(e,t){let n=this.#e.findIndex(s=>s.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[o]=this.#e.splice(n,1);this.enqueue(o.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var ro=class extends Gp.default{#e;#t;#r=0;#a;#i;#l=0;#o;#u;#n;#m;#s=0;#f;#c;#g;#b=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:zi,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#a=e.intervalCap,this.#i=e.interval,this.#n=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#c=e.autoStart===!1}get#x(){return this.#t||this.#r<this.#a}get#v(){return this.#s<this.#f}#E(){this.#s--,this.#d(),this.emit("next")}#S(){this.#w(),this.#y(),this.#u=void 0}get#A(){let e=Date.now();if(this.#o===void 0){let t=this.#l-e;if(t<0)this.#r=this.#e?this.#s:0;else return this.#u===void 0&&(this.#u=setTimeout(()=>{this.#S()},t)),!0}return!1}#d(){if(this.#n.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#s===0&&this.emit("idle"),!1;if(!this.#c){let e=!this.#A;if(this.#x&&this.#v){let t=this.#n.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#o!==void 0||(this.#o=setInterval(()=>{this.#w()},this.#i),this.#l=Date.now()+this.#i)}#w(){this.#r===0&&this.#s===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#r=this.#e?this.#s:0,this.#h()}#h(){for(;this.#d(););}get concurrency(){return this.#f}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#f=e,this.#h()}async#I(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#n.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#b++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#s++;try{t.signal?.throwIfAborted(),this.#r++;let s=e({signal:t.signal});t.timeout&&(s=Ai(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#I(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof Si&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#E()}},t),this.emit("add"),this.#d()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#c?(this.#c=!1,this.#h(),this):this}pause(){this.#c=!0}clear(){this.#n=new this.#m}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#s===0&&this.#n.size===0||await this.#p("idle")}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#s}get isPaused(){return this.#c}};function fl(r){let e=[It.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var jp=60;function dl(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:It[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:It[e.type],TTL:e.TTL??e.ttl??jp,data:e.data instanceof Uint8Array?B(e.data):e.data}))}}var pC=4;function Yp(r,e={}){let t=new ro({concurrency:e.queryConcurrency??pC});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),fl(o.types).forEach(a=>{s.append("type",It[a])}),o.onProgress?.(new Z("dns:query",n));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=dl(await a.json());return o.onProgress?.(new Z("dns:response",c)),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function Yb(){return[Yp("https://cloudflare-dns.com/dns-query"),Yp("https://dns.google/resolve")]}var Jb=vn(Xb(),1);var Zp=class{lru;constructor(e){this.lru=(0,Jb.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return dl({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:It[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??jp)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function Qb(r){return new Zp(r)}var mC=1e3,hl=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=Qb(e.cacheSize??mC),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Yb())}async query(e,t={}){let n=fl(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new Z("dns:cache",o)),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new Z("dns:error",l))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var It;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(It||(It={}));function pl(r={}){return new hl(r)}var Rr="/",ex=new TextEncoder().encode(Rr),ml=ex[0],xe=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=T(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==ml)throw new Error("Invalid key")}toString(e="utf8"){return B(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Rr))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=ex),this._buf[0]!==ml){let e=new Uint8Array(this._buf.byteLength+1);e.fill(ml,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===ml;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Rr).slice(1)}type(){return gC(this.baseNamespace())}name(){return yC(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Rr)||(e+=Rr),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Rr):new r(e.slice(0,-1).join(Rr))}child(e){return this.toString()===Rr?e:e.toString()===Rr?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...wC(e.map(t=>t.namespaces()))])}};function gC(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function yC(r){let e=r.split(":");return e[e.length-1]}function wC(r){return[].concat(...r)}function gl({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*bC(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t],s=V.asCID(n);s!=null?yield[o.join("/"),s]:typeof n=="object"&&(yield*Xp(n,o))}else{let t=V.asCID(e);t!=null?yield[r.join("/"),t]:yield*Xp(e,r)}}function*Xp(r,e){if(r==null||r instanceof Uint8Array)return;let t=V.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,o]of Object.entries(r)){let s=[...e,n];yield*bC(s,o)}}function*xC(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let o=[...r,t];yield o.join("/"),typeof n=="object"&&V.asCID(n)==null&&(yield*Jp(n,o))}else yield*Jp(e,r)}function*Jp(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let o=[...e,t];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&V.asCID(n)==null&&(yield*xC(o,n))}}function vC(r,e){let t=r;for(let[n,o]of e.entries()){if(t=t[o],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(i=>`[${JSON.stringify(i)}]`).join("")}`);let s=V.asCID(t);if(s!=null)return{value:s,remaining:e.slice(n+1).join("/")}}return{value:t}}var Qp=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:gl(),bytes:gl(),value:gl(),asBlock:gl()})}links(){return Xp(this.value,[])}tree(){return Jp(this.value,[])}get(e="/"){return vC(this.value,e.split("/").filter(Boolean))}};function tx({bytes:r,cid:e,value:t,codec:n}){let o=t!==void 0?t:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Qp({cid:e,bytes:r,value:o})}var yl=class extends Error{static name="AlreadyPinnedError";name="AlreadyPinnedError"},Gi=class extends Error{static name="BlockPinnedError";name="BlockPinnedError"},wl=class extends Error{static name="InvalidDatastoreVersion";name="InvalidDatastoreVersion"};var ox="/pin/",rx="/pinned-block/",em=cr,nx=1;function bl(r){return r.version===0&&(r=r.toV1()),new xe(`${ox}${r.toString(em)}`)}var xl=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=bl(e);if(await this.datastore.has(n))throw new yl("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new C("Depth must be greater than or equal to 0");let s=new Wt({concurrency:nx});for await(let a of this.#e(e,s,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>W(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,hn(i),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=await this.getCodec(e.code),s=await Gb(this.blockstore.get(e,n)),i=tx({bytes:s,cid:e,codec:o});yield e;for(let[,a]of i.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new xe(`${rx}${em.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=St(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,hn(s),n),n.onProgress?.(new Z("helia:pin:add",e))}}async*rm(e,t={}){let n=bl(e),o=await this.datastore.get(n,t),s=St(o);await this.datastore.delete(n,t);let i=new Wt({concurrency:nx});for await(let a of this.#e(e,i,{...t,depth:s.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>W(l,e.bytes)),!0),{...t,depth:s.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:ox+(e.cid!=null?`${e.cid.toString(cr)}`:"")},e)){let o=V.parse(t.toString().substring(5),cr),s=St(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new xe(`${rx}${em.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=bl(e),o=await this.datastore.get(n,t);return St(o)}async setMetadata(e,t,n){let o=bl(e),s=await this.datastore.get(o,n),i=St(s);i.metadata=t??{},await this.datastore.put(o,hn(i),n)}};var tm=1,rm=5;var Wi=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},mn=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},ji=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},Yi=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}},nm=class extends Error{static name="InvalidCodecError";constructor(e="Invalid codec"){super(e),this.name="InvalidCodecError"}};var EC=5,vl=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??EC,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await ir(...this.routers)}async stop(){await ar(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new mn("No content routers available");let n=new ms({concurrency:this.providerLookupConcurrency});for await(let o of kt(n.toGenerator(),...no(this.routers,"findProviders").map(s=>s.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let s=await this.findPeer(o.id,t);return s.multiaddrs.length===0?null:s}catch(s){return this.log.error("could not load multiaddrs for peer %p",o.id,s),null}},{peerId:o.id,signal:t.signal}).catch(s=>{this.log.error("could not load multiaddrs for peer %p",o.id,s)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new mn("No content routers available");await Promise.all(no(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(no(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(no(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(no(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new mn("No peer routers available");let n=this,o=kt(...no(this.routers,"findPeer").map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}})()));for await(let s of o)if(s!=null)return s;throw new Rt("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new mn("No peer routers available");for await(let n of kt(...no(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function no(r,e){return r.filter(t=>t[e]!=null)}var El=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Sl=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function sx(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Sl(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new Sl(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Al=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new At)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function SC(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Il=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=SC(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new At),this.cleanup())}async join(e={}){let t=new Al(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await sx(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function om(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Zi=class extends De{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=om(this.emitEmpty.bind(this),1),this.emitIdle=om(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new El;let n=new Il(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new At)}),this.clear()}async onEmpty(e){this.size!==0&&await cl(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await cl(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await cl(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=es({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail.result)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new At("Queue aborted"))};this.addEventListener("success",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var Cl="lock:worker:request-read",_l="lock:worker:abort-read-request",Tl="lock:worker:release-read",kl="lock:master:grant-read",Pl="lock:master:error-read",Bl="lock:worker:request-write",Dl="lock:worker:abort-write-request",Ll="lock:worker:release-write",Nl="lock:master:grant-write",Rl="lock:master:error-write",Ol="lock:worker:finalize",Ml="mortice",ix={singleProcess:!1};var sm=(r,e,t,n,o,s,i,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===o&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(f=>{let d=h=>{if(h?.data==null)return;let m={type:h.data.type,name:h.data.name,identifier:h.data.identifier};m.type===a&&m.identifier===u.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:i,name:u.name,identifier:u.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),u.type===s&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===Ol&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var ax=(r=10)=>Math.random().toString().substring(2,r+2);var Ul=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(Ml)}readLock(e){return this.sendRequest(Cl,_l,kl,Pl,Tl,e)}writeLock(e){return this.sendRequest(Bl,Dl,Nl,Rl,Ll,e)}finalize(){this.channel.postMessage({type:Ol,name:this.name}),this.channel.close()}async sendRequest(e,t,n,o,s,i){i?.signal?.throwIfAborted();let a=ax();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};i?.signal?.addEventListener("abort",u,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:s,identifier:a,name:this.name})})),d.data.type===o)){this.channel.removeEventListener("message",f),i?.signal?.removeEventListener("abort",u);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",f)})}};var cx=r=>{if(r=Object.assign({},ix,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(Ml),n=new De;return t.addEventListener("message",sm(n,t,"requestReadLock","abortReadLockRequest",Cl,_l,Pl,Tl,kl)),t.addEventListener("message",sm(n,t,"requestWriteLock","abortWriteLockRequest",Bl,Dl,Rl,Ll,Nl)),n}return new Ul(r.name)};var oo=new Map,Xi;function lx(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function AC(r){if(Xi==null&&(Xi=cx(r),!lx(Xi))){let e=Xi;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=oo.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortReadLockRequest",a),s.readLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,o=t.detail.identifier,s=oo.get(n);if(s==null)return;let i=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==o||i.abort()};e.addEventListener("abortWriteLockRequest",a),s.writeLock({signal:i.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,o=oo.get(n);o?.finalize()})}return Xi}async function im(r,e){let t,n,o=new Promise((i,a)=>{t=i,n=a}),s=()=>{n(new At)};return e?.signal?.addEventListener("abort",s,{once:!0}),r.add(async()=>{await new Promise(i=>{t(()=>{e?.signal?.removeEventListener("abort",s),i()})})},{signal:e?.signal}).catch(i=>{n(i)}),o}var ux=(r,e)=>{let t=oo.get(r);if(t!=null)return t;let n=AC(e);if(lx(n))return t=n,oo.set(r,t),t;let o=new Zi({concurrency:1}),s;return t={async readLock(i){if(s!=null)return im(s,i);s=new Zi({concurrency:e.concurrency,autoStart:!1});let a=s,c=im(s,i);return o.add(async()=>{a.start(),await a.onIdle().then(()=>{s===a&&(s=null)})}),c},async writeLock(i){return s=null,im(o,i)},finalize:()=>{oo.delete(r)},queue:o},oo.set(r,t),e.autoFinalize===!0&&o.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var IC={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function Ji(r){let e=Object.assign({},IC,r);return ux(e.name,e)}var Fl=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Ji({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await ir(this.child),this.started=!0}async stop(){await ar(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async*get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Gi("Block was pinned - please unpin and try again");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany((async function*(){for await(let s of e){if(await o.pins.isPinned(s))throw new Gi("Block was pinned - please unpin and try again");yield s}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var am=new xe("/version"),fx=1;async function dx(r){if(!await r.has(am)){await r.put(am,T(`${fx}`));return}let e=await r.get(am),t=B(e);if(parseInt(t,10)!==fx)throw new wl("Invalid datastore version, a datastore migration may be required")}var um={};_e(um,{code:()=>lm,decode:()=>RC,decodeOptions:()=>DC,encode:()=>NC,encodeOptions:()=>PC,name:()=>LC,toByteView:()=>px});var hx=42;function px(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function CC(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=V.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new I(p.tag,hx),new I(p.bytes,t)]}function _C(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function TC(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function kC(r){for(let e of r.keys())if(typeof e!="string"||e.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var cm={float64:!0,typeEncoders:{Map:kC,Object:CC,undefined:_C,number:TC}},PC={...cm,typeEncoders:{...cm.typeEncoders}};function BC(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return V.decode(r.subarray(1))}var $l={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};$l.tags[hx]=BC;var DC={...$l,tags:$l.tags.slice()},LC="dag-cbor",lm=113,NC=r=>hn(r,cm),RC=r=>St(px(r),$l);var ym={};_e(ym,{code:()=>gm,decode:()=>gx,encode:()=>mx,format:()=>GC,name:()=>zC,parse:()=>jC,stringify:()=>GC});var fm=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===p.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===p.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[p.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s);e.push(o)}[p.negint.major](e,t){this[p.uint.major](e,t)}[p.bytes.major](e,t){throw new Error(`${Lr} unsupported type: Uint8Array`)}[p.string.major](e,t){this.prefix(e);let n=Uc(JSON.stringify(t.value));e.push(n.length>32?Bi(n):n)}[p.array.major](e,t){this.prefix(e),this.inRecursive.push({type:p.array,elements:0}),e.push([91])}[p.map.major](e,t){this.prefix(e),this.inRecursive.push({type:p.map,elements:0}),e.push([123])}[p.tag.major](e,t){}[p.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(i.type===p.array)e.push([93]);else if(i.type===p.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${Lr} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],s=!1;for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i),!s&&(o[i]===46||o[i]===101||o[i]===69)&&(s=!0);s||(o.push(46),o.push(48)),e.push(o)}};function OC(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Lr} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==p.string||n.type!==p.string)throw new Error(`${Lr} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Lr} unexpected duplicate map keys, this is not supported`)}var MC={addBreakTokens:!0,mapSorter:OC};function dm(r,e){return e=Object.assign({},MC,e),Dp(r,new fm,e)}var ws=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${F} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${F} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new I(p.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${F} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${F} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let s=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(s);return n?new I(p.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new I(i>=0?p.uint:p.negint,i,this._pos-e):new I(i>=0?p.uint:p.negint,BigInt(s),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${F} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let s=this._pos,i=0;s<this.data.length&&i<65536;s++,i++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,s));return this._pos=s+1,new I(p.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${F} unexpected end of unicode escape sequence at position ${this._pos}`);let s=0;for(let i=0;i<4;i++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${F} unexpected unicode escape character at position ${this._pos}`);s=s*16+a,this._pos++}return s},o=()=>{let s=this.ch(),i=null,a=s>239?4:s>223?3:s>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${F} unexpected unicode sequence at position ${this._pos}`);let c,l,u,f;switch(a){case 1:s<128&&(i=s);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(s&31)<<6|c&63,f>127&&(i=f));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(f=(s&15)<<12|(c&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(i=f));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(f=(s&15)<<18|(c&63)<<12|(l&63)<<6|u&63,f>65535&&f<1114112&&(i=f))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let s=this.ch(),i;switch(s){case 92:if(this._pos++,this.done())throw new Error(`${F} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${F} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new I(p.string,Cp(t),this._pos-e);default:if(s<32)throw new Error(`${F} invalid control character at position ${this._pos}`);s<128?(t.push(s),this._pos++):o()}}throw new Error(`${F} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new I(p.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new I(p.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new I(p.null,null,4);case 102:return this.expect([102,97,108,115,101]),new I(p.false,!1,5);case 116:return this.expect([116,114,117,101]),new I(p.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${F} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new I(p.break,void 0,1);if(this.ch()!==44)throw new Error(`${F} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new I(p.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new I(p.break,void 0,1);if(this.ch()!==44)throw new Error(`${F} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new I(p.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${F} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${F} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function hm(r,e){return e=Object.assign({tokenizer:new ws(r,e)},e),St(r,e)}function FC(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function $C(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=V.asCID(r);if(!e)return null;let t=e.toString();return[new I(p.map,1/0,1),new I(p.string,"/",1),new I(p.string,t,t.length),new I(p.break,void 0,1)]}function Vl(r){let e=Pe.encode(r).slice(1);return[new I(p.map,1/0,1),new I(p.string,"/",1),new I(p.map,1/0,1),new I(p.string,"bytes",5),new I(p.string,e,e.length),new I(p.break,void 0,1),new I(p.break,void 0,1)]}function Zt(r){return Vl(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function VC(r){return Vl(new Uint8Array(r))}function KC(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function HC(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var qC={typeEncoders:{Object:$C,Buffer:Vl,Uint8Array:Vl,Int8Array:Zt,Uint16Array:Zt,Int16Array:Zt,Uint32Array:Zt,Int32Array:Zt,Float32Array:Zt,Float64Array:Zt,Uint8ClampedArray:Zt,BigInt64Array:Zt,BigUint64Array:Zt,DataView:Zt,ArrayBuffer:VC,undefined:KC,number:HC}},pm=class extends ws{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===p.map){let t=this._next();if(t.type===p.string&&t.value==="/"){let n=this._next();if(n.type===p.string){if(this._next().type!==p.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new I(p.tag,42,0)}if(n.type===p.map){let o=this._next();if(o.type===p.string&&o.value==="bytes"){let s=this._next();if(s.type===p.string){for(let a=0;a<2;a++)if(this._next().type!==p.break)throw new Error("Invalid encoded Bytes form");let i=Pe.decode(`m${s.value}`);return new I(p.bytes,i,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},mm={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};mm.tags[42]=V.parse;var zC="dag-json",gm=297,mx=r=>dm(r,qC),gx=r=>{let e=FC(r),t=Object.assign(mm,{tokenizer:new pm(e,mm)});return hm(e,t)},GC=r=>WC.decode(mx(r));var WC=new TextDecoder,jC=r=>gx(YC.encode(r)),YC=new TextEncoder;var Sm={};_e(Sm,{code:()=>Em,createLink:()=>Cx,createNode:()=>Ix,decode:()=>c_,encode:()=>a_,name:()=>i_,prepare:()=>xm,validate:()=>vm});var ZC=new TextDecoder;function wm(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Kl(r,e){let t;[t,e]=wm(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function yx(r,e){let t;return[t,e]=wm(r,e),[t&7,t>>3,e]}function XC(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=yx(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Kl(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Kl(r,n),e.Name=ZC.decode(i)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=wm(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function wx(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=yx(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=Kl(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Kl(r,t),n.push(XC(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let i={};return s&&(i.Data=s),i.Links=n||[],i}var xx=new TextEncoder,bx=2**32,JC=2**31;function QC(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=Qi(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=xx.encode(r.Name);t-=n.length,e.set(n,t),t=Qi(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=Qi(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function vx(r){let e=t_(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=Qi(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let s=QC(r.Links[o],t.subarray(0,n));n-=s,n=Qi(t,n,s)-1,t[n]=18}return t}function e_(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+bs(t)}if(typeof r.Name=="string"){let t=xx.encode(r.Name).length;e+=1+t+bs(t)}return typeof r.Tsize=="number"&&(e+=1+bs(r.Tsize)),e}function t_(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+bs(t)}if(r.Links)for(let t of r.Links){let n=e_(t);e+=1+n+bs(n)}return e}function Qi(r,e,t){e-=bs(t);let n=e;for(;t>=JC;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function bs(r){return r%2===0&&r++,Math.floor((r_(r)+6)/7)}function r_(r){let e=0;return r>=bx&&(r=Math.floor(r/bx),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+n_[r]}var n_=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var o_=["Data","Links"],s_=["Hash","Name","Tsize"],bm=new TextEncoder;function Sx(r,e){if(r===e)return 0;let t=r.Name?bm.encode(r.Name):[],n=e.Name?bm.encode(e.Name):[],o=t.length,s=n.length;for(let i=0,a=Math.min(o,s);i<a;++i)if(t[i]!==n[i]){o=t[i],s=n[i];break}return o<s?-1:s<o?1:0}function Ex(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Ax(r){if(typeof r.asCID=="object"){let t=V.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=V.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=V.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=V.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function xm(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=bm.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(Ax),e.Links.sort(Sx);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function vm(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Ex(r,o_))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!Ex(t,s_))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&Sx(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function Ix(r,e=[]){return xm({Data:r,Links:e})}function Cx(r,e,t){return Ax({Hash:t,Name:r,Tsize:e})}function _x(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var i_="dag-pb",Em=112;function a_(r){vm(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),vx(e)}function c_(r){let e=_x(r),t=wx(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=V.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}function xs(r){return r?.then!=null}function Tx(r=[],e){let t={[Em]:Sm,[zs]:Gs,[lm]:um,[gm]:ym,[Rd]:Za};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);xs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new Yi(`Could not load codec for ${n}`)}}function kx(r=[],e){let t={[gt.code]:gt,[Xa.code]:Xa,[ke.code]:ke};return r.forEach(n=>{t[n.code]=n}),async n=>{let o=t[n];if(o==null&&e!=null){let s=e(n);xs(s)?o=await s:o=s,t[o.code]=o}if(o!=null)return o;throw new ji(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var Lt=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var Or=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,bytes:o}of e)await this.put(n,o,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var Hl=0,ql=class extends Or{child;constructor(e){super(),this.child=e}put(e,t,n){return e.multihash.code===Hl||this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}*get(e,t){if(e.multihash.code===Hl){t?.signal?.throwIfAborted(),yield e.multihash.digest;return}if(this.child==null)throw t?.signal?.throwIfAborted(),new Lt;yield*this.child.get(e,t)}has(e,t){return e.multihash.code===Hl?(t?.signal?.throwIfAborted(),!0):this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===Hl){t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}*getAll(e){this.child!=null&&(yield*this.child.getAll(e)),e?.signal?.throwIfAborted()}};function l_(r){return r[Symbol.asyncIterator]!=null}function u_(r,e){let t=0;if(l_(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=gs(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();let i=e(o,t++);if(typeof i.then=="function")return(async function*(){await i&&(yield o);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)})()}var Xt=u_;function f_(r){return r[Symbol.asyncIterator]!=null}function Px(r){return r?.then!=null}function d_(r,e){let t=0;if(f_(r))return(async function*(){for await(let c of r){let l=e(c,t++);Px(l)&&await l,yield c}})();let n=gs(r),{value:o,done:s}=n.next();if(s===!0)return(function*(){})();if(typeof e(o,t++)?.then=="function")return(async function*(){yield o;for(let c of n){let l=e(c,t++);Px(l)&&await l,yield c}})();let a=e;return(function*(){yield o;for(let c of n)a(c,t++),yield c})()}var Am=d_;var zl=class{child;getHasher;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new ql(e.blockstore),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new Z("blocks:put:duplicate",e)),e):(n.onProgress?.(new Z("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n))),n.onProgress?.(new Z("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=Xt(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new Z("blocks:put-many:duplicate",s)),!i}),o=Am(n,async({cid:s})=>{t.onProgress?.(new Z("blocks:put-many:providers:notify",s)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(s,t)))});t.onProgress?.(new Z("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async*get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new Z("blocks:get:providers:get",e));let o=await Bx(e,this.components.blockBrokers,n,{...t,log:this.log});t.onProgress?.(new Z("blocks:get:blockstore:put",e)),await this.child.put(e,o,t),t.onProgress?.(new Z("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(e,t))),yield o;return}t.onProgress?.(new Z("blocks:get:blockstore:get",e)),yield*this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new Z("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Am(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let o=await this.getHasher(n.multihash.code);t.onProgress?.(new Z("blocks:get-many:providers:get",n));let s=await Bx(n,this.components.blockBrokers,o,{...t,log:this.log});t.onProgress?.(new Z("blocks:get-many:blockstore:put",n)),await this.child.put(n,s,t),t.onProgress?.(new Z("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(n,t)))}}))}async delete(e,t={}){t.onProgress?.(new Z("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new Z("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany((async function*(){for await(let n of e)yield n})(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new Z("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},Gl=class extends zl{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await ir(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await ar(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new Im({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},Im=class extends zl{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=me([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=me([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async*get(e,t={}){let n=me([this.closeController.signal,t.signal]);try{yield*super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=me([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=me([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=me([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=me([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=me([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function h_(r){return typeof r.retrieve=="function"}var p_=(r,e)=>{if(e==null)throw new C(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,o=e.digest(t);if(xs(o)?n=await o:n=o,!W(n.digest,r.multihash.digest))throw new Eo("Hash of downloaded block did not match multihash from passed CID")}};async function Bx(r,e,t,n){let o=p_(r,t),s=new AbortController,i=me([s.signal,n.signal]);s.signal;let a=[];for(let c of e)h_(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:i,validateFn:async f=>{await o(f),l=!0}});return l||await o(u),u}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{s.abort(),i.clear()}}var ta=class extends De{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(e,t){super(),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Hn(this.maxProviders),this.initialProviders=t.providers??[]}async retrieve(e,t={}){let n=Pe.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let s=le();if(this.requests.set(n,s.promise),this.providers.length===0){let u=!1;this.initialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.initialPeerSearchComplete,u&&this.log("found initial session peers for %c",e)}let i=!1,a=new Wt({concurrency:this.maxProviders});a.addEventListener("failure",u=>{this.log.error("error querying provider %o, evicting from session",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),a.addEventListener("success",u=>{i=!0,s.resolve(u.detail.result)}),a.addEventListener("idle",()=>{if(i){this.log.trace("session idle, found block");return}if(t.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",e);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let f=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(f)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(u=>{this.log.error("could not find new providers for %c",e,u),s.reject(u)})});let c=u=>{a.add(async()=>this.queryProvider(e,u.detail,t),{provider:u.detail}).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,f)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async u=>a.add(async()=>this.queryProvider(e,u,t),{provider:u}))).catch(u=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,u)});let l=()=>{s.reject(new mt(t.signal?.reason??"Session aborted")),a.abort()};t.signal?.addEventListener("abort",l);try{return await s.promise}finally{this.removeEventListener("provider",c),t.signal?.removeEventListener("abort",l),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=le(),s=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e),this.initialProviders.length>0)for(;s<t&&this.initialProviders.length>0;){let i=this.initialProviders.pop();if(i==null)break;let a=await this.convertToProvider(i,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",s,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),s++,s===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",s);break}}if(s<this.maxProviders)for await(let i of this.findNewProviders(e,n)){if(s===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",s,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),s++,s===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",s);break}}if(this.log("found %d/%d new session peers",s,this.maxProviders),s<t)throw new Wi(`Found ${s} of ${t} ${this.name} providers for ${e}`)}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",e,i.errors??i),o.reject(i)}),o.promise}};var Wl=class{libp2p;blockstore;datastore;events;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??pn(),this.log=this.logger.forComponent("helia"),this.getHasher=kx(e.hashers,e.loadHasher),this.getCodec=Tx(e.codecs,e.loadCodec),this.dns=e.dns??pl(),this.metrics=e.metrics,this.libp2p=e.libp2p,this.events=new De;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,libp2p:this.libp2p,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new vl(t,{routers:(e.routers??[]).flatMap(o=>{let s=[o];return o[bo]!=null&&s.push(o[bo]),o[Ao]!=null&&s.push(o[Ao]),s}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new Gl(t);this.pins=new xl(e.datastore,n,this.getCodec),this.blockstore=new Fl(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await dx(this.datastore),await ir(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("start",{detail:this}))}async stop(){await ar(this.blockstore,this.datastore,this.routing,this.libp2p),this.events.dispatchEvent(new CustomEvent("stop",{detail:this}))}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await Ui(o.deleteMany((async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new Z("helia:gc:deleted",s))}catch(i){n.log.error("Error during gc",i),e.onProgress?.(new Z("helia:gc:error",i))}})()))}finally{t()}this.log("gc finished")}};var m_=[6,53,56,54,55];function Dx(r){return Rx("sni",r)?.value}function Lx(r){let e=Rx("tcp",r)?.value;return e==null?"":`:${e}`}function Rx(r,e){return e.find(t=>t.name===r)}function Nx(r){return r.some(({code:e})=>e===448)}function Jt(r,e){let t=Ox[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var Ox={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Jt(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Jt(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Jt(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Jt(t,e)}`},http:(r,e)=>{let t=Nx(e),n=Dx(e),o=Lx(e);if(t&&n!=null)return`https://${n}${o}`;let s=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Jt(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Jt(t,e),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Jt(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Jt(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Jt(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=Nx(e),n=Dx(e),o=Lx(e);if(t&&n!=null)return`wss://${n}${o}`;let s=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=Jt(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Jt(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function jl(r,e){let n=oe(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=Ox[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return e?.assumeHttp!==!1&&m_.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 de=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),q=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),Mx=r=>({match:e=>r.match(e)===!1?e:!1}),re=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),nt=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),ue=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function he(...r){function e(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 t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var g_=q(421),Ux=he(g_),Zl=q(54),Xl=q(55),Jl=q(56),_m=q(53),cF=he(Zl,re(q(421))),lF=he(Xl,re(q(421))),uF=he(Jl,re(q(421))),Fx=he(nt(_m,Jl,Zl,Xl),re(q(421))),$x=ue(q(4),re(q(43))),Vx=ue(re(q(42)),q(41),re(q(43))),Tm=nt($x,Vx),so=nt(Tm,_m,Zl,Xl,Jl),fF=he(nt(Tm,ue(nt(_m,Jl,Zl,Xl),re(q(421))))),km=he($x),Pm=he(Vx),dF=he(Tm),Bm=ue(so,q(6)),ra=ue(so,q(273)),na=he(ue(Bm,re(q(421)))),hF=he(ra),Dm=ue(ra,de(460),re(q(421))),Ql=ue(ra,de(461),re(q(421))),y_=nt(Dm,Ql),pF=he(Dm),Kx=he(Ql),Cm=nt(so,Bm,ra,Dm,Ql),Hx=nt(ue(Cm,de(477),re(q(421)))),io=he(Hx),qx=nt(ue(Cm,de(478),re(q(421))),ue(Cm,de(448),re(q(449)),de(477),re(q(421)))),oa=he(qx),zx=ue(ra,de(280),re(q(466)),re(q(466)),re(q(421))),Lm=he(zx),Gx=ue(Ql,de(465),re(q(466)),re(q(466)),re(q(421))),Nm=he(Gx),Yl=nt(Hx,qx,ue(Bm,re(q(421))),ue(y_,re(q(421))),ue(so,re(q(421))),zx,Gx,q(421)),mF=he(Yl),w_=ue(re(Yl),de(290),Mx(de(281)),re(q(421))),ao=he(w_),b_=nt(ue(Yl,de(290),de(281),re(q(421))),ue(Yl,de(281),re(q(421))),ue(de(281),re(q(421)))),Rm=he(b_),x_=nt(ue(so,q(6),de(480),re(q(421))),ue(so,de(480),re(q(421)))),Wx=he(x_),v_=ue(so,nt(ue(q(6,"443"),de(480)),ue(q(6),de(443)),ue(q(6),de(448),de(480)),ue(de(448),de(480)),de(448),de(443)),re(q(421))),jx=he(v_),E_=nt(ue(q(777),re(q(421)))),gF=he(E_),S_=nt(ue(q(400),re(q(421)))),yF=he(S_);function Om(r,e,t){return r.filter(n=>{if(jx.matches(n)||e&&Wx.matches(n))return t||Fx.matches(n)?!0:zt(n)===!1;if(!e&&t){let{host:o}=te(n);if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*eu(r,e,t,n,o,s={}){for await(let i of e.findProviders(r,s)){let a=Om(i.multiaddrs,n,o);if(a.length===0)continue;let c=jl(a[0]);yield new vs(c,{logger:t,transformRequestInit:s.transformRequestInit})}}async function Yx(r,e,t){let{signal:n,log:o}=t??{},s=r.headers.get("content-length");if(s!=null){let c=parseInt(s,10);if(c>e)throw o?.error("content-length header (%d) is greater than the limit (%d)",c,e),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 (${e}).`)}let i=r.body?.getReader();if(i==null)throw new Error("Response body is not readable");let a=new ae;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>e)throw new Error(`Response body is greater than the limit (${e}), received ${a.byteLength} bytes.`)}}finally{i.cancel().catch(c=>{o?.error("error cancelling reader - %e",c)}).finally(()=>{i.releaseLock()})}return a.subarray()}var vs=class{url;#e=0;#t=0;#r=0;#a=0;#i=new Map;log;transformRequestInit;constructor(e,{logger:t,transformRequestInit:n}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#l(e){let t=e.multihash.bytes;return Pe.encode(t)}async getRawBlock(e,{signal:t,maxSize:n=Zx}={}){let o=new URL(this.url.toString());if(o.pathname=`/ipfs/${e.toString()}`,o.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let s=this.#l(e),i=new AbortController,a=()=>{i.abort()};t?.addEventListener("abort",a);try{let c=this.#i.get(s);if(c==null){this.#e++;let l={signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},u=this.transformRequestInit!=null?await this.transformRequestInit(l):l;c=fetch(o.toString(),u).then(async f=>{if(this.log("GET %s %d",o,f.status),!f.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);let d=await Yx(f,n,{signal:i.signal,log:this.log});return this.#a++,d}),this.#i.set(s,c)}return await c}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",a),this.#i.delete(s)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#a/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#a,pendingResponses:this.#i.size}}};var Mm=class extends ta{routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??tu,this.allowLocal=t.allowLocal??ru,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let o=await t.getRawBlock(e,n);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*eu(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t){if(sr(e))return;let n=Om(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(n.length===0)return;let o=jl(n[0]);return new vs(o,{logger:this.logger,transformRequestInit:this.transformRequestInit})}};function Xx(r,e){return new Mm(r,e)}var nu=class{allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??tu,this.allowLocal=t.allowLocal??ru,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let o of eu(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,o.url);try{let s=await o.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s",e,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s",e,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return Xx({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var tu=!1,ru=!1,Zx=2097152;function Um(r={}){return e=>new nu(e,r)}var Jx=Symbol.for("@libp2p/content-routing");var Fm=Symbol.for("@libp2p/peer-id");var Qx=Symbol.for("@libp2p/peer-routing");var ou=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var gr=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}};var su=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},iu=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};X.formatters.b=r=>r==null?"undefined":ee.baseEncode(r);X.formatters.t=r=>r==null?"undefined":ge.baseEncode(r);X.formatters.m=r=>r==null?"undefined":Pe.baseEncode(r);X.formatters.p=r=>r==null?"undefined":r.toString();X.formatters.c=r=>r==null?"undefined":r.toString();X.formatters.k=r=>r==null?"undefined":r.toString();X.formatters.a=r=>r==null?"undefined":r.toString();X.formatters.e=r=>r==null?"undefined":ev(r.stack)??ev(r.message)??r.toString();function A_(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function $m(r){let e=A_(`${r}:trace`);return X.enabled(`${r}:trace`)&&X.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=X(`${r}:trace`)),Object.assign(X(r),{error:X(`${r}:error`),trace:e,newScope:t=>$m(`${r}:${t}`)})}function ev(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var tv=Symbol.for("nodejs.util.inspect.custom"),I_=114,sa=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Fm]=!0;toString(){return this.string==null&&(this.string=ee.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return V.createV1(I_,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return W(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return W(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[tv](){return`PeerId(${this.toString()})`}},au=class extends sa{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},cu=class extends sa{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},lu=class extends sa{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},C_=2336,ia=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ke.digest(T(this.url))}[tv](){return`PeerId(${this.url})`}[Fm]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return V.createV1(C_,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=B(e)),e.toString()===this.toString())}};var __=114,rv=2336;function nv(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Xe(ee.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return T_(V.parse(r));if(e==null)throw new ou('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Xe(e.decode(r))}return ov(t)}function ov(r){if(P_(r))return new au({multihash:r});if(k_(r))try{let e=jo(r);if(e.type==="Ed25519")return new cu({multihash:r,publicKey:e});if(e.type==="secp256k1")return new lu({multihash:r,publicKey:e})}catch{let t=B(r.digest);return new ia(new URL(t))}throw new iu("Supplied PeerID Multihash is invalid")}function T_(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==__&&r.code!==rv)throw new su("Supplied PeerID CID is invalid");if(r.code===rv){let e=B(r.multihash.digest);return new ia(new URL(e))}return ov(r.multihash)}function k_(r){return r.code===ke.code}function P_(r){return r.code===gt.code}var Ge=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Mr=class extends Error{static name="ValidationError";name="ValidationError"},aa=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},uu=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function Km(r){return e=>B(e,r)}function Hm(r){return e=>T(e,r)}function Es(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function co(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function sv(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=T(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=co(n);return ye([t,o],t.length+o.length)}function iv(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ge.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=co(n);return ye([t,o],t.length+o.length)}function qm(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=B(e,"base32"),o=Es(t);return`${n}:${o}`}var zm=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Ge("Invalid byte value in IP address");e[n]=o}),e},av=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=at(t[n]),i;s&&(i=zm(t[n]),t[n]=B(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,B(i.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Ge("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},cv=function(r){if(r.byteLength!==4)throw new Ge("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},lv=function(r){if(r.byteLength!==16)throw new Ge("IPv6 address was incorrect length");let e=[];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")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ge(`Invalid IPv6 address "${t}"`)}};function uv(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ge(`Invalid IPv6 address "${r}"`)}}var Vm=Object.values(An).map(r=>r.decoder),B_=(function(){let r=Vm[0].or(Vm[1]);return Vm.slice(2).forEach(e=>r=r.or(e)),r})();function fv(r){return B_.decode(r)}function dv(r){return e=>r.encoder.encode(e)}function D_(r){if(parseInt(r).toString()!==r)throw new Mr("Value must be an integer")}function L_(r){if(r<0)throw new Mr("Value must be a positive integer, or zero")}function N_(r){return e=>{if(e>r)throw new Mr(`Value must be smaller than or equal to ${r}`)}}function R_(...r){return e=>{for(let t of r)t(e)}}var ca=R_(D_,L_,N_(65535));var Me=-1,Gm=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new uu(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Ct=new Gm,fT=[{code:4,name:"ip4",size:32,valueToBytes:zm,bytesToValue:cv,validate:r=>{if(!at(r))throw new Mr(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:co,bytesToValue:Es,validate:ca},{code:273,name:"udp",size:16,valueToBytes:co,bytesToValue:Es,validate:ca},{code:33,name:"dccp",size:16,valueToBytes:co,bytesToValue:Es,validate:ca},{code:41,name:"ip6",size:128,valueToBytes:av,bytesToValue:lv,stringToValue:uv,validate:r=>{if(!Xo(r))throw new Mr(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:Me},{code:43,name:"ipcidr",size:8,bytesToValue:Km("base10"),valueToBytes:Hm("base10")},{code:53,name:"dns",size:Me,resolvable:!0},{code:54,name:"dns4",size:Me,resolvable:!0},{code:55,name:"dns6",size:Me,resolvable:!0},{code:56,name:"dnsaddr",size:Me,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:co,bytesToValue:Es,validate:ca},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Me,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:Me,bytesToValue:Km("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?Hm("base58btc")(r):V.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:qm,valueToBytes:sv},{code:445,name:"onion3",size:296,bytesToValue:qm,valueToBytes:iv},{code:446,name:"garlic64",size:Me},{code:447,name:"garlic32",size:Me},{code:448,name:"tls"},{code:449,name:"sni",size:Me},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Me,bytesToValue:dv(qs),valueToBytes:fv},{code:480,name:"http"},{code:481,name:"http-path",size:Me,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:Me}];fT.forEach(r=>{Ct.addProtocol(r)});function hv(r){let e=[],t=0;for(;t<r.length;){let n=fr(r,t),o=Ct.getProtocol(n),s=be(n),i=dT(o,r,t+s),a=0;i>0&&o.size===Me&&(a=be(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,f=r.subarray(u,u+i);l.value=o.bytesToValue?.(f)??B(f)}e.push(l),t+=c}return e}function pv(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Ct.getProtocol(n.code),s=be(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??T(n.value),a=i.byteLength,o.size===Me&&(c=be(a)));let l=new Uint8Array(s+c+a),u=0;_r(n.code,l,u),u+=s,i!=null&&(o.size===Me&&(_r(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return ye(t,e)}function mv(r){if(r.charAt(0)!=="/")throw new Ge('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Ct.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Ge(`Component ${o} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ge(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Ge("Incomplete multiaddr");return e}function gv(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Ct.getProtocol(e.code);if(t==null)throw new Ge(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function dT(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:fr(e,t)}var hT=Symbol.for("nodejs.util.inspect.custom"),eg=Symbol.for("@multiformats/multiaddr"),pT=[53,54,55,56],Qm=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}};function mT(r){if(r==null&&(r="/"),wv(r))return r.getComponents();if(r instanceof Uint8Array)return hv(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),mv(r);if(Array.isArray(r))return r;throw new Ge("Must be a string, Uint8Array, Component[], or another Multiaddr")}var mu=class r{[eg]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=mT(e),t.validate!==!1&&gT(this)}get bytes(){return this.#r==null&&(this.#r=pv(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=gv(this.#e)),this.#t}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="";for(let{code:a,name:c,value:l}of this.#e)a===42&&(s=`%${l??""}`),pT.includes(a)&&(t="tcp",o=443,n=`${l??""}${s}`,e=a===55?6:4),(a===6||a===273)&&(t=c==="tcp"?"tcp":"udp",o=parseInt(l??"")),(a===4||a===41)&&(t="tcp",n=`${l??""}${s}`,e=a===41?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:t})=>{let n=Ct.getProtocol(e);return{code:e,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#e.map(({code:e})=>e)}protoNames(){return this.#e.map(({name:e})=>e)}tuples(){return this.#e.map(({code:e,value:t})=>{if(t==null)return[e];let n=Ct.getProtocol(e),o=[e];return t!=null&&o.push(n.valueToBytes?.(t)??T(t)),o})}stringTuples(){return this.#e.map(({code:e,value:t})=>t==null?[e]:[e,t])}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new aa(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:n,value:o})=>{n===421&&e.push([n,o]),n===290&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?B(ee.decode(`z${n}`),"base58btc"):B(V.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let e of this.#e)if(Ct.getProtocol(e.code).path)return e.value??null;return null}equals(e){return W(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=yv.get(t.name);if(n==null)throw new Qm(`no available resolver for ${t.name}`);return(await n(this,e)).map(s=>ua(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(this.#e.length!==2||this.#e[0].code!==4&&this.#e[0].code!==41||this.#e[1].code!==6&&this.#e[1].code!==273)}[hT](){return`Multiaddr(${this.toString()})`}};function gT(r){r.getComponents().forEach(e=>{let t=Ct.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}var yv=new Map;function wv(r){return!!r?.[eg]}function ua(r){return new mu(r)}async function*gu(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}X.formatters.b=r=>r==null?"undefined":ee.baseEncode(r);X.formatters.t=r=>r==null?"undefined":ge.baseEncode(r);X.formatters.m=r=>r==null?"undefined":Pe.baseEncode(r);X.formatters.p=r=>r==null?"undefined":r.toString();X.formatters.c=r=>r==null?"undefined":r.toString();X.formatters.k=r=>r==null?"undefined":r.toString();X.formatters.a=r=>r==null?"undefined":r.toString();X.formatters.e=r=>r==null?"undefined":bv(r.stack)??bv(r.message)??r.toString();function yT(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function lo(r){let e=yT(`${r}:trace`);return X.enabled(`${r}:trace`)&&X.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=X(`${r}:trace`)),Object.assign(X(r),{error:X(`${r}:error`),trace:e,newScope:t=>lo(`${r}:${t}`)})}function bv(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var ST=vn(rg(),1);var Qt=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},yu=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},Ss=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},wu=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},bu=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},xu=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},fa=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var er;(function(r){let e;(function(o){o.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(o){o[o.EOL=0]="EOL"})(t||(t={})),(function(o){o.codec=()=>ci(t)})(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=Ke((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.value!=null&&(s.uint32(10),s.bytes(o.value)),o.signatureV1!=null&&(s.uint32(18),s.bytes(o.signatureV1)),o.validityType!=null&&(s.uint32(24),r.ValidityType.codec().encode(o.validityType,s)),o.validity!=null&&(s.uint32(34),s.bytes(o.validity)),o.sequence!=null&&(s.uint32(40),s.uint64(o.sequence)),o.ttl!=null&&(s.uint32(48),s.uint64(o.ttl)),o.pubKey!=null&&(s.uint32(58),s.bytes(o.pubKey)),o.signatureV2!=null&&(s.uint32(66),s.bytes(o.signatureV2)),o.data!=null&&(s.uint32(74),s.bytes(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Ve(o,r.codec()),r.decode=(o,s)=>$e(o,r.codec(),s)})(er||(er={}));var vu=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var wT=lo("ipns:utils"),xv=T("/ipns/");var bT=0,xT=18;function vv(r){let e;if(r.pubKey!=null)try{e=an(r.pubKey)}catch(t){throw wT.error(t),t}if(e!=null)return e}function Ev(r){let e=T("ipns-signature:");return ye([e,r])}function da(r){return"signatureV1"in r?er.encode({value:T(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:T(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):er.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function gn(r){let e=er.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw new Qt("Missing data or signatureV2");let t=Sv(e.data),n=vT(t.Value),o=B(t.Validity);if(e.value!=null&&e.signatureV1!=null)return ET(e),{value:n,validityType:er.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:er.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function ha(r){return ye([xv,r.bytes])}function As(r){let e=Xe(r.slice(xv.length));if(!Eu(e,bT)&&!Eu(e,xT))throw new vu("Multihash in IPNS key was not identity or sha2-256");return e}function Sv(r){let e=St(r);if(e.ValidityType===0)e.ValidityType=er.ValidityType.EOL;else throw new Ss("The validity type is unsupported");return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e}function vT(r){let e=B(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${V.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${V.parse(e).toV1().toString()}`}catch{}throw new bu("Value must be a valid content path starting with /")}function ET(r){if(r.data==null)throw new xu("Record data is missing");let e=Sv(r.data);if(!W(e.Value,r.value??new Uint8Array(0)))throw new Qt('Field "value" did not match between protobuf and CBOR');if(!W(e.Validity,r.validity??new Uint8Array(0)))throw new Qt('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new Qt('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new Qt('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new Qt('Field "ttl" did not match between protobuf and CBOR')}function Eu(r,e){return r.code===e}var z9=lo("ipns"),G9=300*1e9,AT="/ipns/",W9=AT.length;var Av=vn(rg(),1);var Su=lo("ipns:validator"),IT=1024*10;async function CT(r,e){let t=gn(e),n;try{let o=Ev(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw Su.error("record signature verification failed"),new Qt("Record signature verification failed");if(t.validityType===er.ValidityType.EOL){if(Av.default.fromString(t.validity).toDate().getTime()<Date.now())throw Su.error("record has expired"),new yu("record has expired")}else if(t.validityType!=null)throw Su.error("the validity type is unsupported"),new Ss("The validity type is unsupported");Su("ipns record for %s is valid",t.value)}async function Iv(r,e){if(e.byteLength>IT)throw new wu("The record is too large");let t=As(r),n;Eu(t,0)&&(n=jo(t));let o=gn(e),s=vv(o)??n;if(s==null)throw new fa("Could not extract public key from IPNS record or routing key");let i=ha(s.toMultihash());if(!W(i,r))throw new fa("Embedded public key did not match routing key");await CT(s,e)}var Au=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*pa(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),o="";for await(let s of r){if(typeof s=="string"&&(s=new TextEncoder().encode(s)),ko(s)&&(s=s.subarray()),o+=n.decode(s,{stream:!0}),o.length>(e?.maxMessageLength??o.length))throw new Au("Incoming message too long");let i=o.split(t);o=i.pop()??"";for(let a=0;a<i.length;a++)yield JSON.parse(i[a])}o+=n.decode(),o!==""&&(yield JSON.parse(o))}var Is=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},tr=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function _T(r){return r[Symbol.asyncIterator]!=null}function TT(r){if(_T(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var Cv=TT;var _v=T("/ipns/");function Tv(r){return W(r.subarray(0,_v.byteLength),_v)}var Iu=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*il(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!Tv(e))return;let o=As(e),s=V.createV1(114,o),i=gn(t);await this.client.putIPNS(s,i,n)}async get(e,t){if(!Tv(e))throw new gr("Not found");let n=As(e),o=V.createV1(114,n);try{let s=await this.client.getIPNS(o,t);return da(s)}catch(s){throw s.name==="BadResponseError"?new gr("Not found"):s}}},Cu=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await Cv(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new gr("Not found")}async*getClosestPeers(e,t={}){}};var We=$m("delegated-routing-v1-http-api-client"),_u={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},Tu=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new ro({concurrency:t.concurrentRequests??_u.concurrentRequests}),this.inFlightRequests=new Map,this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??_u.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new Iu(this),this.peerRouting=new Cu(this),this.cacheName=t.cacheName??_u.cacheName,this.cacheTTL=t.cacheTTL??_u.cacheTTL}get[Jx](){return this.contentRouting}get[Qx](){return this.peerRouting}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&We("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){We("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=me([this.shutDownController.signal,n,t.signal]);let s=le(),i=le();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.clientUrl}routing/v1/providers/${e.toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(l==null)throw new tr("No response received");if(!l.ok)throw l.status===404?new gr("No matching records found"):l.status===422?new Is("Request does not conform to schema or semantic constraints"):new tr(`Unexpected status code: ${l.status}`);if(l.body==null)throw new tr("Routing response had no body");let u=l.headers.get("Content-Type");if(u==null)throw new tr("No Content-Type header received");if(u?.startsWith("application/json")){let f=await l.json();for(let d of f.Providers){let h=this.#e(d);h!=null&&(yield h)}}else if(u.includes("application/x-ndjson"))for await(let f of pa(gu(l.body))){let d=this.#e(f);d!=null&&(yield d)}else throw new tr(`Unsupported Content-Type: ${u}`)}finally{o.clear(),i.resolve(),We("getProviders finished: %c",e)}}async*getPeers(e,t={}){We("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=me([this.shutDownController.signal,n,t.signal]);let s=le(),i=le();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=new URL(`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:o},l=await this.#r(a.toString(),c);if(l.status===404)throw new gr("No matching records found");if(l.status===422)throw new Is("Request does not conform to schema or semantic constraints");if(l.body==null)throw new tr("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let f=await l.json();for(let d of f.Peers){let h=this.#e(d);h!=null&&(yield h)}}else for await(let f of pa(gu(l.body))){let d=this.#e(f);d!=null&&(yield d)}}catch(a){We.error("getPeers errored:",a)}finally{o.clear(),i.resolve(),We("getPeers finished: %c",e)}}async getIPNS(e,t={}){We("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),o=me([this.shutDownController.signal,n,t.signal]);let s=le(),i=le();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.clientUrl}routing/v1/ipns/${e}`;try{await s.promise;let c={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o},l=await this.#r(a,c);if(We("getIPNS GET %s %d",a,l.status),l.status===404)throw new gr("No matching records found");if(l.status===422)throw new Is("Request does not conform to schema or semantic constraints");if(l.body==null)throw new tr("GET ipns response had no body");let u=await l.arrayBuffer(),f=new Uint8Array(u,0,u.byteLength);return t.validate!==!1&&await Iv(ha(e.multihash),f),gn(f)}catch(c){throw We.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),i.resolve(),We("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){We("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=me([this.shutDownController.signal,o,n.signal]);let i=le(),a=le();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e}`;try{await i.promise;let l=da(t),u={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:s},f=await this.#r(c,u);if(We("putIPNS PUT %s %d",c,f.status),f.status!==200)throw new tr("PUT ipns response had status other than 200")}catch(l){throw We.error("putIPNS PUT %s error:",c,l.stack),l}finally{s.clear(),a.resolve(),We("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(ua)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:nv(e.ID),Addrs:n,Protocols:t}}catch(t){We.error("could not conform record to peer schema",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let o=t?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&e.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&e.searchParams.set("filter-protocols",o)}}async#r(e,t){let n=t.method??"GET",o=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return We("returning cached response for %s",o),c;await this.cache?.delete(e)}}let s=this.inFlightRequests.get(o);if(s!=null){let c=await s;return We("deduplicating outgoing request for %s",o),c.clone()}let i=fetch(e,t).then(async c=>{if(this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,u=new Headers(c.headers);u.set("x-cache-expires",l.toString());let f=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:u});await this.cache.put(e,f)}return c}).finally(()=>{this.inFlightRequests.delete(o)});return this.inFlightRequests.set(o,i),await i}};function kv(r,e={}){return new Tu(new URL(r),e)}var Pv="[a-fA-F\\d:]",yn=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Pv})|(?<=${Pv})(?=\\s|$))`:"",rr="(?: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}",Be="[a-fA-F\\d]{1,4}",ku=`
4
5
  (?:
5
- (?:${Se}:){7}(?:${Se}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
6
- (?:${Se}:){6}(?:${fr}|:${Se}|:)| // 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
7
- (?:${Se}:){5}(?::${fr}|(?::${Se}){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
8
- (?:${Se}:){4}(?:(?::${Se}){0,1}:${fr}|(?::${Se}){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
9
- (?:${Se}:){3}(?:(?::${Se}){0,2}:${fr}|(?::${Se}){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
10
- (?:${Se}:){2}(?:(?::${Se}){0,3}:${fr}|(?::${Se}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
11
- (?:${Se}:){1}(?:(?::${Se}){0,4}:${fr}|(?::${Se}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
12
- (?::(?:(?::${Se}){0,5}:${fr}|(?::${Se}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
6
+ (?:${Be}:){7}(?:${Be}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
7
+ (?:${Be}:){6}(?:${rr}|:${Be}|:)| // 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
8
+ (?:${Be}:){5}(?::${rr}|(?::${Be}){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
9
+ (?:${Be}:){4}(?:(?::${Be}){0,1}:${rr}|(?::${Be}){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
10
+ (?:${Be}:){3}(?:(?::${Be}){0,2}:${rr}|(?::${Be}){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
11
+ (?:${Be}:){2}(?:(?::${Be}){0,3}:${rr}|(?::${Be}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
12
+ (?:${Be}:){1}(?:(?::${Be}){0,4}:${rr}|(?::${Be}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
13
+ (?::(?:(?::${Be}){0,5}:${rr}|(?::${Be}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
13
14
  )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
14
- `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),ZI=new RegExp(`(?:^${fr}$)|(?:^${gu}$)`),XI=new RegExp(`^${fr}$`),JI=new RegExp(`^${gu}$`),Bm=r=>r&&r.exact?ZI:new RegExp(`(?:${Tn(r)}${fr}${Tn(r)})|(?:${Tn(r)}${gu}${Tn(r)})`,"g");Bm.v4=r=>r&&r.exact?XI:new RegExp(`${Tn(r)}${fr}${Tn(r)}`,"g");Bm.v6=r=>r&&r.exact?JI:new RegExp(`${Tn(r)}${gu}${Tn(r)}`,"g");var Pm=Bm;function Dm(r){let e=(...t)=>r(...t);return Object.defineProperty(e,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),e}function Mx(){return!1}var{toString:QI}=Object.prototype;function Lm(r){return QI.call(r)==="[object RegExp]"}var Ux={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function Nm(r,e={}){if(!Lm(r))throw new TypeError("Expected a RegExp instance");let t=Object.keys(Ux).map(o=>(typeof e[o]=="boolean"?e[o]:r[o])?Ux[o]:"").join(""),n=new RegExp(e.source||r.source,t);return n.lastIndex=typeof e.lastIndex=="number"?e.lastIndex:r.lastIndex,n}function Rm(r,e,{timeout:t}={}){try{return Dm(()=>Nm(r).test(e),{timeout:t})()}catch(n){if(Mx(n))return!1;throw n}}var eC=15,tC=45,Fx={timeout:400};function Om(r){return r.length>tC?!1:Rm(Pm.v6({exact:!0}),r,Fx)}function Vx(r){return r.length>eC?!1:Rm(Pm.v4({exact:!0}),r,Fx)}var Kx={http:"80",https:"443",ws:"80",wss:"443"},rC=["http","https","ws","wss"];function $x(r,e){e=e??{};let t=e.defaultDnsType??"dns",{scheme:n,hostname:o,port:s,path:i}=nC(r),a=[oC(o,t),sC(s,n),iC(n)];i!=null&&a.push(aC(i));let c="/"+a.filter(l=>!!l).reduce((l,u)=>l.concat(u),[]).join("/");return X(c)}function nC(r){let[e]=r.split(":");rC.includes(e)||(r="http"+r.substring(e.length));let{protocol:t,hostname:n,port:o,pathname:s,search:i}=new URL(r);if(o==null||o===""){let c=cC(e);c!=null&&(o=c),c==null&&t==="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:e,hostname:n,port:o,path:a}}function oC(r,e){if(!(r==null||r==="")){if(Vx(r))return["ip4",r];if(Om(r))return["ip6",r];if(r[0]==="["){let t=r.substring(1,r.length-1);if(Om(t))return["ip6",t]}return[e,r]}}function sC(r,e){if(!(r==null||r===""))return e==="udp"?["udp",r]:["tcp",r]}function iC(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function aC(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function cC(r){if(!(r==null||r===""||Kx[r]==null))return Kx[r]}var lC=["https://trustless-gateway.link","https://4everland.io"],uC=2336;function fC(r){return r=r.toString(),{id:Jn(H.createV1(uC,Ze.digest(T(r)))),multiaddrs:[$x(r)]}}var Mm=class{gateways;shuffle;constructor(e={}){this.gateways=(e.gateways??lC).map(t=>fC(t)),this.shuffle=e.shuffle??!0}async*findProviders(e,t){yield*(this.shuffle?this.gateways.toSorted(()=>Math.random()>.5?1:-1):this.gateways).map(n=>({...n,protocols:["transport-ipfs-gateway-http"]}))}};function Um(r={}){return new Mm(r)}var Fm=class{libp2p;constructor(e){this.libp2p=e}async provide(e,t){await this.libp2p.contentRouting.provide(e,t)}async cancelReprovide(e,t){await this.libp2p.contentRouting.cancelReprovide(e,t)}async*findProviders(e,t){yield*this.libp2p.contentRouting.findProviders(e,t)}async put(e,t,n){await this.libp2p.contentRouting.put(e,t,n)}async get(e,t){return this.libp2p.contentRouting.get(e,t)}async findPeer(e,t){return this.libp2p.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t){yield*this.libp2p.peerRouting.getClosestPeers(e,t)}};function Vm(r){return new Fm(r)}var ha=class extends Hr{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(ke.encode(e.multihash.bytes),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(ke.encode(e.multihash.bytes));if(n==null)throw new Ft;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(ke.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(ke.encode(e.multihash.bytes))}async*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:H.createV1(Xs,wt(ke.decode(t))),block:n},e?.signal?.throwIfAborted()}};var D7=Et("blockstore:core:tiered");var Hx="SHARDING";function hC(r){return r[Symbol.asyncIterator]!=null}function pC(r){if(hC(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var pa=pC;function mC(r){return r[Symbol.asyncIterator]!=null}function gC(r,e){return mC(r)?async function*(){yield*(await pa(r)).sort(e)}():function*(){yield*pa(r).sort(e)}()}var yu=gC;var jr=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Ys(this.putMany(e,n)),e=[],await Ys(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=or(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>or(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>yu(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=or(n,()=>o++>=s)}return e.limit!=null&&(n=ac(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=or(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>or(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>yu(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=or(n,()=>s++>=o)}return e.limit!=null&&(n=ac(n,e.limit)),n}};var mo=class extends jr{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Ft;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new me(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new me(n),t?.signal?.throwIfAborted()}};var d9=new me(Hx);var I9=Et("datastore:core:tiered");function Ds(r){if(typeof r!="object"||r===null)return!1;let e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}var{hasOwnProperty:Gx}=Object.prototype,{propertyIsEnumerable:yC}=Object,Ls=(r,e,t)=>{Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})},wC=void 0,zx={concatArrays:!1,ignoreUndefined:!1},wu=r=>{let e=[];for(let t in r)Gx.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)yC.call(r,n)&&e.push(n)}return e};function Ns(r){return Array.isArray(r)?bC(r):Ds(r)?xC(r):r}function bC(r){let e=r.slice(0,0);return wu(r).forEach(t=>{Ls(e,t,Ns(r[t]))}),e}function xC(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return wu(r).forEach(t=>{Ls(e,t,Ns(r[t]))}),e}var Wx=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?Ls(r,o,Km(r[o],e[o],n)):Ls(r,o,Ns(e[o])))}),r),vC=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)Gx.call(s,a)&&(i.push(String(a)),s===r?Ls(n,o++,s[a]):Ls(n,o++,Ns(s[a])));n=Wx(n,s,wu(s).filter(a=>!i.includes(a)),t)}),n};function Km(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?vC(r,e,t):!Ds(e)||!Ds(r)?Ns(e):Wx(r,e,wu(e),t)}function Rs(...r){let e=Km(Ns(zx),this!==wC&&this||{},zx),t={_:{}};for(let n of r)if(n!==void 0){if(!Ds(n))throw new TypeError("`"+n+"` is not an Option Object");t=Km(t,{_:n},e)}return t._}var $m=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let s=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[At.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(X(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=Wc()),this.dns)}},go=new $m;var EC={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:go}},transportManager:{faultTolerance:Ln.FATAL_ALL}};async function jx(r){let e=Rs(EC,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new B("Private network is enforced, but no protector was provided");return e}var ma;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:be(0),payloadType:be(0),payload:be(0),signature:be(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Re(t,r.codec()),r.decode=(t,n)=>Ne(t,r.codec(),n)})(ma||(ma={}));var bu=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Os=class r{static createFromProtobuf=e=>{let t=ma.decode(e),n=bn(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=Yx(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new bu("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=ma.encode({publicKey:Dt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:Z(this.marshal(),e.marshal())}async validate(e,t){let n=Yx(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},Yx=(r,e,t)=>{let n=T(r),o=yr(n.byteLength),s=yr(e.length),i=yr(t.length);return new ee(o,n,s,e,i,t)};function Zx(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var Xx="libp2p-peer-record",Jx=Uint8Array.from([3,1]);var ga;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Oe((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:be(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(u&7);break}}}return c})),o),n.encode=s=>Re(s,n.codec()),n.decode=(s,i)=>Ne(s,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Oe((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:be(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new Fn('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>Re(n,r.codec()),r.decode=(n,o)=>Ne(n,r.codec(),o)})(ga||(ga={}));var yo=class r{static createFromProtobuf=e=>{let t=ga.decode(e),n=us(wt(t.peerId)),o=(t.addresses??[]).map(i=>X(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Xx;static CODEC=Jx;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=ga.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Zx(this.multiaddrs,e.multiaddrs))}};var Yr;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:be(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Re(i,o.codec()),o.decode=(i,a)=>Ne(i,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Oe((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),vu.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=vu.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Re(i,o.codec()),o.decode=(i,a)=>Ne(i,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Oe((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),xu.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.updated!=null&&(s.uint32(64),s.uint64Number(o.updated)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new Fn('Decode error - map field "addresses" had too many elements');a.addresses.push(xu.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new Fn('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new ii('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new ii('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Re(o,r.codec()),r.decode=(o,s)=>Ne(o,r.codec(),s)})(Yr||(Yr={}));var xu;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),t.observed!=null&&(n.uint32(24),n.uint64Number(t.observed)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={multiaddr:be(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.multiaddr=t.bytes();break}case 2:{s.isCertified=t.bool();break}case 3:{s.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Re(t,r.codec()),r.decode=(t,n)=>Ne(t,r.codec(),n)})(xu||(xu={}));var vu;(function(r){let e;r.codec=()=>(e==null&&(e=Oe((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.value=t.uint32();break}case 2:{s.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Re(t,r.codec()),r.decode=(t,n)=>Ne(t,r.codec(),n)})(vu||(vu={}));function AC(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=bn(e.publicKey,t);return Yh(n)}function Qx(r,e,t){let n=Yr.decode(e);return Ms(r,n,t)}function Ms(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:AC(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:X(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function ev(r,e){return SC(r.addresses,e.addresses)&&_C(r.protocols,e.protocols)&&IC(r.publicKey,e.publicKey)&&CC(r.peerRecordEnvelope,e.peerRecordEnvelope)&&kC(r.metadata,e.metadata)&&TC(r.tags,e.tags)}function SC(r,e){return rv(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!Z(t.multiaddr,n.multiaddr)))}function _C(r,e){return rv(r,e,(t,n)=>t===n)}function IC(r,e){return tv(r,e)}function CC(r,e){return tv(r,e)}function kC(r,e){return nv(r,e,(t,n)=>Z(t,n))}function TC(r,e){return nv(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function tv(r,e){return r==null&&e==null?!0:r!=null&&e!=null?Z(r,e):!1}function rv(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function nv(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var Hm="/peers/";function ya(r){if(!hr(r)||r.type==null)throw new B("Invalid PeerId");let e=r.toCID().toString();return new me(`${Hm}${e}`)}async function ov(r,e,t,n,o){let s=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=X(i.multiaddr)),!Cn(i.multiaddr))throw new B("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=s.get(c);l!=null?i.isCertified=l.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getPeerId();return r.equals(c)&&(a=a.decapsulate(X(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Au(r,e,t,n){if(e==null)throw new B("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new B("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new B("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Eu(d,{validate:sv})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Eu(d,{validate:iv,map:av})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,p]of d)p==null?a.delete(h):a.set(h,p);a=Eu([...a.entries()],{validate:sv})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[p,m]of d)m==null?h.delete(p):h.set(p,m);c=Eu([...h.entries()],{validate:iv,map:av})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Dt(o.id.publicKey):e.publicKey!=null?u=Dt(e.publicKey):r.publicKey!=null&&(u=Dt(r.publicKey));let f={addresses:await ov(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>Z(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function Eu(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function sv(r,e){if(typeof r!="string")throw new B("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new B("Metadata value must be a Uint8Array")}function iv(r,e){if(typeof r!="string")throw new B("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new B("Tag value must be an integer");if(e.value<0||e.value>100)throw new B("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new B("Tag ttl must be an integer");if(e.ttl<0)throw new B("Tag ttl must be between greater than 0")}}function av(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function cv(r){let e=r.toString().split("/")[2],t=H.parse(e,ke);return Jn(t)}function qm(r,e,t){let n=cv(r);return Qx(n,e,t)}function BC(r,e){return{prefix:Hm,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(qm(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(qm(n.key,n.value,e),qm(o.key,o.value,e)))}}var Su=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=ep({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:Xi({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(ya(e),t)}async load(e,t){let n=ya(e),o=await this.datastore.get(n,t),s=Yr.decode(o);if(this.#r(e,s))throw await this.datastore.delete(n,t),new Ie;return Ms(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await Au(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await Au(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await Au(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(BC(e??{},this.maxAddressAge),e)){let o=cv(t);if(o.equals(this.peerId))continue;let s=Yr.decode(n);if(this.#r(o,s)){await this.datastore.delete(t,e);continue}yield Ms(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=ya(e),o=await this.datastore.get(n,t),s=Yr.decode(o);if(this.#r(e,s))throw await this.datastore.delete(n,t),new Ie;return{peerPB:s,peer:Ms(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,o){t.updated=Date.now();let s=Yr.encode(t);return await this.datastore.put(ya(e),s,o),{peer:Ms(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!ev(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var zm=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Su(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return pa(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=hr(t)?t:hr(t?.expectedPeer)?t.expectedPeer:void 0,s=hr(t)||t===void 0?n:t,i=await Os.openAndCertify(e,yo.DOMAIN,s),a=Jn(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=yo.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=Os.createFromProtobuf(l.peerRecordEnvelope),f=yo.createFromProtobuf(u.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},s),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function lv(r,e={}){return new zm(r,e)}var uv=864e13;var PC=448,Gm=449,DC=53,LC=54,NC=55,RC=56,_u=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=Je({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=this.findHost(e);for(let n of this.mappings.values())if(n.domain===t)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=Sr(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?uv-Date.now():0,lastVerified:o?uv-Date.now():void 0})})}remove(e){let t=this.findHost(e),n=!1;for(let[o,s]of this.mappings.entries())s.domain===t&&(this.log("removing %s to %s DNS mapping %e",o,s.domain,new Error("where")),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let s=e[n].multiaddr.stringTuples(),i=s[0][1];if(i!=null)for(let[a,c]of this.mappings.entries()){if(i!==a)continue;this.maybeAddSNITuple(s,c.domain)&&(e.splice(n,1),n--,t.push({multiaddr:X(`/${s.map(u=>[Wl(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(let n=0;n<e.length;n++)if(e[n][0]===PC&&e[n+1]?.[0]!==Gm)return e.splice(n+1,0,[Gm,t]),!0;return!1}confirm(e,t){let n=this.findHost(e),o=!1;for(let[s,i]of this.mappings.entries())i.domain===n&&(this.log("marking %s to %s DNS mapping as verified",s,i.domain),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){let n=this.findHost(e),o=!1;for(let[s,i]of this.mappings.entries())i.domain===n&&(this.log("removing verification of %s to %s DNS mapping",s,i.domain),o=o||i.verified,i.verified=!1,i.expires=Date.now()+t);return o}findHost(e){for(let t of e.stringTuples())if(t[0]===Gm||t[0]===DC||t[0]===LC||t[0]===NC||t[0]===RC)return t[1]}};var Wm=4,jm=41,Ym=6,OC=273,Iu=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=Je({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=e.stringTuples();for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t[0][1])return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:sr(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=e.stringTuples(),n=t[0][1]??"",o=t[1][0]===Ym?"tcp":"udp",s=parseInt(t[1][1]??"0"),i=!1;for(let[a,c]of this.mappings.entries()){for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===n&&u.externalPort===s&&u.protocol===o&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,s,o),i=i||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return i}getAll(e){let t=[];for(let{multiaddr:n}of e){let o=n.stringTuples(),s;if((o[0][0]===Wm||o[0][0]===jm)&&o[1][0]===Ym?s=`${o[0][1]}-${o[1][1]}-tcp`:(o[0][0]===Wm||o[0][0]===jm)&&o[1][0]===OC&&(s=`${o[0][1]}-${o[1][1]}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)o[0][0]=a.externalFamily===4?Wm:jm,o[0][1]=a.externalIp,o[1][1]=`${a.externalPort}`,t.push({multiaddr:X(`/${o.map(c=>[Wl(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}confirm(e,t){let o=e.stringTuples()[0][1],s=!1;for(let i of this.mappings.values())for(let a of i)a.externalIp===o&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=e.stringTuples(),o=n[0][1]??"",s=n[1][0]===Ym?"tcp":"udp",i=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===o&&u.externalPort===i&&u.protocol===s&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,o,i,s),a=a||u.verified,u.verified=!1,u.expires=Date.now()+t)}return a}};function fv(r){try{for(let{code:e,value:t}of r.getComponents())if(e!==42&&t!=null){if(e===4)return t.startsWith("169.254.");if(e===41)return t.toLowerCase().startsWith("fe80")}}catch{}return!1}function Cu(r){try{for(let{code:e}of r.getComponents())if(e!==42)return e===4||e===41}catch{}return!1}function wo(r){try{if(!Cu(r))return!1;let[[,e]]=r.stringTuples();return e==null?!1:Sr(e)??!1}catch{}return!0}var MC={maxObservedAddresses:10},ku=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Je({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??MC.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(wo(e)||fv(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:X(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var UC=[4,41,53,54,55,56];function Zm(r){try{for(let{code:e}of r.getComponents())if(e!==42)return UC.includes(e)}catch{}return!1}var FC={maxObservedAddresses:10},Tu=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=Je({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??FC.maxObservedAddresses}get(e,t){if(wo(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!Zm(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(Zm(e)){let t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}};var dv=6e4,hv={maxObservedAddresses:10,addressVerificationTTL:dv*10,addressVerificationRetry:dv*5},VC=r=>r;function Xm(r,e){let t=r.getPeerId();return t!=null&&Rt(t).equals(e)&&(r=r.decapsulate(X(`/p2p/${e.toString()}`))),r}var Bu=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new ku(e,t),this.dnsMappings=new _u(e,t),this.ipMappings=new Iu(e,t),this.transportAddresses=new Tu(e,t),this.announceFilter=t.announceFilter??VC,this.observedAddressFilter=no(1024),this.addressVerificationTTL=t.addressVerificationTTL??hv.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??hv.addressVerificationRetry,this._updatePeerStoreAddresses=js(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>X(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>X(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>X(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=e.stringTuples(),n=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=Xm(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=Xm(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Xm(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=X(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(X(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${sr(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(X(`/ip${sr(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;let t=e.toOptions();if(t.family===6||t.host==="127.0.0.1"||Sr(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>po.exactMatch(s)||aa.exactMatch(s),s=>ia.exactMatch(s),s=>gx.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>u.toOptions().family===4&&s(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>l.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.transport),!0}return!1}};var pv;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(pv||(pv={}));var Pu=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Du=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Us=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},wa=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},Lu=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},Nu=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Ru=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},ba=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Ou=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},Mu=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},Uu=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Fu=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Vu=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},bo=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},xo=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Ku=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},$u=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var Jm=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=vn())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Ga(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},$C=["metrics","connectionProtector","dns"],HC=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function mv(r={}){let e=new Jm(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!HC.includes(o)){let i=e.components[o];if(i==null&&!$C.includes(o))throw new Pu(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function gv(r){let e={};for(let t of Object.values(r.components))for(let n of qC(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of zC(t))if(e[n]!==!0)throw new Du(`Service "${GC(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function qC(r){return Array.isArray(r?.[Nn])?r[Nn]:[]}function zC(r){return Array.isArray(r?.[fd])?r[fd]:[]}function GC(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var WC=4,jC=41;function yv(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{if(po.matches(e))return!1;let t=e.stringTuples();return t[0][0]===WC||t[0][0]===jC?!!Sr(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var wv=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},YC=new WeakMap;function ZC({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(wv());let s,i,a,c=r??clearTimeout,l=()=>{c(s),a(wv())},u=()=>{o&&o.removeEventListener("abort",l)},f=new Promise((d,h)=>{i=()=>{u(),d(n)},a=h,s=(e??setTimeout)(i,t)});return o&&o.addEventListener("abort",l,{once:!0}),YC.set(f,()=>{c(s),s=null,i()}),f}}var XC=ZC(),bv=XC;var Hu=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Qm}async consume(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(o,i.consumedPoints,this.blockDuration)),new ja("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await bv(a)}return i}penalty(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let o=this.getKey(e),s=this._getKeySecDuration(n),i=this.memoryStorage.incrby(o,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,t,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},Qm=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let o=this.storage.get(e);if(o!=null){let s=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||s>0?(o.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let o=n*1e3,s=this.storage.get(e);s!=null&&clearTimeout(s.timeoutId);let i={value:t,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,i),o>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:i.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function qu(r){if(hr(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getPeerId();t=n==null?void 0:Rt(n),e.forEach(o=>{if(!Cn(o))throw new an("Invalid multiaddr");let s=o.getPeerId();if(s==null){if(t!=null)throw new B("Multiaddrs must all have the same peer id or have no peer id")}else{let i=Rt(s);if(t?.equals(i)!==!0)throw new B("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!dx.exactMatch(n)),{peerId:t,multiaddrs:e}}var JC=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function xv(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??JC;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function xa(r){try{let e;typeof r=="string"?e=X(r):e=r;let t=new Set([...e.getComponents().map(n=>n.name)]);if(!t.has("ipcidr")){let o=t.has("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(o)}return hm(e)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var zu=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>xa(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new Ot;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let u=await this.peerStore.get(l);o.set(l,[...u.tags.values()].reduce((f,d)=>f+d.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>u.contains(c.remoteAddr.nodeAddress().address))||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await xv(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var vv="last-dial-failure",Ev="last-dial-success";var Av=100,Gu=50;var Wu=class extends zt{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function Sv(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function eg(r){if(!Cu(r))return!1;let{address:e}=r.nodeAddress();return Sv(e)}function QC(r,e){let t=ia.exactMatch(r.multiaddr),n=ia.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=aa.exactMatch(r.multiaddr),s=aa.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=po.exactMatch(r.multiaddr),a=po.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Sm.exactMatch(r.multiaddr),l=Sm.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=Em.exactMatch(r.multiaddr),f=Em.exactMatch(e.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Am.exactMatch(r.multiaddr),h=Am.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function ek(r,e){let t=eg(r.multiaddr),n=eg(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function tk(r,e){let t=wo(r.multiaddr),n=wo(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function rk(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function nk(r,e){let t=ca.exactMatch(r.multiaddr),n=ca.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function _v(r){return r.sort(QC).sort(rk).sort(nk).sort(tk).sort(ek)}async function tg(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new $u("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await tg(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var va={maxParallelDials:Gu,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:go}},ju=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??va.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??va.maxDialQueueLength,this.dialTimeout=t.dialTimeout??va.dialTimeout,this.connections=t.connections??new Ot,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??va.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new Wu({concurrency:t.maxParallelDials??va.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{n.detail?.name!==mt.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=qu(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0||a.limits!=null?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s?.status==="open")return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new j("dial-queue:already-connected")),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return t.onProgress?.(new j("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Bo("Dial queue is full");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),t.onProgress?.(new j("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new j("dial-queue:start-dial"));let c=de([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:t.priority??sg,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let u=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new j("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Bo("Peer had more than maxPeerAddrsToDial");a++;try{let p=await this.components.transportManager.dial(h.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(p.remotePeer,{multiaddrs:[p.remoteAddr],metadata:{[Ev]:T(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",n,m)}return p}catch(p){if(this.log.error("dial failed to %a",h.multiaddr,p),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[vv]:T(Date.now().toString())}})}catch(m){this.log.error("could not update last dial failure key for %p",n,m)}if(t.aborted)throw new Ha(p.message);l.push(p)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:X(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Bo("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new ba("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);o.push(...f.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await tg(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new Uu("The dial request has no valid addresses");let l=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||l.push(f);let u=this.addressSorter==null?_v(l):l.sort(this.addressSorter);if(u.length===0)throw new ba("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!ca.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var Dv=nn(Bv(),1);var sk=Object.prototype.toString,ik=r=>sk.call(r)==="[object Error]",ak=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function ig(r){return r&&ik(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:ak.has(r.message):!1}var ag=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},Pv=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function cg(r,e){return new Promise((t,n)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let o=Dv.default.operation(e),s=()=>{o.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",s,{once:!0});let i=()=>{e.signal?.removeEventListener("abort",s),o.stop()};o.attempt(async a=>{try{let c=await r(a);i(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof ag)throw c.originalError;if(c instanceof TypeError&&!ig(c))throw c;if(Pv(c,a,e),await e.shouldRetry(c)||(o.stop(),n(c)),await e.onFailedAttempt(c),!o.retry(c))throw o.mainError()}catch(l){Pv(l,a,e),i(),n(l)}}})})}var Yu=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Lo({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);Lv(t)&&(this.queue.has(e)||this.queue.add(async n=>{await cg(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(ud)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>Lv(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function Lv(r){for(let e of r.tags.keys())if(e.startsWith(ud))return!0;return!1}var sg=50,lg={maxConnections:Av,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},Zu=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??lg.maxConnections,this.maxConnections<1)throw new B("Connection Manager maxConnections must be greater than 0");this.connections=new Ot,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>xa(n)),this.deny=(t.deny??[]).map(n=>xa(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??lg.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Hu({points:t.inboundConnectionThreshold??lg.inboundConnectionThreshold,duration:1}),this.connectionPruner=new zu({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>X(n))}),this.dialQueue=new ju(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??Gu,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:go},connections:this.connections}),this.reconnectQueue=new Yu({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await pr(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await mr(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new B("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.length===0&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Cr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n}=qu(e);if(this.peerId.equals(n))throw new To("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p",n),t.onProgress?.(new j("dial-queue:already-connected")),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??sg});if(o.status!=="open")throw new ko("Remote closed connection during opening");let s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)if(a.id===o.id&&(i=!0),t.force!==!0&&a.id!==o.id&&a.remoteAddr.equals(o.remoteAddr))return o.abort(new an("Duplicate multiaddr connection")),a;return i||s.push(o),o}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>o.contains(e.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>o.contains(e.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>X(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Fs=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),o=e-this.movingAverage,s=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var uk=1.2,fk=2,dk=5e3,hk=6e4,pk=5e3,Xu=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??pk;this.success=new Fs(t),this.failure=new Fs(t),this.next=new Fs(t),this.failureMultiplier=e.failureMultiplier??fk,this.timeoutMultiplier=e.timeoutMultiplier??uk,this.minTimeout=e.minTimeout??dk,this.maxTimeout=e.maxTimeout??hk,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),o=de([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var Ju=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Qu(r,e){let t=ic();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new ee;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await Le(n.next(),i?.signal);return c===!0?null:l}for(;o.byteLength<i.bytes;){let{value:c,done:l}=await Le(n.next(),i?.signal);if(l===!0)throw new Ju("unexpected end of input");o.append(c)}let a=o.sublist(0,i.bytes);return o.consume(i.bytes),a},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var mk=1e4,gk="1.0.0",yk="ping",wk="ipfs",Nv=32,bk=!0,ef=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??wk}/${yk}/${gk}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??mk,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??bk,this.timeout=new Xu({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Nn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=Qu(o);t=Date.now(),await Promise.all([s.write(Jt(Nv),{signal:n}),s.read({bytes:Nv,signal:n})]),e.rtt=Date.now()-t,await s.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var tf=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:O(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:O(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new Us("No content routers available");let n=this,o=new eo;for await(let s of Bt(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new Us("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Us("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Cr;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Cr;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var rf=globalThis.CustomEvent??Event;async function*ug(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=Q(),a=Q(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let p of r){if(s.length===t&&(i=Q(),await i.promise),u)break;let m={done:!1};s.push(m),p().then(w=>{m.done=!0,m.ok=!0,m.value=w,o.dispatchEvent(new rf("task-complete"))},w=>{m.done=!0,m.err=w,o.dispatchEvent(new rf("task-complete"))})}c=!0,o.dispatchEvent(new rf("task-complete"))}catch(p){l=p,o.dispatchEvent(new rf("task-complete"))}});function f(){return n?s[0]?.done:!!s.find(p=>p.done)}function*d(){for(;s.length>0&&s[0].done;){let p=s[0];if(s.shift(),p.ok)yield p.value;else throw u=!0,i.resolve(),p.err;i.resolve()}}function*h(){for(;f();)for(let p=0;p<s.length;p++)if(s[p].done){let m=s[p];if(s.splice(p,1),p--,m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}for(;;){if(f()||(a=Q(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var nf=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:O(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new wa("No peer routers available");if(e.toString()===this.peerId.toString())throw new Lu("Should not try to find self");let n=this,o=Bt(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new Ie}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new wa("No peer routers available");let n=this,o=no(1024);for await(let s of ug(async function*(){let i=Bt(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var of=class extends tt{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=de([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=Q(),yield(await gr(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=de([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=Jt(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await Le(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var fg=32,dg=64,sf=class{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=Je({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new Nu(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new Ru(`Handler already registered for protocol ${e}`);let o=Rs.bind({ignoreUndefined:!0})({maxInboundStreams:fg,maxOutboundStreams:dg},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new B("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(t,n).then(o=>{for(let s of o.protocols){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t)!==!1&&(a.filter?.remove(t),a.onDisconnect?.(t))}}).catch(o=>{o.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",t,o)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var af=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=Je({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=Je({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ln.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new B("Transport must have a valid tag");if(this.transports.has(t))throw new B(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new Ku(`No transport available for address ${String(e)}`);return t?.onProgress?.(new j("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Cr("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(s=>{t.errors.set(s.toString(),new Ou)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(s)??[];u==null&&(u=[],this.listeners.set(s,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=u.findIndex(d=>d===l);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),wm.matches(c)?t.ipv4.attempts++:bm.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),wm.matches(c)&&t.ipv4.success++,bm.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),t.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Ln.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new Mu(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
15
+ `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),kT=new RegExp(`(?:^${rr}$)|(?:^${ku}$)`),PT=new RegExp(`^${rr}$`),BT=new RegExp(`^${ku}$`),ng=r=>r&&r.exact?kT:new RegExp(`(?:${yn(r)}${rr}${yn(r)})|(?:${yn(r)}${ku}${yn(r)})`,"g");ng.v4=r=>r&&r.exact?PT:new RegExp(`${yn(r)}${rr}${yn(r)}`,"g");ng.v6=r=>r&&r.exact?BT:new RegExp(`${yn(r)}${ku}${yn(r)}`,"g");var og=ng;function sg(r){let e=(...t)=>r(...t);return Object.defineProperty(e,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),e}function Bv(){return!1}var{toString:DT}=Object.prototype;function ig(r){return DT.call(r)==="[object RegExp]"}var Dv={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function ag(r,e={}){if(!ig(r))throw new TypeError("Expected a RegExp instance");let t=Object.keys(Dv).map(o=>(typeof e[o]=="boolean"?e[o]:r[o])?Dv[o]:"").join(""),n=new RegExp(e.source||r.source,t);return n.lastIndex=typeof e.lastIndex=="number"?e.lastIndex:r.lastIndex,n}function cg(r,e,{timeout:t}={}){try{return sg(()=>ag(r).test(e),{timeout:t})()}catch(n){if(Bv(n))return!1;throw n}}var LT=15,NT=45,Lv={timeout:400};function lg(r){return r.length>NT?!1:cg(og.v6({exact:!0}),r,Lv)}function Nv(r){return r.length>LT?!1:cg(og.v4({exact:!0}),r,Lv)}var Rv={http:"80",https:"443",ws:"80",wss:"443"},RT=["http","https","ws","wss"];function Ov(r,e){e=e??{};let t=e.defaultDnsType??"dns",{scheme:n,hostname:o,port:s,path:i}=OT(r),a=[MT(o,t),UT(s,n),FT(n)];i!=null&&a.push($T(i));let c="/"+a.filter(l=>!!l).reduce((l,u)=>l.concat(u),[]).join("/");return oe(c)}function OT(r){let[e]=r.split(":");RT.includes(e)||(r="http"+r.substring(e.length));let{protocol:t,hostname:n,port:o,pathname:s,search:i}=new URL(r);if(o==null||o===""){let c=VT(e);c!=null&&(o=c),c==null&&t==="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:e,hostname:n,port:o,path:a}}function MT(r,e){if(!(r==null||r==="")){if(Nv(r))return["ip4",r];if(lg(r))return["ip6",r];if(r[0]==="["){let t=r.substring(1,r.length-1);if(lg(t))return["ip6",t]}return[e,r]}}function UT(r,e){if(!(r==null||r===""))return e==="udp"?["udp",r]:["tcp",r]}function FT(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function $T(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function VT(r){if(!(r==null||r===""||Rv[r]==null))return Rv[r]}var KT=["https://trustless-gateway.link","https://4everland.io"],HT=2336;function qT(r){return r=r.toString(),{id:Qn(V.createV1(HT,ke.digest(T(r)))),multiaddrs:[Ov(r)]}}var ug=class{gateways;shuffle;constructor(e={}){this.gateways=(e.gateways??KT).map(t=>qT(t)),this.shuffle=e.shuffle??!0}async*findProviders(e,t){yield*(this.shuffle?this.gateways.toSorted(()=>Math.random()>.5?1:-1):this.gateways).map(n=>({...n,protocols:["transport-ipfs-gateway-http"]}))}};function fg(r={}){return new ug(r)}var dg=class{libp2p;constructor(e){this.libp2p=e}async provide(e,t){await this.libp2p.contentRouting.provide(e,t)}async cancelReprovide(e,t){await this.libp2p.contentRouting.cancelReprovide(e,t)}async*findProviders(e,t){yield*this.libp2p.contentRouting.findProviders(e,t)}async put(e,t,n){await this.libp2p.contentRouting.put(e,t,n)}async get(e,t){return this.libp2p.contentRouting.get(e,t)}async findPeer(e,t){return this.libp2p.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t){yield*this.libp2p.peerRouting.getClosestPeers(e,t)}};function hg(r){return new dg(r)}function zT(r){return r[Symbol.asyncIterator]!=null}function GT(r){if(zT(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var uo=GT;function WT(r){return typeof r?.then=="function"}var ma=class extends Or{data;constructor(){super(),this.data=new Map}put(e,t,n){n?.signal?.throwIfAborted();let o;if(t instanceof Uint8Array)o=[t];else{let s=uo(t);if(WT(s))return s.then(i=>this._put(e,i,n));o=s}return this._put(e,o,n)}_put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(ge.encode(e.multihash.bytes),t),e}*get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(ge.encode(e.multihash.bytes));if(n==null)throw new Lt;yield*n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(ge.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(ge.encode(e.multihash.bytes))}*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:V.createV1(zs,Xe(ge.decode(t))),bytes:(async function*(){yield*n})()},e?.signal?.throwIfAborted()}};var kV=ps("blockstore:core:tiered");var Mv="SHARDING";function YT(r){return r[Symbol.asyncIterator]!=null}function ZT(r,e){return YT(r)?(async function*(){yield*(await uo(r)).sort(e)})():(function*(){yield*uo(r).sort(e)})()}var Pu=ZT;var Ur=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await Ui(this.putMany(e,n)),e=[],await Ui(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=Xt(n,s=>s.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Xt(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Pu(o,s),n)),e.offset!=null){let o=0,s=e.offset;n=Xt(n,()=>o++>=s)}return e.limit!=null&&(n=al(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=Xt(n,s=>s.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,s)=>Xt(o,s),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,s)=>Pu(o,s),n)),e.offset!=null){let o=e.offset,s=0;n=Xt(n,()=>s++>=o)}return e.limit!=null&&(n=al(n,e.limit)),n}};var fo=class extends Ur{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Lt;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,o]of this.data.entries())yield{key:new xe(n),value:o},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new xe(n),t?.signal?.throwIfAborted()}};var aK=new xe(Mv);var vK=ps("datastore:core:tiered");async function Fv(r){if(r.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new C("Private network is enforced, but no protector was provided");return r}var ga;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:Ie(0),payloadType:Ie(0),payload:Ie(0),signature:Ie(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=t.bytes();break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Ve(t,r.codec()),r.decode=(t,n)=>$e(t,r.codec(),n)})(ga||(ga={}));var Bu=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var Cs=class r{static createFromProtobuf=e=>{let t=ga.decode(e),n=an(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let o=e.domain,s=e.codec,i=e.marshal(),a=$v(o,s,i),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:s,payload:i,signature:c})};static openAndCertify=async(e,t,n)=>{let o=r.createFromProtobuf(e);if(!await o.validate(t,n))throw new Bu("Envelope signature is not valid for the given domain");return o};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:o,signature:s}=e;this.publicKey=t,this.payloadType=n,this.payload=o,this.signature=s}marshal(){return this.marshaled==null&&(this.marshaled=ga.encode({publicKey:Tt(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:W(this.marshal(),e.marshal())}async validate(e,t){let n=$v(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},$v=(r,e,t)=>{let n=T(r),o=nn(n.byteLength),s=nn(e.length),i=nn(t.length);return new ae(o,n,s,e,i,t)};var Vv="libp2p-peer-record",Kv=Uint8Array.from([3,1]);var ya;(function(r){let e;(function(n){let o;n.codec=()=>(o==null&&(o=Ke((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.multiaddr!=null&&s.multiaddr.byteLength>0&&(i.uint32(10),i.bytes(s.multiaddr)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={multiaddr:Ie(0)},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{c.multiaddr=s.bytes();break}default:{s.skipType(u&7);break}}}return c})),o),n.encode=s=>Ve(s,n.codec()),n.decode=(s,i)=>$e(s,n.codec(),i)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=Ke((n,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(o.uint32(10),o.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(o.uint32(16),o.uint64(n.seq)),n.addresses!=null)for(let i of n.addresses)o.uint32(26),r.AddressInfo.codec().encode(i,o);s.lengthDelimited!==!1&&o.ldelim()},(n,o,s={})=>{let i={peerId:Ie(0),seq:0n,addresses:[]},a=o==null?n.len:n.pos+o;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{i.peerId=n.bytes();break}case 2:{i.seq=n.uint64();break}case 3:{if(s.limits?.addresses!=null&&i.addresses.length===s.limits.addresses)throw new Fn('Decode error - map field "addresses" had too many elements');i.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:s.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return i})),t),r.encode=n=>Ve(n,r.codec()),r.decode=(n,o)=>$e(n,r.codec(),o)})(ya||(ya={}));function Hv(r,e){let t=(n,o)=>n.toString().localeCompare(o.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,o)=>e[o].equals(n)))}var ho=class r{static createFromProtobuf=e=>{let t=ya.decode(e),n=ys(Xe(t.peerId)),o=(t.addresses??[]).map(i=>oe(i.multiaddr)),s=t.seq;return new r({peerId:n,multiaddrs:o,seqNumber:s})};static DOMAIN=Vv;static CODEC=Kv;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:o}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=o??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=ya.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!Hv(this.multiaddrs,e.multiaddrs))}};var Fr;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=Ke((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:"",value:Ie(0)},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=i.bytes();break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Ve(i,o.codec()),o.decode=(i,a)=>$e(i,o.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=Ke((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),Lu.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a,c={})=>{let l={key:""},u=a==null?i.len:i.pos+a;for(;i.pos<u;){let f=i.uint32();switch(f>>>3){case 1:{l.key=i.string();break}case 2:{l.value=Lu.codec().decode(i,i.uint32(),{limits:c.limits?.value});break}default:{i.skipType(f&7);break}}}return l})),s),o.encode=i=>Ve(i,o.codec()),o.decode=(i,a)=>$e(i,o.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=Ke((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),Du.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);o.updated!=null&&(s.uint32(64),s.uint64Number(o.updated)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{if(i.limits?.addresses!=null&&a.addresses.length===i.limits.addresses)throw new Fn('Decode error - map field "addresses" had too many elements');a.addresses.push(Du.codec().decode(o,o.uint32(),{limits:i.limits?.addresses$}));break}case 2:{if(i.limits?.protocols!=null&&a.protocols.length===i.limits.protocols)throw new Fn('Decode error - map field "protocols" had too many elements');a.protocols.push(o.string());break}case 4:{a.publicKey=o.bytes();break}case 5:{a.peerRecordEnvelope=o.bytes();break}case 6:{if(i.limits?.metadata!=null&&a.metadata.size===i.limits.metadata)throw new li('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(o,o.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(i.limits?.tags!=null&&a.tags.size===i.limits.tags)throw new li('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(o,o.uint32(),{limits:{value:i.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=o.uint64Number();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Ve(o,r.codec()),r.decode=(o,s)=>$e(o,r.codec(),s)})(Fr||(Fr={}));var Du;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),t.observed!=null&&(n.uint32(24),n.uint64Number(t.observed)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={multiaddr:Ie(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.multiaddr=t.bytes();break}case 2:{s.isCertified=t.bool();break}case 3:{s.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Ve(t,r.codec()),r.decode=(t,n)=>$e(t,r.codec(),n)})(Du||(Du={}));var Lu;(function(r){let e;r.codec=()=>(e==null&&(e=Ke((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={value:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.value=t.uint32();break}case 2:{s.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Ve(t,r.codec()),r.decode=(t,n)=>$e(t,r.codec(),n)})(Lu||(Lu={}));function XT(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=an(e.publicKey,t);return Kp(n)}function qv(r,e,t){let n=Fr.decode(e);return _s(r,n,t)}function _s(r,e,t){let n=new Map,o=BigInt(Date.now());for(let[s,i]of e.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...e,id:XT(r,e),addresses:e.addresses.filter(({observed:s})=>s!=null&&s>Date.now()-t).map(({multiaddr:s,isCertified:i})=>({multiaddr:oe(s),isCertified:i??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function zv(r,e){return JT(r.addresses,e.addresses)&&QT(r.protocols,e.protocols)&&ek(r.publicKey,e.publicKey)&&tk(r.peerRecordEnvelope,e.peerRecordEnvelope)&&rk(r.metadata,e.metadata)&&nk(r.tags,e.tags)}function JT(r,e){return Wv(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!W(t.multiaddr,n.multiaddr)))}function QT(r,e){return Wv(r,e,(t,n)=>t===n)}function ek(r,e){return Gv(r,e)}function tk(r,e){return Gv(r,e)}function rk(r,e){return jv(r,e,(t,n)=>W(t,n))}function nk(r,e){return jv(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function Gv(r,e){return r==null&&e==null?!0:r!=null&&e!=null?W(r,e):!1}function Wv(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function jv(r,e,t){if(r.size!==e.size)return!1;for(let[n,o]of r.entries()){let s=e.get(n);if(s==null||!t(o,s))return!1}return!0}var pg="/peers/";function wa(r){if(!sr(r)||r.type==null)throw new C("Invalid PeerId");let e=r.toCID().toString();return new xe(`${pg}${e}`)}async function Yv(r,e,t,n,o){let s=new Map;for(let i of t){if(i==null)continue;if(i.multiaddr instanceof Uint8Array&&(i.multiaddr=oe(i.multiaddr)),!un(i.multiaddr))throw new C("Multiaddr was invalid");if(!await e(r,i.multiaddr,o))continue;let a=i.isCertified??!1,c=i.multiaddr.toString(),l=s.get(c);l!=null?i.isCertified=l.isCertified||a:s.set(c,{multiaddr:i.multiaddr,isCertified:a})}return[...s.values()].sort((i,a)=>i.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:i,multiaddr:a})=>{let c=a.getComponents().find(l=>l.code===421)?.value;return r.equals(c)&&(a=a.decapsulate(oe(`/p2p/${r}`))),{isCertified:i,multiaddr:a.bytes}})}async function Ru(r,e,t,n){if(e==null)throw new C("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new C("publicKey bytes do not match peer id publicKey bytes");let o=n.existingPeer?.peer;if(o!=null&&!r.equals(o.id))throw new C("peer id did not match existing peer id");let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=Nu(d,{validate:Zv})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=Nu(d,{validate:Xv,map:Jv})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,m]of d)m==null?a.delete(h):a.set(h,m);a=Nu([...a.entries()],{validate:Zv})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[m,g]of d)g==null?h.delete(m):h.set(m,g);c=Nu([...h.entries()],{validate:Xv,map:Jv})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;o?.id.publicKey!=null?u=Tt(o.id.publicKey):e.publicKey!=null?u=Tt(e.publicKey):r.publicKey!=null&&(u=Tt(r.publicKey));let f={addresses:await Yv(r,n.addressFilter??(async()=>!0),s,n.existingPeer?.peerPB.addresses,n),protocols:[...i.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>W(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function Nu(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function Zv(r,e){if(typeof r!="string")throw new C("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new C("Metadata value must be a Uint8Array")}function Xv(r,e){if(typeof r!="string")throw new C("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new C("Tag value must be an integer");if(e.value<0||e.value>100)throw new C("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new C("Tag ttl must be an integer");if(e.ttl<0)throw new C("Tag ttl must be between greater than 0")}}function Jv(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function Qv(r){let e=r.toString().split("/")[2],t=V.parse(e,ge);return Qn(t)}function mg(r,e,t){let n=Qv(r);return qv(n,e,t)}function ok(r,e){return{prefix:pg,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(mg(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(mg(n.key,n.value,e),mg(o.key,o.value,e)))}}var Ou=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=qp({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:Ji({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let o=await n.lock.readLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async getWriteLock(e,t){let n=this.getLock(e);try{let o=await n.lock.writeLock(t);return()=>{o(),this.maybeRemoveLock(e,n)}}catch(o){throw this.maybeRemoveLock(e,n),o}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(wa(e),t)}async load(e,t){let n=wa(e),o=await this.datastore.get(n,t),s=Fr.decode(o);if(this.#r(e,s))throw await this.datastore.delete(n,t),new Rt;return _s(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let o=await this.#e(e,n),s=await Ru(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,s,o)}async patch(e,t,n){let o=await this.#e(e,n),s=await Ru(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async merge(e,t,n){let o=await this.#e(e,n),s=await Ru(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,o)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(ok(e??{},this.maxAddressAge),e)){let o=Qv(t);if(o.equals(this.peerId))continue;let s=Fr.decode(n);if(this.#r(o,s)){await this.datastore.delete(t,e);continue}yield _s(o,s,this.peerId.equals(o)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=wa(e),o=await this.datastore.get(n,t),s=Fr.decode(o);if(this.#r(e,s))throw await this.datastore.delete(n,t),new Rt;return{peerPB:s,peer:_s(e,s,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,o){t.updated=Date.now();let s=Fr.encode(t);return await this.datastore.put(wa(e),s,o),{peer:_s(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!zv(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,o=Date.now()-this.maxAddressAge,s=t.addresses.filter(i=>i.observed!=null&&i.observed>o);return n&&s.length===0}};var gg=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new Ou(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return uo(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:o})=>o)}}async save(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.save(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async patch(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.patch(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async merge(e,t,n){let o=await this.store.getWriteLock(e,n);try{let s=await this.store.merge(e,t,n);return this.#e(e,s),s.peer}finally{o?.()}}async consumePeerRecord(e,t,n){let o=sr(t)?t:sr(t?.expectedPeer)?t.expectedPeer:void 0,s=sr(t)||t===void 0?n:t,i=await Cs.openAndCertify(e,ho.DOMAIN,s),a=Qn(i.publicKey.toCID());if(o?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",o,a),!1;let c=ho.createFromProtobuf(i.payload),l;try{l=await this.get(a,s)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=Cs.createFromProtobuf(l.peerRecordEnvelope),f=ho.createFromProtobuf(u.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},s),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function eE(r,e={}){return new gg(r,e)}var tE=864e13;var Mu=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=tt({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=te(e),n=t.host;(t.type==="ip4"||t.type==="ip6")&&t.sni!=null&&(n=t.sni);for(let o of this.mappings.values())if(o.domain===n)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let o=Jo(n)===!0;this.mappings.set(n,{domain:e,verified:o,expires:o?tE-Date.now():0,lastVerified:o?tE-Date.now():void 0})})}remove(e){let t=te(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries())s.domain===t.sni&&(this.log("removing %s to %s DNS mapping %e",o,s.domain),this.mappings.delete(o),n=n||s.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr;if(!He(o))continue;let s=te(o);for(let[i,a]of this.mappings.entries()){if(s.host!==i)continue;let c=this.maybeAddSNIComponent(o,a.domain);c!=null&&(e.splice(n,1),n--,t.push({multiaddr:c,verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNIComponent(e,t){let n=e.getComponents();for(let o=0;o<n.length;o++)if(n[o].code===448&&n[o+1]?.code!==449)return n.splice(o+1,0,{name:"sni",code:449,value:t}),oe(n)}confirm(e,t){let n=te(e),o=n.host;(n.type==="ip4"||n.type==="ip6")&&n.sni!=null&&(o=n.sni);let s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("marking %s to %s DNS mapping as verified",i,a.domain),s=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return s}unconfirm(e,t){let n=te(e);if(n.type!=="ip4"&&n.type!=="ip6")return!1;let o=n.sni??n.host,s=!1;for(let[i,a]of this.mappings.entries())a.domain===o&&(this.log("removing verification of %s to %s DNS mapping",i,a.domain),s=s||a.verified,a.verified=!1,a.expires=Date.now()+t);return s}};var Uu=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=tt({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=te(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;for(let n of this.mappings.values())for(let o of n)if(o.externalIp===t.host)return!0;return!1}add(e,t,n,o=t,s="tcp"){let i=`${e}-${t}-${s}`,a=this.mappings.get(i)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:o,externalFamily:at(n)?4:6,protocol:s,verified:!1,expires:0};a.push(c),this.mappings.set(i,a)}remove(e){let t=te(e);if(t.type!=="ip4"&&t.type!=="ip6")return!1;let n=!1;for(let[o,s]of this.mappings.entries()){for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===t.host&&a.externalPort===t.port&&a.protocol===t.protocol&&(this.log("removing %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,t.host,t.port,t.protocol),n=n||a.verified,s.splice(i,1),i--)}s.length===0&&this.mappings.delete(o)}return n}getAll(e){let t=[];for(let{multiaddr:n}of e){if(!He(n))continue;let o=te(n);if(o.type!=="ip4"&&o.type!=="ip6")continue;let s;if(o.protocol==="tcp"?s=`${o.host}-${o.port}-tcp`:o.protocol==="udp"&&(s=`${o.host}-${o.port}-udp`),s==null)continue;let i=this.mappings.get(s);if(i!=null)for(let a of i)t.push({multiaddr:this.maybeOverrideIp(n,a.externalIp,a.externalFamily,a.protocol,a.externalPort),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}maybeOverrideIp(e,t,n,o,s){let i=e.getComponents(),a=i.findIndex(l=>l.code===4||l.code===41),c=i.findIndex(l=>l.name===o);return a>-1&&c>-1?(i[a].value=t,i[a].code=n===4?4:41,i[c].value=`${s}`,oe(i)):e}confirm(e,t){if(!He(e))return!1;let n=te(e),o=!1;for(let s of this.mappings.values())for(let i of s)i.externalIp===n.host&&(this.log("marking %s to %s IP mapping as verified",i.internalIp,i.externalIp),o=i.verified,i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now());return o}unconfirm(e,t){if(!He(e))return!1;let n=te(e),o=!1;for(let s of this.mappings.values())for(let i=0;i<s.length;i++){let a=s[i];a.externalIp===n.host&&a.externalPort===n.port&&a.protocol===n.protocol&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n.host,n.port,n.protocol),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}};var sk={maxObservedAddresses:10},Fu=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=tt({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??sk.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(zt(e)||gw(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:oe(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),o=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,o),s}};var ik={maxObservedAddresses:10},$u=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=tt({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??ik.maxObservedAddresses}get(e,t){if(zt(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),o=this.addresses.get(n);return o==null&&(o={verified:!He(e),expires:0},this.addresses.set(n,o)),{multiaddr:e,verified:o.verified,type:"transport",expires:o.expires,lastVerified:o.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},s=o.verified;return o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now(),this.addresses.set(n,o),s}unconfirm(e,t){let n=this.toKey(e),o=this.addresses.get(n)??{verified:!1,expires:0},s=o.verified;return o.verified=!1,o.expires=Date.now()+t,this.addresses.set(n,o),s}toKey(e){if(!He(e))return e.toString();let t=te(e);return`${t.host}-${t.port}-${t.protocol}`}};var rE=6e4,nE={maxObservedAddresses:10,addressVerificationTTL:rE*10,addressVerificationRetry:rE*5},ak=r=>r;function yg(r,e){let t=r.getComponents().findLast(n=>n.code===421)?.value;return t!=null&&mr(t).equals(e)&&(r=r.decapsulate(oe(`/p2p/${e.toString()}`))),r}var Vu=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:o=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(i=>i.toString()),this.announce=new Set(o.map(i=>i.toString())),this.appendAnnounce=new Set(s.map(i=>i.toString())),this.observed=new Fu(e,t),this.dnsMappings=new Mu(e,t),this.ipMappings=new Uu(e,t),this.transportAddresses=new $u(e,t),this.announceFilter=t.announceFilter??ak,this.observedAddressFilter=Hn(1024),this.addressVerificationTTL=t.addressVerificationTTL??nE.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??nE.addressVerificationRetry,this._updatePeerStoreAddresses=Ii(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getComponents().findLast(n=>n.code===421)?.value===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses - %e",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>oe(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>oe(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>oe(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=te(e),n;switch(t.type){case"ip4":{n=`${t.host}:${t.port}`;break}case"ip6":{n=`[${t.host}]:${t.port}`;break}default:return}this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=yg(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=yg(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=yg(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let o=n.multiaddr.toString();return e.has(o)?!1:(e.add(o),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let o=oe(n);return o.getComponents().pop()?.value===this.components.peerId.toString()?o:o.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(e)}),e.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(o=>this.transportAddresses.get(o,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(o=>{o.updateAnnounceAddrs(n)}),t=t.concat(n.map(o=>({multiaddr:o,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(oe(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.add(e,t,n,o,s),this.observed.removePrefixed(`/ip${at(n)?4:6}/${n}/${s}/${o}`)}removePublicAddressMapping(e,t,n,o=t,s="tcp"){this.ipMappings.remove(oe(`/ip${at(n)?4:6}/${n}/${s}/${o}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e)||!He(e))return!1;let t=te(e);if(t.type!=="ip4"||Jo(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),o=[s=>io.exactMatch(s)||oa.exactMatch(s),s=>na.exactMatch(s),s=>Kx.exactMatch(s)];for(let s of o){if(!s(e))continue;let i=n.filter(l=>l.getAddrs().filter(u=>te(u).type==="ip4"&&s(u)).length>0);if(i.length!==1)continue;let a=i[0].getAddrs().filter(l=>!vi(l)).pop();if(a==null)continue;let c=te(a);return c.port==null?!1:(this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.protocol),!0)}return!1}};var oE;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(oE||(oE={}));var Ku=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},Hu=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Ts=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},ba=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},qu=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},zu=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},Gu=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},xa=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},Wu=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},ju=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},Yu=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},Zu=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},Xu=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},wn=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},po=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},Ju=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},Qu=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var wg=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=pn())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Wa(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},ck=["metrics","connectionProtector","dns"],lk=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function sE(r={}){let e=new wg(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!lk.includes(o)){let i=e.components[o];if(i==null&&!ck.includes(o))throw new Ku(`${o} not set`);return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function iE(r){let e={};for(let t of Object.values(r.components))for(let n of uk(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of fk(t))if(e[n]!==!0)throw new Hu(`Service "${dk(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function uk(r){return Array.isArray(r?.[Sn])?r[Sn]:[]}function fk(r){return Array.isArray(r?.[gd])?r[gd]:[]}function dk(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}function aE(r={}){return r.denyDialMultiaddr==null&&(r.denyDialMultiaddr=e=>io.matches(e)?!0:zt(e)),r}function ef(r){if(sr(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getComponents().findLast(o=>o.code===421)?.value;t=n==null?void 0:mr(n),e.forEach(o=>{if(!un(o))throw new Wr("Invalid multiaddr");let s=o.getComponents().findLast(i=>i.code===421)?.value;if(s==null){if(t!=null)throw new C("Multiaddrs must all have the same peer id or have no peer id")}else{let i=mr(s);if(t?.equals(i)!==!0)throw new C("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Ux.exactMatch(n)),{peerId:t,multiaddrs:e}}var hk=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function cE(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??hk;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}function va(r){let e=te(r),t=e.cidr;if(e.type!=="ip4"&&e.type!=="ip6")throw new C(`Multiaddr ${r} was not an IPv4 or IPv6 address`);if(t==null)switch(e.type){case"ip4":{t=32;break}case"ip6":{t=128;break}default:throw new C(`Multiaddr ${r} was not an IPv4 or IPv6 address`)}return new Gn(e.host,t)}function bg(r){return!ao.exactMatch(r)}function tf(r,e,t){if(r==null||e==null)return;let n=e.sort((s,i)=>s.direct?-1:i.direct?1:0).find(s=>s.limits==null);if(n==null||n.direct||t==null)return n;if(!t.some(s=>bg(s)))return n}var rf=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>va(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections - %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let o=new Dt;for(let c of e){let l=c.remotePeer;if(!o.has(l)){o.set(l,0);try{let u=await this.peerStore.get(l);o.set(l,[...u.tags.values()].reduce((f,d)=>f+d.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags - %e",u)}}}let s=this.sortConnections(e,o),i=Math.max(t-n,0),a=[];for(let c of s)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>{if(He(c.remoteAddr)){let f=te(c.remoteAddr);return u.contains(f.host)}return!0})||a.push(c),a.length===i)break;await Promise.all(a.map(async c=>{await cE(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var lE="last-dial-failure",uE="last-dial-success";var fE=100,nf=50;function pk(r,e){let t=na.exactMatch(r.multiaddr),n=na.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let o=oa.exactMatch(r.multiaddr),s=oa.exactMatch(e.multiaddr);if(o&&!s)return-1;if(!o&&s)return 1;let i=io.exactMatch(r.multiaddr),a=io.exactMatch(e.multiaddr);if(i&&!a)return-1;if(!i&&a)return 1;let c=Rm.exactMatch(r.multiaddr),l=Rm.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=Lm.exactMatch(r.multiaddr),f=Lm.exactMatch(e.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=Nm.exactMatch(r.multiaddr),h=Nm.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function mk(r,e){let t=vi(r.multiaddr),n=vi(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function gk(r,e){let t=zt(r.multiaddr),n=zt(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function yk(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function wk(r,e){let t=ao.exactMatch(r.multiaddr),n=ao.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function dE(r){return r.sort(pk).sort(yk).sort(wk).sort(gk).sort(mk)}var xg=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let s=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[It.TXT]}),i=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of s.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(i!=null&&!l.includes(i)||a.push(oe(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=pl()),this.dns)}},Ea=new xg;async function vg(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new Qu("Max recursive depth reached");let o=!1,s=[];for(let i of Object.values(e))if(i.canResolve(r)){o=!0;let a=await i.resolve(r,t);for(let c of a)s.push(...await vg(c,e,{...t,depth:n+1}))}return o===!1&&s.push(r),s}var Sa={maxParallelDials:nf,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Ea}},of=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Sa.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Sa.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Sa.dialTimeout,this.connections=t.connections??new Dt,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Sa.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new ol({concurrency:t.maxParallelDials??Sa.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==mt.name&&this.log.error("error in dial queue - %e",n.detail.error)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=ef(e);if(n!=null&&t.force!==!0){let i=tf(n,this.connections.get(n),o);if(i!=null)return this.log("already connected to %a",i.remoteAddr),t.onProgress?.(new Z("dial-queue:already-connected")),i}let s=this.queue.queue.find(i=>{if(n?.equals(i.options.peerId)===!0)return!0;let a=i.options.multiaddrs;if(a==null)return!1;for(let c of o)if(a.has(c.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let i of o)s.options.multiaddrs.add(i.toString());return t.onProgress?.(new Z("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new So("Dial queue is full");return this.log("creating dial target for %p",n,o.map(i=>i.toString())),t.onProgress?.(new Z("dial-queue:add-to-dial-queue")),this.queue.add(async i=>{i.onProgress?.(new Z("dial-queue:start-dial"));let a=me([this.shutDownController.signal,i.signal]);try{return await this.dialPeer(i,a)}finally{a.clear()}},{peerId:n,priority:t.priority??Ig,multiaddrs:new Set(o.map(i=>i.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,o=e.multiaddrs,s=new Set,i=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);i||o.size>0;){c++,i=!1;let u=[],f=new Set(e.multiaddrs);o.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(s.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new Z("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new So("Peer had more than maxPeerAddrsToDial");a++;try{let m=await this.components.transportManager.dial(h.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(m.remotePeer,{multiaddrs:[m.remoteAddr],metadata:{[uE]:T(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}return m}catch(m){if(this.log.error("dial failed to %a - %e",h.multiaddr,m),s.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[lE]:T(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p - %e",n,g)}if(t.aborted)throw new Ka(m.message);l.push(m)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(f=>({multiaddr:oe(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new So("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new xa("The dial request is blocked by gater.allowDialPeer");if(o.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);o.push(...f.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:d})=>d.toString())),o.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let s=(await Promise.all(o.map(async f=>{let d=await vg(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;s=s.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let i=s.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getComponents().findLast(h=>h.code===421)?.value;return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of i){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new Yu("The dial request has no valid addresses");let l=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||l.push(f);let u=this.addressSorter==null?dE(l):l.sort(this.addressSorter);if(u.length===0)throw new xa("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnLimitedConnection===!1?n.find(o=>!ao.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var bk=Object.prototype.toString,xk=r=>bk.call(r)==="[object Error]",vk=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Cg(r){if(!(r&&xk(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")?!0:vk.has(t)}function Ek(r){if(typeof r=="number"){if(r<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(r))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(r!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function sf(r,e,{min:t=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${r}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${r}\` to be a finite number.`);if(e<t)throw new TypeError(`Expected \`${r}\` to be \u2265 ${t}.`)}}var _g=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function Sk(r,e){let t=Math.max(1,r+1),n=e.randomize?Math.random()+1:1,o=Math.round(n*e.minTimeout*e.factor**(t-1));return o=Math.min(o,e.maxTimeout),o}function hE(r,e){return Number.isFinite(e)?e-(performance.now()-r):e}async function Ak({error:r,attemptNumber:e,retriesConsumed:t,startTime:n,options:o}){let s=r instanceof Error?r:new TypeError(`Non-error was thrown: "${r}". You should only throw errors.`);if(s instanceof _g)throw s.originalError;let i=Number.isFinite(o.retries)?Math.max(0,o.retries-t):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:s,attemptNumber:e,retriesLeft:i,retriesConsumed:t});if(await o.onFailedAttempt(c),hE(n,a)<=0)throw s;let l=await o.shouldConsumeRetry(c),u=hE(n,a);if(u<=0||i<=0)throw s;if(s instanceof TypeError&&!Cg(s)){if(l)throw s;return o.signal?.throwIfAborted(),!1}if(!await o.shouldRetry(c))throw s;if(!l)return o.signal?.throwIfAborted(),!1;let f=Sk(t,o),d=Math.min(f,u);return d>0&&await new Promise((h,m)=>{let g=()=>{clearTimeout(y),o.signal?.removeEventListener("abort",g),m(o.signal.reason)},y=setTimeout(()=>{o.signal?.removeEventListener("abort",g),h()},d);o.unref&&y.unref?.(),o.signal?.addEventListener("abort",g,{once:!0})}),o.signal?.throwIfAborted(),!0}async function Tg(r,e={}){if(e={...e},Ek(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,sf("factor",e.factor,{min:0,allowInfinity:!1}),sf("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),sf("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),sf("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let t=0,n=0,o=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){t++;try{e.signal?.throwIfAborted();let s=await r(t);return e.signal?.throwIfAborted(),s}catch(s){await Ak({error:s,attemptNumber:t,retriesConsumed:n,startTime:o,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}var af=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new ms({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(o=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,o)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);pE(t)&&(this.queue.has(e)||this.queue.add(async n=>{await Tg(async o=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(s){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,o,this.retries,s),s}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let o={};[...t.tags.keys()].forEach(s=>{s.startsWith(md)&&(o[s]=void 0)}),await this.peerStore.merge(e,{tags:o}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>pE(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error("could not open connection to keepalive peer - %e",n)})}))}).catch(e=>{this.log.error("error reconnect to peers after start - %e",e)})}stop(){this.started=!1,this.queue.abort()}};function pE(r){for(let e of r.tags.keys())if(e.startsWith(md))return!0;return!1}var Ig=50,kg={maxConnections:fE,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},cf=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??kg.maxConnections,this.maxConnections<1)throw new C("Connection Manager maxConnections must be greater than 0");this.connections=new Dt,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>va(oe(n))),this.deny=(t.deny??[]).map(n=>va(oe(n))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??kg.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new sl({points:t.inboundConnectionThreshold??kg.inboundConnectionThreshold,duration:1}),this.connectionPruner=new rf({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>oe(n))}),this.dialQueue=new of(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??nf,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Ea},connections:this.connections}),this.reconnectQueue=new af({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await ir(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await ar(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push(Promise.all([Gt(n,"close",{signal:AbortSignal.timeout(500)}),n.close({signal:AbortSignal.timeout(500)})]).catch(o=>{n.abort(o)}));this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new C("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error("could not connect - %e",t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,o=!this.connections.has(n),s=this.connections.get(n)??[];s.push(t),this.connections.set(n,s),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),o&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,s=(this.connections.get(n)??[]).filter(i=>i.id!==t.id);this.connections.set(n,s),s.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:n}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new vr("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n,multiaddrs:o}=ef(e);if(this.peerId.equals(n))throw new vo("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let c=tf(n,this.getConnections(n),o);if(c!=null)return this.log("had an existing connection to %p as %a",n,c.remoteAddr),t.onProgress?.(new Z("dial-queue:already-connected")),c}let s=await this.dialQueue.dial(e,{...t,priority:t.priority??Ig});if(s.status!=="open")throw new En("Remote closed connection during opening");let i=this.connections.get(s.remotePeer);i==null&&(i=[],this.connections.set(s.remotePeer,i));let a=!1;for(let c of i)if(c.id===s.id&&(a=!0),t.force!==!0&&c.id!==s.id&&c.remoteAddr.equals(s.remoteAddr))return s.abort(new Wr("Duplicate multiaddr connection")),c;return a||i.push(s),s}finally{this.outboundPendingConnections--}}async openStream(e,t,n={}){return(await this.openConnection(e,n)).newStream(t,n)}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await Promise.all([Gt(o,"close",t),o.close(t)])}catch(s){o.abort(s)}}))}acceptIncomingConnection(e){if(this.deny.some(o=>{if(He(e.remoteAddr)){let s=te(e.remoteAddr);return o.contains(s.host)}return!1}))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>{if(He(e.remoteAddr)){let s=te(e.remoteAddr);return o.contains(s.host)}return!0}))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(He(e.remoteAddr)){let o=te(e.remoteAddr);try{this.inboundConnectionRateLimiter.consume(o.host,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o.host),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>oe(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var _k=1e4,Tk="1.0.0",kk="ping",Pk="ipfs",mE=32,Bk=!0,lf=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??Pk}/${kk}/${Tk}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??_k,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??Bk,this.timeout=new Cc({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Sn]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),o=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),s=Ip(o);t=Date.now(),await Promise.all([s.write(Kt(mE),{signal:n}),s.read({bytes:mE,signal:n})]),e.rtt=Date.now()-t,await o.close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat - %e",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var uf=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()}),getAttributesFromYieldedValue:(n,o)=>({...o,providers:[...Array.isArray(o.providers)?o.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:B(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:B(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new Ts("No content routers available");let n=this,o=new to;for await(let s of kt(...n.routers.filter(i=>i.findProviders instanceof Function).map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new Ts("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Ts("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new vr;await Promise.all(this.routers.filter(o=>o.put instanceof Function).map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new vr;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var ff=globalThis.CustomEvent??Event;async function*Pg(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,o=new EventTarget,s=[],i=le(),a=le(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(s.length===t&&(i=le(),await i.promise),u)break;let g={done:!1};s.push(g),m().then(y=>{g.done=!0,g.ok=!0,g.value=y,o.dispatchEvent(new ff("task-complete"))},y=>{g.done=!0,g.err=y,o.dispatchEvent(new ff("task-complete"))})}c=!0,o.dispatchEvent(new ff("task-complete"))}catch(m){l=m,o.dispatchEvent(new ff("task-complete"))}});function f(){return n?s[0]?.done:!!s.find(m=>m.done)}function*d(){for(;s.length>0&&s[0].done;){let m=s[0];if(s.shift(),m.ok)yield m.value;else throw u=!0,i.resolve(),m.err;i.resolve()}}function*h(){for(;f();)for(let m=0;m<s.length;m++)if(s[m].done){let g=s[m];if(s.splice(m,1),m--,g.ok)yield g.value;else throw u=!0,i.resolve(),g.err;i.resolve()}}for(;;){if(f()||(a=le(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&s.length===0)break}}var df=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],o)=>({...o,key:B(n,"base36")}),getAttributesFromYieldedValue:(n,o)=>({...o,peers:[...Array.isArray(o.peers)?o.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new ba("No peer routers available");if(e.toString()===this.peerId.toString())throw new qu("Should not try to find self");let n=this,o=kt(...this.routers.filter(s=>s.findPeer instanceof Function).map(s=>(async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error("router failed to find peer - %e",i)}})()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),s;throw new Rt}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new ba("No peer routers available");let n=this,o=Hn(1024);for await(let s of Pg((async function*(){let i=kt(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs - %e",c);return}return a}})()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),!o.has(s.id.toMultihash().bytes)&&(o.add(s.id.toMultihash().bytes),yield s))}};var hf=class extends De{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=me([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=le(),yield(await Gt(this,"walk:peer",{signal:t,rejectionEvents:["walk:error"]})).detail}catch(n){throw n.detail!=null?n.detail:n}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=me([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let o=Kt(32),s=Date.now();for await(let i of this.peerRouting.getClosestPeers(o,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",i.id,Date.now()-s,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:i}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await kr(this.needNext.promise,e)),s=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",o,this.walkers,n)}catch(o){this.log.error("random walk errored - %e",o),this.safeDispatchEvent("walk:error",{detail:o})}this.log("no walkers left, ended walk")}).catch(o=>{this.log.error("random walk errored - %e",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Bg=32,Dg=64,pf=class{log;topologies;handlers;components;middleware;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.middleware=new Map,this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,o]of this.topologies)t[n]=o.size;return t}}),this.handlers=tt({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new zu(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new Gu(`Handler already registered for protocol ${e}`);this.handlers.set(e,{handler:t,options:{maxInboundStreams:Bg,maxOutboundStreams:Dg,...n}}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(o=>{this.handlers.delete(o)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new C("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}use(e,t){this.middleware.set(e,t)}unuse(e){this.middleware.delete(e)}getMiddleware(e){return this.middleware.get(e)??[]}async _onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};try{let o=await this.components.peerStore.get(t,n);for(let s of o.protocols){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t)!==!1&&(a.filter?.remove(t),await a.onDisconnect?.(t))}))}}catch(o){if(o.name==="NotFoundError")return;this.log.error("could not inform topologies of disconnecting peer %p - %e",t,o)}}async _onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));try{for(let s of o){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),await a.onDisconnect?.(t.id))}))}}catch(s){this.log.error("could not inform topologies of updated peer %p - %e",t.id,s)}}async _onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;try{for(let s of t){let i=this.topologies.get(s);i!=null&&await Promise.all([...i.values()].map(async a=>{n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),await a.onConnect?.(o,n))}))}}catch(s){this.log.error("could not inform topologies of updated peer after identify %p - %e",o,s)}}};var mf=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=tt({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=tt({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Us.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new C("Transport must have a valid tag");if(this.transports.has(t))throw new C(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new Ju(`No transport available for address ${String(e)}`);return t?.onProgress?.(new Z("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new vr("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(s=>{t.errors.set(s.toString(),new Wu)});let n=[];for(let[s,i]of this.transports.entries()){let a=i.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",s,c);let l=i.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(s)??[];u==null&&(u=[],this.listeners.set(s,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=u.findIndex(d=>d===l);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),km.matches(c)?t.ipv4.attempts++:Pm.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),km.matches(c)&&t.ipv4.success++,Pm.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",s,c,f),t.errors.set(c.toString(),f),f}))}}let o=await Promise.allSettled(n);if(!(o.length>0&&o.every(s=>s.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===Us.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new ju(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
15
16
  ${[...t.errors.entries()].map(([s,i])=>`
16
- ${s}: ${`${i.stack??i}`.split(`
17
+ ${s}: ${`${Dk(i)}`.split(`
17
18
  `).join(`
18
19
  `)}
19
- `).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Ke="/multistream/1.0.0";var cf=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},lf=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},uf=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Ea(r,e={}){let t=Qu(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Ce(e.maxDataLength));let n=e?.lengthDecoder??Rn,o=e?.lengthEncoder??yr;return{read:async i=>{let a=-1,c=new ee;for(;;){c.append(await t.read({...i,bytes:1}));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new cf("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new uf("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new lf("message length too long");return t.read({...i,bytes:a})},write:async(i,a)=>{await t.write(new ee(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new ee(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap:()=>t.unwrap()}}var xk=T(`
20
- `);async function Eo(r,e,t){await r.write(e,t)}async function Rv(r,e,t){await r.writeV(e,t)}async function vk(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==xk[0])throw e.log.error("Invalid mss message - missing newline",t),new $a("Missing newline");return t.sublist(0,-1)}async function Bn(r,e){let t=await vk(r,e);return O(t.subarray())}async function Aa(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return Ek(r,e[0],t);let n=Ea(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Ke,o);let s=T(`${Ke}
21
- `),i=T(`${o}
22
- `);await Rv(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await Bn(n,t);if(t.log.trace('select: read "%s"',a),a===Ke&&(t.log.trace("select: reading protocol response"),a=await Bn(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Eo(n,T(`${c}
23
- `),t),t.log.trace("select: reading protocol response");let l=await Bn(n,t);if(t.log.trace('select: read "%s" for "%s"',l,c),l===c)return{stream:n.unwrap(),protocol:c}}throw new Gs("protocol selection failed")}function Ek(r,e,t){let n=r.sink.bind(r),o=r.source,s=!1,i=!1,a=Q(),c=!1,l=!1,u=Q(),f=!1,d=!1,h=Q(),p=Ea({sink:n,source:o},{...t,maxDataLength:1024});r.sink=async S=>{let{sink:E}=p.unwrap();await E(async function*(){let D=!1;for await(let M of S){if(l&&await u.promise,c)yield M;else{l=!0,t.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Ke,e,M.byteLength);let z=`${e}
24
- `;yield new ee(Uint8Array.from([19]),T(`${Ke}
25
- `),yr(z.length),T(z),M).subarray(),t.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Ke,e,M.byteLength),c=!0,l=!1,u.resolve(),m().catch(W=>{t.log.error("could not finish optimistic protocol negotiation of %s",e,W)})}D=!0}D||await m()}())};async function m(){if(i){t.log.trace("optimistic: already negotiating %s stream",e),await a.promise;return}i=!0;try{c||(t.log.trace("optimistic: doing send protocol for %s stream",e),await w()),f||(t.log.trace("optimistic: doing read protocol for %s stream",e),await y())}finally{i=!1,s=!0,a.resolve()}}async function w(){if(l){await u.promise;return}l=!0;try{t.log.trace('optimistic: write ["%s", "%s", data] in source',Ke,e),await p.writeV([T(`${Ke}
26
- `),T(`${e}
27
- `)]),t.log.trace('optimistic: wrote ["%s", "%s", data] in source',Ke,e)}finally{c=!0,l=!1,u.resolve()}}async function y(){if(d){await h.promise;return}d=!0;try{t.log.trace("optimistic: reading multistream select header");let S=await Bn(p,t);if(t.log.trace('optimistic: read multistream select header "%s"',S),S===Ke&&(S=await Bn(p,t)),t.log.trace('optimistic: read protocol "%s", expecting "%s"',S,e),S!==e)throw new Gs("protocol selection failed")}finally{f=!0,d=!1,h.resolve()}}if(r.source=async function*(){await m(),t.log.trace('optimistic: reading data from "%s" stream',e),yield*p.unwrap().source}(),r.closeRead!=null){let S=r.closeRead.bind(r);r.closeRead=async E=>{s||await m().catch(D=>{t.log.error("could not negotiate protocol before close read",D)}),await S(E)}}if(r.closeWrite!=null){let S=r.closeWrite.bind(r);r.closeWrite=async E=>{s||await m().catch(D=>{t.log.error("could not negotiate protocol before close write",D)}),await S(E)}}if(r.close!=null){let S=r.close.bind(r);r.close=async E=>{let D=[];l&&D.push(u.promise),d&&D.push(h.promise),D.length>0?await Le(Promise.all(D),E?.signal):(s=!0,i=!1,a.resolve()),await S(E)}}return{stream:r,protocol:e}}async function Sa(r,e,t){e=Array.isArray(e)?e:[e],t.log.trace("handle: available protocols %s",e);let n=Ea(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){t.log.trace("handle: reading incoming string");let o=await Bn(n,t);if(t.log.trace('handle: read "%s"',o),o===Ke){t.log.trace('handle: respond with "%s" for "%s"',Ke,o),await Eo(n,T(`${Ke}
28
- `),t),t.log.trace('handle: responded with "%s" for "%s"',Ke,o);continue}if(e.includes(o))return t.log.trace('handle: respond with "%s" for "%s"',o,o),await Eo(n,T(`${o}
29
- `),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new ee(...e.map(i=>oc.single(T(`${i}
20
+ `).join("")}`)}}ipv6Unsupported(e){if(e.ipv4.attempts===0||e.ipv6.attempts===0)return!1;let t=e.ipv4.attempts===e.ipv4.success,n=e.ipv6.success===0;return t&&n}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};function Dk(r){return r.stack!=null&&r.stack.trim()!==""?r.stack:r.message!=null?r.message:r.toString()}var yr="/multistream/1.0.0";var Lk=T(`
21
+ `);async function Aa(r,e){let n=(await r.read(e)).subarray();if(n.byteLength===0||n[n.length-1]!==Lk[0])throw new Va("Missing newline");return B(n).trimEnd()}async function ks(r,e,t={}){if(e=Array.isArray(e)?[...e]:[e],e.length===0)throw new Error("At least one protocol must be specified");let n=r.log.newScope("mss:select"),o=Oc(r,{...t,maxDataLength:1024});for(let s=0;s<e.length;s++){let i=e[s],a;if(s===0){n.trace('write ["%s", "%s"]',yr,i);let c=T(`${yr}
22
+ `),l=T(`${i}
23
+ `);if(await o.writeV([c,l],t),n.trace("reading multistream-select header"),a=await Aa(o,t),n.trace('read "%s"',a),a!==yr){n.error("did not read multistream-select header from response");break}}else n.trace('write "%s"',i),await o.write(T(`${i}
24
+ `),t);if(n.trace("reading protocol response"),a=await Aa(o,t),n.trace('read "%s"',a),a===i)return n.trace('selected "%s" after negotiation',a),o.unwrap(),i}throw new $a(`Protocol selection failed - could not negotiate ${e}`)}async function Ps(r,e,t={}){e=Array.isArray(e)?e:[e];let n=r.log.newScope("mss:handle"),o=Oc(r,{...t,maxDataLength:1024,maxLengthLength:2});for(;;){n.trace("reading incoming string");let s=await Aa(o,t);if(n.trace('read "%s"',s),s===yr){n.trace('respond with "%s" for "%s"',yr,s),await o.write(T(`${yr}
25
+ `),t),n.trace('responded with "%s" for "%s"',yr,s);continue}if(e.includes(s))return n.trace('respond with "%s" for "%s"',s,s),await o.write(T(`${s}
26
+ `),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new ae(...e.map(a=>tl.single(T(`${a}
30
27
  `))),T(`
31
- `));t.log.trace('handle: respond with "%s" for %s',e,o),await Eo(n,s,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log.trace('handle: respond with "na" for "%s"',o),await Eo(n,T(`na
32
- `),t),t.log('handle: responded with "na" for "%s"',o)}}var Sk=500,pg=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[kg]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new Va("the connection is being closed");if(this.status==="closed")throw new ko("the connection is closed");if(Array.isArray(e)||(e=[e]),this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Po("Cannot open protocol stream on limited connection");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(Sk);e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.status!=="closed"&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}};function Mv(r){return new pg(r)}function Ik(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return fg}function Ck(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??dg}function Uv(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var ff=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=Je({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=Je({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Fu(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=de([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=await Le(this.components.connectionManager.acceptIncomingConnection(e),o),!n)throw new Vu("Connection denied");await Le(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=Rt(n),await Le(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o,s,i,a,c;this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let l=e;if(n?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(e.log("protecting the %s connection",t),l=await u.protect(e,n))}try{if(o=l,n?.skipEncryption!==!0){n?.onProgress?.(new j(`upgrader:encrypt-${t}-connection`)),{conn:o,remotePeer:s,protocol:c,streamMuxer:a}=await(t==="inbound"?this._encryptInbound(l,n):this._encryptOutbound(l,n));let u={...l,...o};await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,u)}else{let u=e.remoteAddr.getPeerId();if(u==null)throw new an(`${t} connection that skipped encryption must have a peer id`);let f=Rt(u);c="native",s=f}if(s.equals(this.components.peerId)){let u=new To("Can not dial self");throw e.abort(u),u}if(i=o,n?.muxerFactory!=null)a=n.muxerFactory;else if(a==null&&this.streamMuxers.size>0){n?.onProgress?.(new j(`upgrader:multiplex-${t}-connection`));let u=await(t==="inbound"?this._multiplexInbound({...l,...o},this.streamMuxers,n):this._multiplexOutbound({...l,...o},this.streamMuxers,n));a=u.muxerFactory,i=u.stream}}catch(u){throw e.log.error("failed to upgrade inbound connection %s %a - %e",t==="inbound"?"from":"to",e.remoteAddr,u),u}return await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:c,direction:t,maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,limits:n?.limits})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,limits:c}=e,l,u,f;a!=null&&(l=a.createStreamMuxer({direction:n,onIncomingStream:p=>{if(f==null)return;let m=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then(async()=>{let w=this.components.registrar.getProtocols(),{stream:y,protocol:S}=await Sa(p,w,{signal:m,log:p.log,yieldBytes:!1});if(f==null)return;f.log("incoming stream opened on %s",S);let E=Ik(S,this.components.registrar);if(Uv(S,"inbound",f)===E){let M=new qa(`Too many inbound protocol streams for protocol "${S}" - limit ${E}`);throw p.abort(M),M}p.source=y.source,p.sink=y.sink,p.protocol=S,y.closeWrite!=null&&(p.closeWrite=y.closeWrite),y.closeRead!=null&&(p.closeRead=y.closeRead),y.close!=null&&(p.close=y.close),await this.components.peerStore.merge(i,{protocols:[S]},{signal:m}),this.components.metrics?.trackProtocolStream(p,f),this._onStream({connection:f,stream:p,protocol:S})}).catch(async w=>{f.log.error("error handling incoming stream id %s - %e",p.id,w),p.timeline.close==null&&await p.close({signal:m}).catch(y=>p.abort(y))})}}),u=async(p,m={})=>{if(l==null)throw new bo("Connection is not multiplexed");f.log.trace("starting new stream for protocols %s",p);let w=await l.newStream();f.log.trace("started new stream %s for protocols %s",w.id,p);try{if(m.signal==null){w.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let M=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);m={...m,signal:M}}w.log.trace("selecting protocol from protocols %s",p);let{stream:y,protocol:S}=await Aa(w,p,{...m,log:w.log,yieldBytes:!0});w.log.trace("selected protocol %s",S);let E=Ck(S,this.components.registrar,m),D=Uv(S,"outbound",f);if(D>=E){let M=new za(`Too many outbound protocol streams for protocol "${S}" - ${D}/${E}`);throw w.abort(M),M}return await this.components.peerStore.merge(i,{protocols:[S]}),w.source=y.source,w.sink=y.sink,w.protocol=S,y.closeWrite!=null&&(w.closeWrite=y.closeWrite),y.closeRead!=null&&(w.closeRead=y.closeRead),y.close!=null&&(w.close=y.close),this.components.metrics?.trackProtocolStream(w,f),w}catch(y){throw f.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",n==="inbound"?"from":"to",e.maConn.remoteAddr,p,y),w.timeline.close==null&&w.abort(y),y}},Promise.all([l.sink(s.source),s.sink(l.source)]).catch(p=>{f.log.error("error piping data through muxer - %e",p)}));let d=o.timeline;o.timeline=new Proxy(d,{set:(...p)=>(p[1]==="close"&&p[2]!=null&&d.close==null&&(async()=>{try{f.status==="open"&&await f.close()}catch(m){f.log.error("error closing connection after timeline close %e",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:f})}})().catch(m=>{f.log.error("error thrown while dispatching connection:close event %e",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let h=()=>{throw new bo("Connection is not multiplexed")};return f=Mv({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:l?.protocol,encryption:t,limits:c,logger:this.components.logger,newStream:u??h,getStreams:()=>l?.streams??[],close:async p=>{await l?.close(p),await o.close(p)},abort:p=>{o.abort(p),l?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:f}),f.__maConnTimeline=d,f}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.limits!=null&&i.runOnLimitedConnection!==!0)throw new Po("Cannot open protocol stream on limited connection");s({connection:t,stream:n})}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let{stream:o,protocol:s}=await Sa(e,n,{...t,log:e.log}),i=this.connectionEncrypters.get(s);if(i==null)throw new xo(`no crypto module found for ${s}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,s),{...await i.secureInbound(o,t),protocol:s}}catch(o){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,o),new xo(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await Aa(e,n,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(i==null)throw new xo(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,s),{...await i.secureOutbound(o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,o),new xo(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let{stream:s,protocol:i}=await Aa(e,o,{...n,log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",i);let a=t.get(i);return{stream:s,muxerFactory:a}}catch(s){throw e.log.error("error multiplexing outbound connection",s),new bo(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{let{stream:s,protocol:i}=await Sa(e,o,{...n,log:e.log}),a=t.get(i);return{stream:s,muxerFactory:a}}catch(s){throw e.log.error("error multiplexing inbound connection",s),new bo(String(s))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};var df="2.9.0",hf="js-libp2p";function pf(r,e){return`${r??hf}/${e??df} browser/${globalThis.navigator.userAgent}`}var _a=class extends tt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new tt,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=e.peerId,this.logger=e.logger??vn(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??hf,s=e.nodeInfo?.version??df,i=this.components=mv({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??pf(o,s)},logger:this.logger,events:t,datastore:e.datastore??new mo,connectionGater:yv(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",lv(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new ff(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new af(this.components,e.transportManager)),this.configureComponent("connectionManager",new Zu(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new ef(this.components,e.connectionMonitor)),this.configureComponent("registrar",new sf(this.components)),this.configureComponent("addressManager",new Bu(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new nf(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new tf(this.components,{routers:c})),this.configureComponent("randomWalk",new of(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],f=u(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=f,this.configureComponent(l,f),f[on]!=null&&(this.log("registering service %s for content routing",l),c.push(f[on])),f[sn]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[sn])),f[ld]!=null&&(this.log("registering service %s for peer discovery",l),f[ld].addEventListener?.("peer",d=>{this.#e(d)}))}gv(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new eo;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new B("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new B("no protocols were provided to open a stream");return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Cn(e)&&(e=Rt(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=We([T("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=bn(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function Vv(r={}){r.privateKey??=await Nc("Ed25519");let e=new _a({...await jx(r),peerId:F0(r.privateKey)});return r.start!==!1&&await e.start(),e}var kk=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function Kv(r){return r==null?!1:r instanceof _a?!0:kk.every(e=>typeof r[e]=="function")}var V1=nn(Zv(),1);var Vs={};Ee(Vs,{create:()=>Kk,derivedEmptyPasswordKey:()=>mf});var mf={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Kk(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=Ae.get();t*=8;async function c(f,d){let h=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:p};typeof d=="string"&&(d=T(d));let w;if(d.length===0){w=await a.subtle.importKey("jwk",mf,{name:"AES-GCM"},!0,["encrypt"]);try{let S={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(S,E,{name:e,length:t},!0,["encrypt"])}catch{w=await a.subtle.importKey("jwk",mf,{name:"AES-GCM"},!0,["encrypt"])}}else{let S={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(S,E,{name:e,length:t},!0,["encrypt"])}let y=await a.subtle.encrypt(m,w,f);return We([h,m.iv,new Uint8Array(y)])}async function l(f,d){let h=f.subarray(0,s),p=f.subarray(s,s+n),m=f.subarray(s+n),w={name:e,iv:p};typeof d=="string"&&(d=T(d));let y;if(d.length===0)try{let E={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},D=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(E,D,{name:e,length:t},!0,["decrypt"])}catch{y=await a.subtle.importKey("jwk",mf,{name:"AES-GCM"},!0,["decrypt"])}else{let E={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},D=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(E,D,{name:e,length:t},!0,["decrypt"])}let S=await a.subtle.decrypt(w,y,m);return new Uint8Array(S)}return{encrypt:c,decrypt:l}}var J=nn(Xv());function Ao(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function Pn(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*e);l[s-u-1]=Math.floor(o/f),o-=l[s-u-1]*f}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function wf(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function gg(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=Ao(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,Ao(s,8)-n}function Jv(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=Pn(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Pn(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function Qv(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function ht(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var Vz=Math.log(2);function bf(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function yg(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function tn(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var ka=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return yg(this.items)}},Ia=[new Uint8Array([1])],e1="0123456789";var $s="",dr=new ArrayBuffer(0),wg=new Uint8Array(0),Ta="EndOfContent",r1="OCTET STRING",n1="BIT STRING";function rn(r){var e;return e=class extends r{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?J.BufferSourceConverter.toUint8Array(s.valueHex):wg}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!tn(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",dr)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:J.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Xr=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=$s,warnings:n=[],valueBeforeDecode:o=wg}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=J.BufferSourceConverter.toUint8Array(o)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:J.Convert.ToHex(this.valueBeforeDecodeView)}}};Xr.NAME="baseBlock";var et=class extends Xr{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};et.NAME="valueBlock";var xf=class extends rn(Xr){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?J.BufferSourceConverter.toUint8Array(e.valueHex):wg,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",dr}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=Pn(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=J.BufferSourceConverter.toUint8Array(e);if(!tn(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),u=255;for(;s[c]&128;){if(l[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===u){u+=255;let d=new Uint8Array(u);for(let h=0;h<l.length;h++)d[h]=l[h];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=s[c]&127;let f=new Uint8Array(c);for(let d=0;d<c;d++)f[d]=l[d];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=Ao(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};xf.NAME="identificationBlock";var vf=class extends Xr{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=J.BufferSourceConverter.toUint8Array(e);if(!tn(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Ao(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=Pn(this.length,8);if(o.byteLength>127)return this.error="Too big length",dr;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};vf.NAME="lengthBlock";var U={},$e=class extends Xr{constructor({name:e=$s,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new xf(o),this.lenBlock=new vf(o),this.valueBlock=s?new s(o):new et(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new ka;t||o1(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?dr:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():J.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=J.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return Qv(t,n)}};$e.NAME="BaseBlock";function o1(r){var e;if(r instanceof U.Constructed)for(let t of r.valueBlock.value)o1(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var Ef=class extends $e{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=$s,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Ef.NAME="BaseStringBlock";var Af=class extends rn(et){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Af.NAME="PrimitiveValueBlock";var s1,Sf=class extends $e{constructor(e={}){super(e,Af),this.idBlock.isConstructed=!1}};s1=Sf;U.Primitive=s1;Sf.NAME="PRIMITIVE";function Zk(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function od(r,e=0,t=r.length){let n=e,o=new $e({},et),s=new Xr;if(!tn(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=$e;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=U.EndOfContent;break;case 1:c=U.Boolean;break;case 2:c=U.Integer;break;case 3:c=U.BitString;break;case 4:c=U.OctetString;break;case 5:c=U.Null;break;case 6:c=U.ObjectIdentifier;break;case 10:c=U.Enumerated;break;case 12:c=U.Utf8String;break;case 13:c=U.RelativeObjectIdentifier;break;case 14:c=U.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=U.Sequence;break;case 17:c=U.Set;break;case 18:c=U.NumericString;break;case 19:c=U.PrintableString;break;case 20:c=U.TeletexString;break;case 21:c=U.VideotexString;break;case 22:c=U.IA5String;break;case 23:c=U.UTCTime;break;case 24:c=U.GeneralizedTime;break;case 25:c=U.GraphicString;break;case 26:c=U.VisibleString;break;case 27:c=U.GeneralString;break;case 28:c=U.UniversalString;break;case 29:c=U.CharacterString;break;case 30:c=U.BmpString;break;case 31:c=U.DATE;break;case 32:c=U.TimeOfDay;break;case 33:c=U.DateTime;break;case 34:c=U.Duration;break;default:{let l=o.idBlock.isConstructed?new U.Constructed:new U.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?U.Constructed:U.Primitive}return o=Zk(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function sd(r){if(!r.byteLength){let e=new $e({},et);return e.error="Input buffer has zero length",{offset:-1,result:e}}return od(J.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function Xk(r,e){return r?1:e}var _r=class extends et{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=J.BufferSourceConverter.toUint8Array(e);if(!tn(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;Xk(this.isIndefiniteForm,n)>0;){let i=od(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===Ta)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Ta?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new ka;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?dr:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};_r.NAME="ConstructedValueBlock";var i1,Dn=class extends $e{constructor(e={}){super(e,_r),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
28
+ `));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(T(`na
29
+ `),t),n('responded with "na" for "%s"',s)}}var Ng=class extends De{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=bg(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new za(n.local,n.error))})}[Symbol.toStringTag]="Connection";[jg]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new wn("Connection is not multiplexed");if(this.muxer.status!=="open")throw new En(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new En(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new Ms("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let a=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:a}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await ks(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=Ok(n.protocol,this.components.registrar,t),s=wE(n.protocol,"outbound",this);if(s>o){let a=new qa(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(a),a}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,i)}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await Ps(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=Rk(t.protocol,this.components.registrar);if(wE(t.protocol,"inbound",this)>o)throw new Ha(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new Ms("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,f)=>{await i(l,u),f(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function bE(r,e){return new Ng(r,e)}function Rk(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return Bg}function Ok(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??Dg}function wE(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var gf=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=tt({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=tt({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new Zu(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=me([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new Xu("Connection denied");await kr(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=mr(n),await kr(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let f=this.components.connectionProtector;f!=null&&(e.log("protecting the %s connection",t),o=await f.protect(o,n))}try{if(Mk(n)){if(n.remotePeer==null)throw new Wr(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let f=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,d;f!=null&&(d=mr(f)),n?.onProgress?.(new Z(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:d}):this._encryptOutbound(o,{...n,remotePeer:d}))}if(s.equals(this.components.peerId)){let f=new vo("Can not dial self");throw e.abort(f),f}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new Z(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(f){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,f),f}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=bE(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await Ps(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new po(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new po(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await ks(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new po(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new po(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await ks(e,o,n),i=t.get(s);if(i==null)throw new wn(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new wn(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await Ps(e,o,n),i=t.get(s);if(i==null)throw new wn(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function Mk(r){return r.skipEncryption===!0}var yf="3.0.6",wf="js-libp2p";function bf(r,e){return`${r??wf}/${e??yf} browser/${globalThis.navigator.userAgent}`}var Ia=class extends De{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new De,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),f=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||f},this.peerId=e.peerId,this.logger=e.logger??pn(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??wf,s=e.nodeInfo?.version??yf,i=this.components=sE({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??bf(o,s)},logger:this.logger,events:t,datastore:e.datastore??new fo,connectionGater:aE(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",eE(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(f=>f.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new gf(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new mf(this.components,e.transportManager)),this.configureComponent("connectionManager",new cf(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new lf(this.components,e.connectionMonitor)),this.configureComponent("registrar",new pf(this.components)),this.configureComponent("addressManager",new Vu(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new df(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new uf(this.components,{routers:c})),this.configureComponent("randomWalk",new hf(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],f=u(this.components);if(f==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=f,this.configureComponent(l,f),f[bo]!=null&&(this.log("registering service %s for content routing",l),c.push(f[bo])),f[Ao]!=null&&(this.log("registering service %s for peer routing",l),a.push(f[Ao])),f[pd]!=null&&(this.log("registering service %s for peer discovery",l),f[pd].addEventListener?.("peer",d=>{this.#e(d)}))}iE(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new to;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new C("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new C("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){un(e)&&(e=mr(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=ye([T("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=an(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function vE(r={}){r.privateKey??=await mc("Ed25519");let e=new Ia({...await Fv(r),peerId:zb(r.privateKey)});return r.start!==!1&&await e.start(),e}var Uk=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function EE(r){return r==null?!1:r instanceof Ia?!0:Uk.every(e=>typeof r[e]=="function")}var v1=vn(BE(),1);var Rg={keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"};var Bs={};_e(Bs,{create:()=>Xk,derivedEmptyPasswordKey:()=>xf});var xf={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Xk(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=Te.get();t*=8;async function c(f,d){let h=a.getRandomValues(new Uint8Array(s)),m=a.getRandomValues(new Uint8Array(n)),g={name:e,iv:m};typeof d=="string"&&(d=T(d));let y;if(d.length===0){y=await a.subtle.importKey("jwk",xf,{name:"AES-GCM"},!0,["encrypt"]);try{let P={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(P,A,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",xf,{name:"AES-GCM"},!0,["encrypt"])}}else{let P={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(P,A,{name:e,length:t},!0,["encrypt"])}let x=await a.subtle.encrypt(g,y,f);return ye([h,g.iv,new Uint8Array(x)])}async function l(f,d){let h=f.subarray(0,s),m=f.subarray(s,s+n),g=f.subarray(s+n),y={name:e,iv:m};typeof d=="string"&&(d=T(d));let x;if(d.length===0)try{let A={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},N=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);x=await a.subtle.deriveKey(A,N,{name:e,length:t},!0,["decrypt"])}catch{x=await a.subtle.importKey("jwk",xf,{name:"AES-GCM"},!0,["decrypt"])}else{let A={name:"PBKDF2",salt:h,iterations:i,hash:{name:o}},N=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);x=await a.subtle.deriveKey(A,N,{name:e,length:t},!0,["decrypt"])}let P=await a.subtle.decrypt(y,x,g);return new Uint8Array(P)}return{encrypt:c,decrypt:l}}var ne=vn(DE());function mo(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function bn(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*e);l[s-u-1]=Math.floor(o/f),o-=l[s-u-1]*f}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function Sf(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function Mg(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=mo(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,mo(s,8)-n}function LE(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=bn(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=bn(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function NE(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function ht(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var jW=Math.log(2);function Af(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Ug(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function zr(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var Ta=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Ug(this.items)}},Ca=[new Uint8Array([1])],RE="0123456789";var Ls="",nr=new ArrayBuffer(0),Fg=new Uint8Array(0),ka="EndOfContent",ME="OCTET STRING",UE="BIT STRING";function Gr(r){var e;return e=class extends r{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?ne.BufferSourceConverter.toUint8Array(s.valueHex):Fg}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!zr(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",nr)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ne.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Vr=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=Ls,warnings:n=[],valueBeforeDecode:o=Fg}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=ne.BufferSourceConverter.toUint8Array(o)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ne.Convert.ToHex(this.valueBeforeDecodeView)}}};Vr.NAME="baseBlock";var ot=class extends Vr{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};ot.NAME="valueBlock";var If=class extends Gr(Vr){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?ne.BufferSourceConverter.toUint8Array(e.valueHex):Fg,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",nr}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=bn(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=ne.BufferSourceConverter.toUint8Array(e);if(!zr(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),u=255;for(;s[c]&128;){if(l[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===u){u+=255;let d=new Uint8Array(u);for(let h=0;h<l.length;h++)d[h]=l[h];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=s[c]&127;let f=new Uint8Array(c);for(let d=0;d<c;d++)f[d]=l[d];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=mo(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};If.NAME="identificationBlock";var Cf=class extends Vr{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=ne.BufferSourceConverter.toUint8Array(e);if(!zr(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=mo(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=bn(this.length,8);if(o.byteLength>127)return this.error="Too big length",nr;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Cf.NAME="lengthBlock";var U={},je=class extends Vr{constructor({name:e=Ls,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new If(o),this.lenBlock=new Cf(o),this.valueBlock=s?new s(o):new ot(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new Ta;t||FE(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?nr:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():ne.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=ne.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${t}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return NE(t,n)}};je.NAME="BaseBlock";function FE(r){var e;if(r instanceof U.Constructed)for(let t of r.valueBlock.value)FE(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var _f=class extends je{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Ls,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};_f.NAME="BaseStringBlock";var Tf=class extends Gr(ot){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Tf.NAME="PrimitiveValueBlock";var $E,kf=class extends je{constructor(e={}){super(e,Tf),this.idBlock.isConstructed=!1}};$E=kf;U.Primitive=$E;kf.NAME="PRIMITIVE";function i6(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function ld(r,e=0,t=r.length){let n=e,o=new je({},ot),s=new Vr;if(!zr(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=je;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=U.EndOfContent;break;case 1:c=U.Boolean;break;case 2:c=U.Integer;break;case 3:c=U.BitString;break;case 4:c=U.OctetString;break;case 5:c=U.Null;break;case 6:c=U.ObjectIdentifier;break;case 10:c=U.Enumerated;break;case 12:c=U.Utf8String;break;case 13:c=U.RelativeObjectIdentifier;break;case 14:c=U.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=U.Sequence;break;case 17:c=U.Set;break;case 18:c=U.NumericString;break;case 19:c=U.PrintableString;break;case 20:c=U.TeletexString;break;case 21:c=U.VideotexString;break;case 22:c=U.IA5String;break;case 23:c=U.UTCTime;break;case 24:c=U.GeneralizedTime;break;case 25:c=U.GraphicString;break;case 26:c=U.VisibleString;break;case 27:c=U.GeneralString;break;case 28:c=U.UniversalString;break;case 29:c=U.CharacterString;break;case 30:c=U.BmpString;break;case 31:c=U.DATE;break;case 32:c=U.TimeOfDay;break;case 33:c=U.DateTime;break;case 34:c=U.Duration;break;default:{let l=o.idBlock.isConstructed?new U.Constructed:new U.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?U.Constructed:U.Primitive}return o=i6(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function ud(r){if(!r.byteLength){let e=new je({},ot);return e.error="Input buffer has zero length",{offset:-1,result:e}}return ld(ne.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function a6(r,e){return r?1:e}var wr=class extends ot{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=ne.BufferSourceConverter.toUint8Array(e);if(!zr(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;a6(this.isIndefiniteForm,n)>0;){let i=ld(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===ka)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===ka?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Ta;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?nr:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};wr.NAME="ConstructedValueBlock";var VE,xn=class extends je{constructor(e={}){super(e,wr),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
33
30
  `).map(o=>` ${o}`).join(`
34
31
  `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
35
32
  ${e.join(`
36
- `)}`:`${t} :`}};i1=Dn;U.Constructed=i1;Dn.NAME="CONSTRUCTED";var _f=class extends et{fromBER(e,t,n){return t}toBER(e){return dr}};_f.override="EndOfContentValueBlock";var a1,If=class extends $e{constructor(e={}){super(e,_f),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};a1=If;U.EndOfContent=a1;If.NAME=Ta;var c1,So=class extends $e{constructor(e={}){super(e,et),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};c1=So;U.Null=c1;So.NAME="NULL";var Cf=class extends rn(et){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=J.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,n){let o=J.BufferSourceConverter.toUint8Array(e);return tn(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,gg.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Cf.NAME="BooleanValueBlock";var l1,kf=class extends $e{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,Cf),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};l1=kf;U.Boolean=l1;kf.NAME="BOOLEAN";var Tf=class extends rn(_r){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=_r.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Ta){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==r1)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?_r.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Tf.NAME="OctetStringValueBlock";var bg,Jr=class extends $e{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Tf),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=od(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Dn.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,t=J.Convert.ToHex(this.valueBlock.valueHexView);return`${e} : ${t}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof bg&&e.push(t.valueBlock.valueHexView);return J.BufferSourceConverter.concat(e)}};bg=Jr;U.OctetString=bg;Jr.NAME=r1;var Bf=class extends rn(_r){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=_r.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Ta){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==n1)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let s=J.BufferSourceConverter.toUint8Array(e);if(!tn(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=od(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return _r.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return dr;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Bf.NAME="BitStringValueBlock";var u1,Pf=class extends $e{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Bf),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Dn.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let i of t)e.push(i.toString(2).padStart(8,"0"));let n=e.join(""),o=this.constructor.NAME,s=n.substring(0,n.length-this.valueBlock.unusedBits);return`${o} : ${s}`}}};u1=Pf;U.BitString=u1;Pf.NAME=n1;var f1;function Jk(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<i?i:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=s[i-f]+a[c-f]+t[0];break;default:l=s[i-f]+t[0]}switch(t[0]=l/10,!0){case f>=s.length:s=wf(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return t[0]>0&&(s=wf(t,s)),s}function t1(r){if(r>=Ia.length)for(let e=Ia.length;e<=r;e++){let t=new Uint8Array([0]),n=Ia[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=wf(t,n)),Ia.push(n)}return Ia[r]}function Qk(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=s[i-u]-a[c-u]-t,!0){case l<0:t=1,s[i-u]=l+10;break;default:t=0,s[i-u]=l}if(t>0)for(let f=i-c+1;f>=0;f--,u++)if(l=s[i-u]-t,l<0)t=1,s[i-u]=l+10;else{t=0,s[i-u]=l;break}return s.slice()}var Ba=class extends rn(et){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=gg.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Jv(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&(i[1]&128)!==0?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=Qk(t1(n),t),i="-";break;default:t=Jk(t,t1(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=e1.charAt(t[c]));return a===!1&&(i+=e1.charAt(0)),i}};f1=Ba;Ba.NAME="IntegerValueBlock";Object.defineProperty(f1.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Ca,Qr=class extends $e{constructor(e={}){super(e,Ba),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return bf(),BigInt(this.valueBlock.toString())}static fromBigInt(e){bf();let t=BigInt(e),n=new ka,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(J.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${J.Convert.ToHex(a)}`)+t,u=J.BufferSourceConverter.toUint8Array(J.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new Ca({valueHex:n.final()})}convertToDER(){let e=new Ca({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Ca({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Ca=Qr;U.Integer=Ca;Qr.NAME="INTEGER";var d1,Df=class extends Qr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};d1=Df;U.Enumerated=d1;Df.NAME="ENUMERATED";var Pa=class extends rn(et){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=J.BufferSourceConverter.toUint8Array(e);if(!tn(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ao(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){bf();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Pn(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",dr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=J.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Pa.NAME="sidBlock";var Lf=class extends et{constructor({value:e=$s,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Pa;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,dr;t.push(o)}return yg(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Pa;if(o>Number.MAX_SAFE_INTEGER){bf();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Lf.NAME="ObjectIdentifierValueBlock";var h1,Ir=class extends $e{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Lf),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};h1=Ir;U.ObjectIdentifier=h1;Ir.NAME="OBJECT IDENTIFIER";var Da=class extends rn(Xr){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=J.BufferSourceConverter.toUint8Array(e);if(!tn(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Ao(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Pn(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",dr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=J.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Da.NAME="relativeSidBlock";var Nf=class extends et{constructor({value:e=$s,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Da;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,dr;n.push(s)}return yg(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Da;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Nf.NAME="RelativeObjectIdentifierValueBlock";var p1,Rf=class extends $e{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Nf),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};p1=Rf;U.RelativeObjectIdentifier=p1;Rf.NAME="RelativeObjectIdentifier";var m1,pt=class extends Dn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};m1=pt;U.Sequence=m1;pt.NAME="SEQUENCE";var g1,Of=class extends Dn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};g1=Of;U.Set=g1;Of.NAME="SET";var Mf=class extends rn(et){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=$s}toJSON(){return{...super.toJSON(),value:this.value}}};Mf.NAME="StringValueBlock";var Uf=class extends Mf{};Uf.NAME="SimpleStringValueBlock";var ct=class extends Ef{constructor({...e}={}){super(e,Uf)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,J.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};ct.NAME="SIMPLE STRING";var Ff=class extends ct{fromBuffer(e){this.valueBlock.valueHexView=J.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=J.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=J.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(J.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Ff.NAME="Utf8StringValueBlock";var y1,en=class extends Ff{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};y1=en;U.Utf8String=y1;en.NAME="UTF8String";var Vf=class extends ct{fromBuffer(e){this.valueBlock.value=J.Convert.ToUtf16String(e),this.valueBlock.valueHexView=J.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(J.Convert.FromUtf16String(e))}};Vf.NAME="BmpStringValueBlock";var w1,Kf=class extends Vf{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};w1=Kf;U.BmpString=w1;Kf.NAME="BMPString";var $f=class extends ct{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=Pn(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};$f.NAME="UniversalStringValueBlock";var b1,Hf=class extends $f{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};b1=Hf;U.UniversalString=b1;Hf.NAME="UniversalString";var x1,qf=class extends ct{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};x1=qf;U.NumericString=x1;qf.NAME="NumericString";var v1,zf=class extends ct{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};v1=zf;U.PrintableString=v1;zf.NAME="PrintableString";var E1,Gf=class extends ct{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};E1=Gf;U.TeletexString=E1;Gf.NAME="TeletexString";var A1,Wf=class extends ct{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};A1=Wf;U.VideotexString=A1;Wf.NAME="VideotexString";var S1,jf=class extends ct{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};S1=jf;U.IA5String=S1;jf.NAME="IA5String";var _1,Yf=class extends ct{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};_1=Yf;U.GraphicString=_1;Yf.NAME="GraphicString";var I1,La=class extends ct{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};I1=La;U.VisibleString=I1;La.NAME="VisibleString";var C1,Zf=class extends ct{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};C1=Zf;U.GeneralString=C1;Zf.NAME="GeneralString";var k1,Xf=class extends ct{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};k1=Xf;U.CharacterString=k1;Xf.NAME="CharacterString";var T1,Na=class extends La{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,J.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=ht(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=ht(this.month,2),t[2]=ht(this.day,2),t[3]=ht(this.hour,2),t[4]=ht(this.minute,2),t[5]=ht(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};T1=Na;U.UTCTime=T1;Na.NAME="UTCTime";var B1,Jf=class extends Na{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let f=new Number(e[e.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=f*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*s;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(ht(this.year,4)),t.push(ht(this.month,2)),t.push(ht(this.day,2)),t.push(ht(this.hour,2)),t.push(ht(this.minute,2)),t.push(ht(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(ht(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};B1=Jf;U.GeneralizedTime=B1;Jf.NAME="GeneralizedTime";var P1,Qf=class extends en{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};P1=Qf;U.DATE=P1;Qf.NAME="DATE";var D1,ed=class extends en{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};D1=ed;U.TimeOfDay=D1;ed.NAME="TimeOfDay";var L1,td=class extends en{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};L1=td;U.DateTime=L1;td.NAME="DateTime";var N1,rd=class extends en{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};N1=rd;U.Duration=N1;rd.NAME="Duration";var R1,nd=class extends en{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};R1=nd;U.TIME=R1;nd.NAME="TIME";async function id(r,e){let n=await Vs.create().encrypt(r,e);return Ye.encode(n)}async function xg(r,e,t){if(r.type==="RSA")return nT(r,e,t);if(r.type==="Ed25519")return eT(r,e,t);if(r.type==="secp256k1")return tT(r,e,t);if(r.type==="ECDSA")return rT(r,e,t);throw new qt}async function eT(r,e,t="libp2p-key"){if(t==="libp2p-key")return id(Xn(r),e);throw new B(`export format '${t}' is not supported`)}async function tT(r,e,t="libp2p-key"){if(t==="libp2p-key")return id(Xn(r),e);throw new B("Export format is not supported")}async function rT(r,e,t="libp2p-key"){if(t==="libp2p-key")return id(Xn(r),e);throw new B(`export format '${t}' is not supported`)}async function nT(r,e,t="pkcs-8"){if(t==="pkcs-8")return oT(r,e);if(t==="libp2p-key")return id(Xn(r),e);throw new B("Export format is not supported")}async function oT(r,e){let t=Ae.get(),o=new pt({value:[new Qr({value:0}),new pt({value:[new Ir({value:"1.2.840.113549.1.1.1"}),new So]}),new Jr({valueHex:r.raw})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=Jt(16),a=await Mc(fs,e,i,{c:1e4,dkLen:32}),c=Jt(16),l=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),u=await t.subtle.encrypt({name:"AES-CBC",iv:c},l,s),f=new pt({value:[new Jr({valueHex:i}),new Qr({value:1e4}),new Qr({value:32}),new pt({value:[new Ir({value:"1.2.840.113549.2.11"}),new So]})]}),d=new pt({value:[new Ir({value:"1.2.840.113549.1.5.13"}),new pt({value:[new pt({value:[new Ir({value:"1.2.840.113549.1.5.12"}),f]}),new pt({value:[new Ir({value:"2.16.840.1.101.3.4.1.42"}),new Jr({valueHex:c})]})]})]}),p=new pt({value:[d,new Jr({valueHex:u})]}).toBER(),m=new Uint8Array(p,0,p.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...O(m,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
37
- `)}async function vg(r,e){try{let t=await sT(r,e);return R0(t)}catch{}if(!r.includes("BEGIN"))throw new B("Encrypted key was not a libp2p-key or a PEM file");return iT(r,e)}async function sT(r,e){let t=Ye.decode(r);return Vs.create().decrypt(t,e)}async function iT(r,e){let t=Ae.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let s=T(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=sd(s),{iv:a,salt:c,iterations:l,keySize:u,cipherText:f}=aT(i),d=await Mc(fs,e,c,{c:l,dkLen:u}),h=await t.subtle.importKey("raw",d,"AES-CBC",!1,["decrypt"]),p=Ra(await t.subtle.decrypt({name:"AES-CBC",iv:a},h,f)),{result:m}=sd(p);n=F1(m)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let s=T(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=sd(s);n=F1(i)}else throw new B("Could not parse private key from PEM data");let o=O0(n);if(o.type!=="RSA")throw new B("Could not parse RSA private key from PEM data");return o}function aT(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new B("Only pkcs5PBES2 encrypted private keys are supported");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new B("Only pkcs5PBKDF2 key derivation functions are supported");let s=n.valueBlock.value[1],i=Ra(s.valueBlock.value[0].getValue()),a=1e4,c=32;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new B("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key");let l=e.valueBlock.value[1].valueBlock.value[1],u=l.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new B("Only AES-CBC encryption schemes are supported")}}}}let f=Ra(l.valueBlock.value[1].getValue());return{cipherText:Ra(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:f}}function F1(r){return Ra(r.valueBlock.value[2].getValue())}function Ra(r){return new Uint8Array(r,0,r.byteLength)}var cT="/pkcs8/",Ag="/info/",Oa=new WeakMap,_o={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3},Eg={dek:{keyLength:512/8,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function Hs(r){return r==null||typeof r!="string"?!1:r===(0,V1.default)(r.trim())&&r.length>0}async function He(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function Io(r){return new me(cT+r)}function qs(r){return new me(Ag+r)}async function lT(r){let e=Xn(r),t=await Yt.digest(e);return ie.encode(t.bytes).substring(1)}var ad=class{components;init;log;self;constructor(e,t){if(this.components=e,this.log=e.logger.forComponent("libp2p:keychain"),this.init=Rs(Eg,t),this.self=t.selfKey??"self",this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLength<_o.minKeyLength)throw new Error(`dek.keyLength must be least ${_o.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<_o.minSaltLength)throw new Error(`dek.saltLength must be least ${_o.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<_o.minIterationCount)throw new Error(`dek.iterationCount must be least ${_o.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?Ni(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Oa.set(this,{dek:n})}[Symbol.toStringTag]="@libp2p/keychain";[Nn]=["@libp2p/keychain"];static generateOptions(){let e=Object.assign({},Eg),t=Math.ceil(_o.minSaltLength/3)*3;return e.dek.salt=O(Jt(t),"base64"),e}static get options(){return Eg}async findKeyByName(e){if(!Hs(e))throw await He(),new B(`Invalid key name '${e}'`);let t=qs(e);try{let n=await this.components.datastore.get(t);return JSON.parse(O(n))}catch(n){throw await He(),this.log.error(n),new Ie(`Key '${e}' does not exist.`)}}async findKeyById(e){try{let t={prefix:Ag};for await(let n of this.components.datastore.query(t)){let o=JSON.parse(O(n.value));if(o.id===e)return o}throw new B(`Key with id '${e}' does not exist.`)}catch(t){throw await He(),t}}async importKey(e,t){if(!Hs(e))throw await He(),new B(`Invalid key name '${e}'`);if(t==null)throw await He(),new B("Key is required");let n=Io(e);if(await this.components.datastore.has(n))throw await He(),new B(`Key '${e}' already exists`);let s,i;try{s=await lT(t);let l=Oa.get(this);if(l==null)throw new B("dek missing");let u=l.dek;i=await xg(t,u,t.type==="RSA"?"pkcs-8":"libp2p-key")}catch(l){throw await He(),l}let a={name:e,id:s},c=this.components.datastore.batch();return c.put(n,T(i)),c.put(qs(e),T(JSON.stringify(a))),await c.commit(),a}async exportKey(e){if(!Hs(e))throw await He(),new B(`Invalid key name '${e}'`);let t=Io(e);try{let n=await this.components.datastore.get(t),o=O(n),s=Oa.get(this);if(s==null)throw new B("dek missing");let i=s.dek;return await vg(o,i)}catch(n){throw await He(),n}}async removeKey(e){if(!Hs(e)||e===this.self)throw await He(),new B(`Invalid key name '${e}'`);let t=Io(e),n=await this.findKeyByName(e),o=this.components.datastore.batch();return o.delete(t),o.delete(qs(e)),await o.commit(),n}async listKeys(){let e={prefix:Ag},t=[];for await(let n of this.components.datastore.query(e))t.push(JSON.parse(O(n.value)));return t}async renameKey(e,t){if(!Hs(e)||e===this.self)throw await He(),new B(`Invalid old key name '${e}'`);if(!Hs(t)||t===this.self)throw await He(),new B(`Invalid new key name '${t}'`);let n=Io(e),o=Io(t),s=qs(e),i=qs(t);if(await this.components.datastore.has(o))throw await He(),new B(`Key '${t}' already exists`);try{let c=await this.components.datastore.get(n),l=await this.components.datastore.get(s),u=JSON.parse(O(l));u.name=t;let f=this.components.datastore.batch();return f.put(o,c),f.put(i,T(JSON.stringify(u))),f.delete(n),f.delete(s),await f.commit(),u}catch(c){throw await He(),c}}async rotateKeychainPass(e,t){if(typeof e!="string")throw await He(),new B(`Invalid old pass type '${typeof e}'`);if(typeof t!="string")throw await He(),new B(`Invalid new pass type '${typeof t}'`);if(t.length<20)throw await He(),new B(`Invalid pass length ${t.length}`);this.log("recreating keychain");let n=Oa.get(this);if(n==null)throw new B("dek missing");let o=n.dek;this.init.pass=t;let s=t!=null&&this.init.dek?.salt!=null?Ni(t,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Oa.set(this,{dek:s});let i=await this.listKeys();for(let a of i){let c=await this.components.datastore.get(Io(a.name)),l=O(c),u=await vg(l,o),f=s.toString(),d=await xg(u,f,u.type==="RSA"?"pkcs-8":"libp2p-key"),h=this.components.datastore.batch(),p={name:a.name,id:a.id};h.put(Io(a.name),T(d)),h.put(qs(a.name),T(JSON.stringify(p))),await h.commit()}this.log("keychain reconstructed")}};function cd(r={}){return e=>new ad(e,r)}async function Sg(r,e={}){let t=e.selfKey??"self",n=cd(e)({datastore:r,logger:vn()}),o;return await r.has(new me(`/pkcs8/${t}`))?o=await n.exportKey(t):(o=await Nc(e.keyType??"Ed25519"),await n.importKey(t,o)),o}function K1(r={}){let e=`@helia/http ${pf()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:[]},transports:[],connectionEncrypters:[],streamMuxers:[],peerDiscovery:[],services:{delegatedRouting:()=>Rx("https://delegated-ipfs.dev",{filterAddrs:["https"],filterProtocols:["transport-ipfs-gateway-http"]}),keychain:cd(r.keychain)}}}async function $1(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await Sg(r.datastore,r.keychain));let t=K1(e);return t.datastore=t.datastore??r.datastore,await Vv({...t,...e,start:!1})}async function H1(r={}){let e=r.datastore??new mo,t=r.blockstore??new ha,n;return Kv(r.libp2p)?n=r.libp2p:n=await $1({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Cm()],routers:r.routers??[Vm(n),Um()],metrics:n.metrics}}async function uT(r={}){let e=await H1(r),t=new Ml(e);return e.start!==!1&&await t.start(),t}return Y1(fT);})();
33
+ `)}`:`${t} :`}};VE=xn;U.Constructed=VE;xn.NAME="CONSTRUCTED";var Pf=class extends ot{fromBER(e,t,n){return t}toBER(e){return nr}};Pf.override="EndOfContentValueBlock";var KE,Bf=class extends je{constructor(e={}){super(e,Pf),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};KE=Bf;U.EndOfContent=KE;Bf.NAME=ka;var HE,go=class extends je{constructor(e={}){super(e,ot),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};HE=go;U.Null=HE;go.NAME="NULL";var Df=class extends Gr(ot){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=ne.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,n){let o=ne.BufferSourceConverter.toUint8Array(e);return zr(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Mg.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Df.NAME="BooleanValueBlock";var qE,Lf=class extends je{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,Df),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};qE=Lf;U.Boolean=qE;Lf.NAME="BOOLEAN";var Nf=class extends Gr(wr){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=wr.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===ka){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==ME)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?wr.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Nf.NAME="OctetStringValueBlock";var $g,Kr=class extends je{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Nf),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=ld(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return xn.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,t=ne.Convert.ToHex(this.valueBlock.valueHexView);return`${e} : ${t}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof $g&&e.push(t.valueBlock.valueHexView);return ne.BufferSourceConverter.concat(e)}};$g=Kr;U.OctetString=$g;Kr.NAME=ME;var Rf=class extends Gr(wr){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=wr.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===ka){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==UE)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let s=ne.BufferSourceConverter.toUint8Array(e);if(!zr(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=ld(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return wr.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return nr;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Rf.NAME="BitStringValueBlock";var zE,Of=class extends je{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Rf),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return xn.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let i of t)e.push(i.toString(2).padStart(8,"0"));let n=e.join(""),o=this.constructor.NAME,s=n.substring(0,n.length-this.valueBlock.unusedBits);return`${o} : ${s}`}}};zE=Of;U.BitString=zE;Of.NAME=UE;var GE;function c6(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<i?i:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=s[i-f]+a[c-f]+t[0];break;default:l=s[i-f]+t[0]}switch(t[0]=l/10,!0){case f>=s.length:s=Sf(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return t[0]>0&&(s=Sf(t,s)),s}function OE(r){if(r>=Ca.length)for(let e=Ca.length;e<=r;e++){let t=new Uint8Array([0]),n=Ca[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=Sf(t,n)),Ca.push(n)}return Ca[r]}function l6(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=s[i-u]-a[c-u]-t,!0){case l<0:t=1,s[i-u]=l+10;break;default:t=0,s[i-u]=l}if(t>0)for(let f=i-c+1;f>=0;f--,u++)if(l=s[i-u]-t,l<0)t=1,s[i-u]=l+10;else{t=0,s[i-u]=l;break}return s.slice()}var Pa=class extends Gr(ot){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Mg.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(LE(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&(i[1]&128)!==0?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=l6(OE(n),t),i="-";break;default:t=c6(t,OE(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=RE.charAt(t[c]));return a===!1&&(i+=RE.charAt(0)),i}};GE=Pa;Pa.NAME="IntegerValueBlock";Object.defineProperty(GE.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var _a,Hr=class extends je{constructor(e={}){super(e,Pa),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Af(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Af();let t=BigInt(e),n=new Ta,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(ne.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${ne.Convert.ToHex(a)}`)+t,u=ne.BufferSourceConverter.toUint8Array(ne.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new _a({valueHex:n.final()})}convertToDER(){let e=new _a({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new _a({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};_a=Hr;U.Integer=_a;Hr.NAME="INTEGER";var WE,Mf=class extends Hr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};WE=Mf;U.Enumerated=WE;Mf.NAME="ENUMERATED";var Ba=class extends Gr(ot){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=ne.BufferSourceConverter.toUint8Array(e);if(!zr(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=mo(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Af();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=bn(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",nr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=ne.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Ba.NAME="sidBlock";var Uf=class extends ot{constructor({value:e=Ls,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Ba;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,nr;t.push(o)}return Ug(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Ba;if(o>Number.MAX_SAFE_INTEGER){Af();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Uf.NAME="ObjectIdentifierValueBlock";var jE,br=class extends je{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Uf),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};jE=br;U.ObjectIdentifier=jE;br.NAME="OBJECT IDENTIFIER";var Da=class extends Gr(Vr){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=ne.BufferSourceConverter.toUint8Array(e);if(!zr(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=mo(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=bn(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",nr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=ne.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Da.NAME="relativeSidBlock";var Ff=class extends ot{constructor({value:e=Ls,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Da;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,nr;n.push(s)}return Ug(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Da;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Ff.NAME="RelativeObjectIdentifierValueBlock";var YE,$f=class extends je{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Ff),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};YE=$f;U.RelativeObjectIdentifier=YE;$f.NAME="RelativeObjectIdentifier";var ZE,pt=class extends xn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};ZE=pt;U.Sequence=ZE;pt.NAME="SEQUENCE";var XE,Vf=class extends xn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};XE=Vf;U.Set=XE;Vf.NAME="SET";var Kf=class extends Gr(ot){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Ls}toJSON(){return{...super.toJSON(),value:this.value}}};Kf.NAME="StringValueBlock";var Hf=class extends Kf{};Hf.NAME="SimpleStringValueBlock";var lt=class extends _f{constructor({...e}={}){super(e,Hf)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,ne.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};lt.NAME="SIMPLE STRING";var qf=class extends lt{fromBuffer(e){this.valueBlock.valueHexView=ne.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=ne.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=ne.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(ne.Convert.FromUtf8String(e)),this.valueBlock.value=e}};qf.NAME="Utf8StringValueBlock";var JE,qr=class extends qf{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};JE=qr;U.Utf8String=JE;qr.NAME="UTF8String";var zf=class extends lt{fromBuffer(e){this.valueBlock.value=ne.Convert.ToUtf16String(e),this.valueBlock.valueHexView=ne.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(ne.Convert.FromUtf16String(e))}};zf.NAME="BmpStringValueBlock";var QE,Gf=class extends zf{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};QE=Gf;U.BmpString=QE;Gf.NAME="BMPString";var Wf=class extends lt{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=bn(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};Wf.NAME="UniversalStringValueBlock";var e1,jf=class extends Wf{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};e1=jf;U.UniversalString=e1;jf.NAME="UniversalString";var t1,Yf=class extends lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};t1=Yf;U.NumericString=t1;Yf.NAME="NumericString";var r1,Zf=class extends lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};r1=Zf;U.PrintableString=r1;Zf.NAME="PrintableString";var n1,Xf=class extends lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};n1=Xf;U.TeletexString=n1;Xf.NAME="TeletexString";var o1,Jf=class extends lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};o1=Jf;U.VideotexString=o1;Jf.NAME="VideotexString";var s1,Qf=class extends lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};s1=Qf;U.IA5String=s1;Qf.NAME="IA5String";var i1,ed=class extends lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};i1=ed;U.GraphicString=i1;ed.NAME="GraphicString";var a1,La=class extends lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};a1=La;U.VisibleString=a1;La.NAME="VisibleString";var c1,td=class extends lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};c1=td;U.GeneralString=c1;td.NAME="GeneralString";var l1,rd=class extends lt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};l1=rd;U.CharacterString=l1;rd.NAME="CharacterString";var u1,Na=class extends La{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,ne.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=ht(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=ht(this.month,2),t[2]=ht(this.day,2),t[3]=ht(this.hour,2),t[4]=ht(this.minute,2),t[5]=ht(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};u1=Na;U.UTCTime=u1;Na.NAME="UTCTime";var f1,nd=class extends Na{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let f=new Number(e[e.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let m=parseInt(h.substring(0,2),10);if(isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*m,h.length===4){if(m=parseInt(h.substring(2,4),10),isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");c=f*m}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*s;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(ht(this.year,4)),t.push(ht(this.month,2)),t.push(ht(this.day,2)),t.push(ht(this.hour,2)),t.push(ht(this.minute,2)),t.push(ht(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(ht(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};f1=nd;U.GeneralizedTime=f1;nd.NAME="GeneralizedTime";var d1,od=class extends qr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};d1=od;U.DATE=d1;od.NAME="DATE";var h1,sd=class extends qr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};h1=sd;U.TimeOfDay=h1;sd.NAME="TimeOfDay";var p1,id=class extends qr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};p1=id;U.DateTime=p1;id.NAME="DateTime";var m1,ad=class extends qr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};m1=ad;U.Duration=m1;ad.NAME="Duration";var g1,cd=class extends qr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};g1=cd;U.TIME=g1;cd.NAME="TIME";async function fd(r,e){let n=await Bs.create().encrypt(r,e);return Pe.encode(n)}async function Vg(r,e,t){if(r.type==="RSA")return h6(r,e,t);if(r.type==="Ed25519")return u6(r,e,t);if(r.type==="secp256k1")return f6(r,e,t);if(r.type==="ECDSA")return d6(r,e,t);throw new Ot}async function u6(r,e,t="libp2p-key"){if(t==="libp2p-key")return fd($n(r),e);throw new C(`export format '${t}' is not supported`)}async function f6(r,e,t="libp2p-key"){if(t==="libp2p-key")return fd($n(r),e);throw new C("Export format is not supported")}async function d6(r,e,t="libp2p-key"){if(t==="libp2p-key")return fd($n(r),e);throw new C(`export format '${t}' is not supported`)}async function h6(r,e,t="pkcs-8"){if(t==="pkcs-8")return p6(r,e);if(t==="libp2p-key")return fd($n(r),e);throw new C("Export format is not supported")}async function p6(r,e){let t=Te.get(),o=new pt({value:[new Hr({value:0}),new pt({value:[new br({value:"1.2.840.113549.1.1.1"}),new go]}),new Kr({valueHex:r.raw})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=Kt(16),a=await gc(en,e,i,{c:1e4,dkLen:32}),c=Kt(16),l=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),u=await t.subtle.encrypt({name:"AES-CBC",iv:c},l,s),f=new pt({value:[new Kr({valueHex:i}),new Hr({value:1e4}),new Hr({value:32}),new pt({value:[new br({value:"1.2.840.113549.2.11"}),new go]})]}),d=new pt({value:[new br({value:"1.2.840.113549.1.5.13"}),new pt({value:[new pt({value:[new br({value:"1.2.840.113549.1.5.12"}),f]}),new pt({value:[new br({value:"2.16.840.1.101.3.4.1.42"}),new Kr({valueHex:c})]})]})]}),m=new pt({value:[d,new Kr({valueHex:u})]}).toBER(),g=new Uint8Array(m,0,m.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...B(g,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
34
+ `)}async function Kg(r,e){try{let t=await m6(r,e);return ew(t)}catch{}if(!r.includes("BEGIN"))throw new C("Encrypted key was not a libp2p-key or a PEM file");return g6(r,e)}async function m6(r,e){let t=Pe.decode(r);return Bs.create().decrypt(t,e)}async function g6(r,e){let t=Te.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let s=T(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=ud(s),{iv:a,salt:c,iterations:l,keySize:u,cipherText:f}=y6(i),d=await gc(en,e,c,{c:l,dkLen:u}),h=await t.subtle.importKey("raw",d,"AES-CBC",!1,["decrypt"]),m=Ra(await t.subtle.decrypt({name:"AES-CBC",iv:a},h,f)),{result:g}=ud(m);n=x1(g)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let s=T(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=ud(s);n=x1(i)}else throw new C("Could not parse private key from PEM data");let o=tw(n);if(o.type!=="RSA")throw new C("Could not parse RSA private key from PEM data");return o}function y6(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new C("Only pkcs5PBES2 encrypted private keys are supported");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new C("Only pkcs5PBKDF2 key derivation functions are supported");let s=n.valueBlock.value[1],i=Ra(s.valueBlock.value[0].getValue()),a=1e4,c=32;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new C("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key");let l=e.valueBlock.value[1].valueBlock.value[1],u=l.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new C("Only AES-CBC encryption schemes are supported")}}}}let f=Ra(l.valueBlock.value[1].getValue());return{cipherText:Ra(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:f}}function x1(r){return Ra(r.valueBlock.value[2].getValue())}function Ra(r){return new Uint8Array(r,0,r.byteLength)}var w6="/pkcs8/",Hg="/info/",Oa=new WeakMap,yo={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3};function Ns(r){return r==null||typeof r!="string"?!1:r===(0,v1.default)(r.trim())&&r.length>0}async function Ye(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function wo(r){return new xe(w6+r)}function Rs(r){return new xe(Hg+r)}async function b6(r){let e=$n(r),t=await gt.digest(e);return ee.encode(t.bytes).substring(1)}var dd=class{components;init;log;self;constructor(e,t){if(this.components=e,this.log=e.logger.forComponent("libp2p:keychain"),this.init={...t,dek:{...Rg,...t.dek}},this.self=t.selfKey??"self",this.init.pass!=null&&this.init.pass?.length<20)throw new Error("pass must be least 20 characters");if(this.init.dek?.keyLength!=null&&this.init.dek.keyLength<yo.minKeyLength)throw new Error(`dek.keyLength must be least ${yo.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<yo.minSaltLength)throw new Error(`dek.saltLength must be least ${yo.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<yo.minIterationCount)throw new Error(`dek.iterationCount must be least ${yo.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?yi(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Oa.set(this,{dek:n})}[Symbol.toStringTag]="@libp2p/keychain";[Sn]=["@libp2p/keychain"];static generateOptions(){let e=Object.assign({},this.options),t=Math.ceil(yo.minSaltLength/3)*3;return e.dek!=null&&(e.dek.salt=B(Kt(t),"base64")),e}static get options(){return{dek:{...Rg}}}async findKeyByName(e){if(!Ns(e))throw await Ye(),new C(`Invalid key name '${e}'`);let t=Rs(e);try{let n=await this.components.datastore.get(t);return JSON.parse(B(n))}catch(n){throw await Ye(),this.log.error("could not read key from datastore - %e",n),new Rt(`Key '${e}' does not exist.`)}}async findKeyById(e){try{let t={prefix:Hg};for await(let n of this.components.datastore.query(t)){let o=JSON.parse(B(n.value));if(o.id===e)return o}throw new C(`Key with id '${e}' does not exist.`)}catch(t){throw await Ye(),t}}async importKey(e,t){if(!Ns(e))throw await Ye(),new C(`Invalid key name '${e}'`);if(t==null)throw await Ye(),new C("Key is required");let n=wo(e);if(await this.components.datastore.has(n))throw await Ye(),new C(`Key '${e}' already exists`);let s,i;try{s=await b6(t);let l=Oa.get(this);if(l==null)throw new C("dek missing");let u=l.dek;i=await Vg(t,u,t.type==="RSA"?"pkcs-8":"libp2p-key")}catch(l){throw await Ye(),l}let a={name:e,id:s},c=this.components.datastore.batch();return c.put(n,T(i)),c.put(Rs(e),T(JSON.stringify(a))),await c.commit(),a}async exportKey(e){if(!Ns(e))throw await Ye(),new C(`Invalid key name '${e}'`);let t=wo(e);try{let n=await this.components.datastore.get(t),o=B(n),s=Oa.get(this);if(s==null)throw new C("dek missing");let i=s.dek;return await Kg(o,i)}catch(n){throw await Ye(),n}}async removeKey(e){if(!Ns(e)||e===this.self)throw await Ye(),new C(`Invalid key name '${e}'`);let t=wo(e),n=await this.findKeyByName(e),o=this.components.datastore.batch();return o.delete(t),o.delete(Rs(e)),await o.commit(),n}async listKeys(){let e={prefix:Hg},t=[];for await(let n of this.components.datastore.query(e))t.push(JSON.parse(B(n.value)));return t}async renameKey(e,t){if(!Ns(e)||e===this.self)throw await Ye(),new C(`Invalid old key name '${e}'`);if(!Ns(t)||t===this.self)throw await Ye(),new C(`Invalid new key name '${t}'`);let n=wo(e),o=wo(t),s=Rs(e),i=Rs(t);if(await this.components.datastore.has(o))throw await Ye(),new C(`Key '${t}' already exists`);try{let c=await this.components.datastore.get(n),l=await this.components.datastore.get(s),u=JSON.parse(B(l));u.name=t;let f=this.components.datastore.batch();return f.put(o,c),f.put(i,T(JSON.stringify(u))),f.delete(n),f.delete(s),await f.commit(),u}catch(c){throw await Ye(),c}}async rotateKeychainPass(e,t){if(typeof e!="string")throw await Ye(),new C(`Invalid old pass type '${typeof e}'`);if(typeof t!="string")throw await Ye(),new C(`Invalid new pass type '${typeof t}'`);if(t.length<20)throw await Ye(),new C(`Invalid pass length ${t.length}`);this.log("recreating keychain");let n=Oa.get(this);if(n==null)throw new C("dek missing");let o=n.dek;this.init.pass=t;let s=t!=null&&this.init.dek?.salt!=null?yi(t,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";Oa.set(this,{dek:s});let i=await this.listKeys();for(let a of i){let c=await this.components.datastore.get(wo(a.name)),l=B(c),u=await Kg(l,o),f=s.toString(),d=await Vg(u,f,u.type==="RSA"?"pkcs-8":"libp2p-key"),h=this.components.datastore.batch(),m={name:a.name,id:a.id};h.put(wo(a.name),T(d)),h.put(Rs(a.name),T(JSON.stringify(m))),await h.commit()}this.log("keychain reconstructed")}};function hd(r={}){return e=>new dd(e,r)}async function qg(r,e={}){let t=e.selfKey??"self",n=hd(e)({datastore:r,logger:pn()}),o;return await r.has(new xe(`/pkcs8/${t}`))?o=await n.exportKey(t):(o=await mc(e.keyType??"Ed25519"),await n.importKey(t,o)),o}function E1(r={}){let e=`@helia/http ${bf()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:[]},transports:[],connectionEncrypters:[],streamMuxers:[],peerDiscovery:[],services:{delegatedRouting:()=>kv("https://delegated-ipfs.dev",{filterAddrs:["https"],filterProtocols:["transport-ipfs-gateway-http"]}),keychain:hd(r.keychain)}}}async function S1(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await qg(r.datastore,r.keychain));let t=E1(e);return t.datastore=t.datastore??r.datastore,await vE({...t,...e,start:!1})}async function A1(r={}){let e=r.datastore??new fo,t=r.blockstore??new ma,n;return EE(r.libp2p)?n=r.libp2p:n=await S1({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Um()],routers:r.routers??[hg(n),fg()],metrics:n.metrics}}async function x6(r={}){let e=await A1(r),t=new Wl(e);return e.start!==!1&&await t.start(),t}return P1(v6);})();
38
35
  /*! Bundled license information:
39
36
 
40
37
  pvtsutils/build/index.js:
@@ -63,17 +60,16 @@ pvtsutils/build/index.js:
63
60
  *
64
61
  *)
65
62
 
66
- @noble/hashes/esm/utils.js:
63
+ @noble/hashes/utils.js:
67
64
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
68
65
 
69
- @noble/curves/esm/utils.js:
70
- @noble/curves/esm/abstract/modular.js:
71
- @noble/curves/esm/abstract/curve.js:
72
- @noble/curves/esm/abstract/edwards.js:
73
- @noble/curves/esm/ed25519.js:
74
- @noble/curves/esm/abstract/weierstrass.js:
75
- @noble/curves/esm/_shortw_utils.js:
76
- @noble/curves/esm/secp256k1.js:
66
+ @noble/curves/utils.js:
67
+ @noble/curves/abstract/modular.js:
68
+ @noble/curves/abstract/curve.js:
69
+ @noble/curves/abstract/edwards.js:
70
+ @noble/curves/ed25519.js:
71
+ @noble/curves/abstract/weierstrass.js:
72
+ @noble/curves/secp256k1.js:
77
73
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
78
74
 
79
75
  pvutils/build/utils.es.js: