@helia/verified-fetch 7.2.15 → 7.2.16

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,6 +1,6 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaVerifiedFetch = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var HeliaVerifiedFetch=(()=>{var gF=Object.create;var Sp=Object.defineProperty;var yF=Object.getOwnPropertyDescriptor;var wF=Object.getOwnPropertyNames;var bF=Object.getPrototypeOf,xF=Object.prototype.hasOwnProperty;var $=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),xt=(r,e)=>{for(var t in e)Sp(r,t,{get:e[t],enumerable:!0})},qx=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wF(e))!xF.call(r,o)&&o!==t&&Sp(r,o,{get:()=>e[o],enumerable:!(n=yF(e,o))||n.enumerable});return r};var Yt=(r,e,t)=>(t=r!=null?gF(bF(r)):{},qx(e||!r||!r.__esModule?Sp(t,"default",{value:r,enumerable:!0}):t,r)),EF=r=>qx(Sp({},"__esModule",{value:!0}),r);var k8=$(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});pl.Netmask4Impl=void 0;pl.ip2long=hl;pl.long2ip=Fo;function Fo(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var mH=48,gH=97,yH=65;function wH(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let i=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-mH)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-gH)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-yH)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===i)throw new Error("empty octet");return[e,o]}function hl(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=wH(r);r=r.substring(o),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var I8=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=hl(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(hl(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Fo(this.netLong),this.mask=Fo(this.maskLong),this.hostmask=Fo(~this.maskLong),this.first=this.bitmask<=30?Fo(this.netLong+1):this.base,this.last=this.bitmask<=30?Fo(this.netLong+this.size-2):Fo(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Fo(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(hl(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(Fo(this.netLong+this.size*e),this.mask)}forEach(e){let t=hl(this.first),n=hl(this.last),o=0;for(;t<=n;)e(Fo(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};pl.Netmask4Impl=I8});var CS=$(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});ml.Netmask6Impl=void 0;ml.ip6bigint=P8;ml.bigint2ip6=Na;var bH=k8(),R8=(1n<<128n)-1n;function P8(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),o=(0,bH.ip2long)(n),i=r.substring(0,t+1)+"0:0";return _S(i)&~0xffffffffn|BigInt(o)}return _S(r)}function _S(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),i=r.substring(e+2),s=o===""?[]:o.split(":"),a=i===""?[]:i.split(":"),c=8-s.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...s,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let o=0;o<8;o++){let i=t[o];if(i.length===0||i.length>4)throw new Error('Invalid IPv6: bad group "'+i+'"');let s=parseInt(i,16);if(isNaN(s)||s<0||s>65535)throw new Error('Invalid IPv6: bad group "'+i+'"');n=n<<16n|BigInt(s)}return n}function Na(r){if(r<0n||r>R8)throw new Error("Invalid IPv6 address value");let e=[];for(let s=0;s<8;s++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,o=-1,i=0;for(let s=0;s<8;s++)e[s]===0?o===-1?(o=s,i=1):i++:(i>n&&i>=2&&(t=o,n=i),o=-1,i=0);if(i>n&&i>=2&&(t=o,n=i),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let s=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return s.join(":")+"::"+a.join(":")}else return e.map(s=>s.toString(16)).join(":")}var D8=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=R8>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=P8(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=Na(this.netBigint),this.mask=Na(this.maskBigint),this.hostmask=Na(~this.maskBigint&R8),this.first=this.base,this.last=Na(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(P8(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(Na(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,i=0;for(;t<=o;)e(Na(t),Number(t),i),i++,t++}toString(){return this.base+"/"+this.bitmask}};ml.Netmask6Impl=D8});var IS=$(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.long2ip=us.ip2long=us.Netmask=void 0;var bm=k8();Object.defineProperty(us,"ip2long",{enumerable:!0,get:function(){return bm.ip2long}});Object.defineProperty(us,"long2ip",{enumerable:!0,get:function(){return bm.long2ip}});var xH=CS(),L8=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new xH.Netmask6Impl(e,t):this._impl=new bm.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof bm.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};us.Netmask=L8});var BT=$((Yme,G5)=>{"use strict";var hK=Object.prototype.hasOwnProperty,Nr="~";function bf(){}Object.create&&(bf.prototype=Object.create(null),new bf().__proto__||(Nr=!1));function pK(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function OT(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new pK(t,n||r,o),s=Nr?Nr+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],i]:r._events[s].push(i):(r._events[s]=i,r._eventsCount++),r}function T1(r,e){--r._eventsCount===0?r._events=new bf:delete r._events[e]}function gr(){this._events=new bf,this._eventsCount=0}gr.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)hK.call(t,n)&&e.push(Nr?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};gr.prototype.listeners=function(e){var t=Nr?Nr+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,s=new Array(i);o<i;o++)s[o]=n[o].fn;return s};gr.prototype.listenerCount=function(e){var t=Nr?Nr+e:e,n=this._events[t];return n?n.fn?1:n.length:0};gr.prototype.emit=function(e,t,n,o,i,s){var a=Nr?Nr+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,d;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,i),!0;case 6:return c.fn.call(c.context,t,n,o,i,s),!0}for(d=1,u=new Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,h;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].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[d].fn.apply(c[d].context,u)}}return!0};gr.prototype.on=function(e,t,n){return OT(this,e,t,n,!1)};gr.prototype.once=function(e,t,n){return OT(this,e,t,n,!0)};gr.prototype.removeListener=function(e,t,n,o){var i=Nr?Nr+e:e;if(!this._events[i])return this;if(!t)return T1(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&T1(this,i);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==t||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:T1(this,i)}return this};gr.prototype.removeAllListeners=function(e){var t;return e?(t=Nr?Nr+e:e,this._events[t]&&T1(this,t)):(this._events=new bf,this._eventsCount=0),this};gr.prototype.off=gr.prototype.removeListener;gr.prototype.addListener=gr.prototype.on;gr.prefixed=Nr;gr.EventEmitter=gr;typeof G5<"u"&&(G5.exports=gr)});var UT=$((y1e,FT)=>{FT.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(i,s){t[i]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=t[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){t[i]!==void 0?t[i]=s:o(i,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var v0=$((uye,Dw)=>{var lye=(function(){typeof Dw<"u"&&(Dw.exports=y);var r=86400,e=3200,t=146097*e/400,n=r*t,o=1e3*n,i=864e13,s=4294967296,a=1e6,c="000000000",l=Math.trunc||function(C){var L=C-C%1;return L==0&&(C<0||C===0&&1/C!=1/0)?-0:L},u=y.prototype,d=(y.fromDate=function(C){return new y(+C)},y.fromInt64BE=R(0,1,2,3,0,4),y.fromInt64LE=R(3,2,1,0,4,0),y.fromString=function(M){var L,H=new y,M=(M+="").replace(/^\s*[+\-]?\d+/,function(A){var A=+A,T=1970+(A-1970)%400;return H.year=A-T,T}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function(x,A,T){return A<0&&(T*=-1),L=6e4*(60*+A+ +T),""}).replace(/\.\d+$/,function(x){return H.nano=+(x+c).substr(1,9),""}).split(/\D+/);if(1<M.length?M[1]--:M[1]=0,H.time=L=Date.UTC.apply(Date,M)-(L||0),isNaN(L))throw new TypeError("Invalid Date");return g(H)},y.fromTimeT=function(C){return b(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=g(this);return(C.time%1e3*a+ +C.nano+1e9)%1e9},u.getTimeT=function(){var L=g(this),C=Math.floor(L.time/1e3),L=L.year;return L&&(C+=L*t*r/e),C},u.getYear=function(){return this.toDate().getUTCFullYear()+this.year},u.toDate=function(){return m(g(this).time)},u.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},u.toString=function(C){var L=this,H=L.toDate(),M={H:function(){return O(H.getUTCHours())},L:function(){return U(H.getUTCMilliseconds(),3)},M:function(){return O(H.getUTCMinutes())},N:function(){return U(L.getNano(),9)},S:function(){return O(H.getUTCSeconds())},Y:function(){var x=L.getYear();return 999999<x?"+"+x:9999<x?"+"+U(x,6):0<=x?U(x,4):-999999<=x?"-"+U(-x,6):x},a:function(){return h[H.getUTCDay()]},b:function(){return f[H.getUTCMonth()]},d:function(){return O(H.getUTCDate())},e:function(){return(function(x){return(9<x?"":" ")+(0|x)})(H.getUTCDate())},m:function(){return O(H.getUTCMonth()+1)}};return(function x(A){return A.replace(/%./g,function(T){var S=T[1],v=p[S],S=M[S];return v?x(v):S?S():T})})(C||d)},u.writeInt64BE=_(0,1,2,3,0,4),u.writeInt64LE=_(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),f=["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 y;function y(C,L,H){var M=this;if(!(M instanceof y))return new y(C,L,H);M.time=+C||0,M.nano=+L||0,M.year=+H||0,g(M)}function g(C){var L,H,M,x=C.year,A=C.time,T=C.nano,v=((T<0||a<=T)&&(T-=(H=Math.floor(T/a))*a,A+=H,H=1),x%e);return(A<-i||i<A||v)&&((L=l(A/o))&&(x+=L*e,A-=L*o),(M=m(A)).setUTCFullYear(v+M.getUTCFullYear()),M=(A=+M)+(L=l((x-=v)/e))*o,L&&-i<=M&&M<=i&&(x-=L*e,A=M),H=1),H&&(C.year=x,C.time=A,C.nano=T),C}function m(C){var L=new Date(0);return L.setTime(C),L}function b(x,M){x=+x||0;var H=l((M=(M|0)*s)/n)+l(x/n),M=M%n+x%n,x=l(M/n);return x&&(H+=x,M-=x*n),new y(1e3*M,0,H*e)}function _(C,L,H,M,x,A){return function(v,S){var B=g(this);v=v||new Array(8),D(v,S|=0);var I=Math.floor(B.time/1e3),B=B.year*(t*r/e),P=l(B/s)+l(I/s),B=B%s+I%s,I=Math.floor(B/s);return I&&(P+=I,B-=I*s),T(v,S+x,P),T(v,S+A,B),v};function T(v,S,P){v[S+C]=P>>24&255,v[S+L]=P>>16&255,v[S+H]=P>>8&255,v[S+M]=255&P}}function R(C,L,H,M,x,A){return function(v,S){D(v,S|=0);var P=T(v,S+x);return b(T(v,S+A),P)};function T(v,S){return 16777216*v[S+C]+(v[S+L]<<16|v[S+H]<<8|v[S+M])}}function D(C,L){if(C=C&&C.length,C==null)throw new TypeError("Invalid Buffer");if(C<L+8)throw new RangeError("Out of range")}function O(C){return(9<C?"":"0")+(0|C)}function U(C,L){return(c+(0|C)).substr(-L)}})()});var HC=$((U9e,$C)=>{"use strict";function zG(r){return r>=55296&&r<=56319}function GG(r){return r>=56320&&r<=57343}$C.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var o=t.length,i=0,s,a,c=0;c<o;c+=1){if(s=t.charCodeAt(c),a=t[c],zG(s)&&GG(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),i+=e(a),i===n)return t.slice(0,c+1);if(i>n)return t.slice(0,c-a.length+1)}return t}});var VC=$(($9e,qC)=>{"use strict";function WG(r){return r>=55296&&r<=56319}function jG(r){return r>=56320&&r<=57343}qC.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,o=null,i=null,s=0;s<t;s++)o=e.charCodeAt(s),jG(o)?i!=null&&WG(i)?n+=1:n+=3:o<=127?n+=1:o>=128&&o<=2047?n+=2:o>=2048&&o<=65535&&(n+=3),i=o;return n}});var zC=$((H9e,KC)=>{"use strict";var YG=HC(),XG=VC();KC.exports=YG.bind(null,XG)});var jC=$((q9e,WC)=>{"use strict";var QG=zC(),ZG=/[\/\?<>\\:\*\|"]/g,JG=/[\x00-\x1f\x80-\x9f]/g,eW=/^\.+$/,tW=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function rW(r,e){for(var t=r.length;t>0&&(r[t-1]==="."||r[t-1]===" ");)t--;return t<r.length?r.slice(0,t)+e:r}function GC(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(ZG,e).replace(JG,e).replace(eW,e).replace(tW,e);return t=rW(t,e),QG(t,255)}WC.exports=function(r,e){var t=e&&e.replacement||"",n=GC(r,t);return t===""?n:GC(n,"")}});var ZC=$(su=>{"use strict";var iW="[object ArrayBuffer]",Oi=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===iW}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 i=0;i<n.length;i++)if(n[i]!==o[i])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 s of t)n+=s.byteLength;let o=new Uint8Array(n),i=0;for(let s of t){let a=this.toUint8Array(s);o.set(a,i),i+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},u7="string",sW=/^[0-9a-f\s]+$/i,aW=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,cW=/^[a-zA-Z0-9-_]+$/,R2=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=Oi.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return decodeURIComponent(escape(n))}},Vn=class{static toString(e,t=!1){let n=Oi.toArrayBuffer(e),o=new DataView(n),i="";for(let s=0;s<n.byteLength;s+=2){let a=o.getUint16(s,t);i+=String.fromCharCode(a)}return i}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let i=0;i<e.length;i++)o.setUint16(i*2,e.charCodeAt(i),t);return n}},P2=class r{static isHex(e){return typeof e===u7&&sW.test(e)}static isBase64(e){return typeof e===u7&&aW.test(e)}static isBase64Url(e){return typeof e===u7&&cW.test(e)}static ToString(e,t="utf8"){let n=Oi.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 Vn.toString(n,!0);case"utf16":case"utf16be":return Vn.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 Vn.fromString(e,!0);case"utf16":case"utf16be":return Vn.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Oi.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 R2.fromString(e);case"utf16":case"utf16be":return Vn.fromString(e);case"utf16le":case"usc2":return Vn.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 R2.toString(e);case"utf16":case"utf16be":return Vn.toString(e);case"utf16le":case"usc2":return Vn.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=Oi.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Oi.toUint8Array(e),n="",o=t.length;for(let i=0;i<o;i++){let s=t[i];s<16&&(n+="0"),n+=s.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 i=t.slice(o,o+2);n[o/2]=parseInt(i,16)}return n.buffer}static ToUtf16String(e,t=!1){return Vn.toString(e,t)}static FromUtf16String(e,t=!1){return Vn.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,"")||""}};P2.DEFAULT_UTF8_ENCODING="utf8";function lW(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let i in o)t[i]=o[i]}return t}function uW(...r){let e=r.map(o=>o.byteLength).reduce((o,i)=>o+i),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let i of o)t[n++]=i}),t.buffer}function dW(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}su.BufferSourceConverter=Oi;su.Convert=P2;su.assign=lW;su.combine=uW;su.isEqual=dW});var IR=$(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.parseCookie=_R;ni.parse=_R;ni.stringifyCookie=Yj;ni.stringifySetCookie=c3;ni.serialize=c3;ni.parseSetCookie=Xj;ni.stringifySetCookie=c3;ni.serialize=c3;var AR=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,TR=/^[\u0021-\u003A\u003C-\u007E]*$/,Kj=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,zj=/^[\u0020-\u003A\u003D-\u007E]*$/,Gj=/^-?\d+$/,Wj=Object.prototype.toString,jj=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function _R(r,e){let t=new jj,n=r.length;if(n<2)return t;let o=e?.decode||CR,i=0;do{let s=mb(r,i,n);if(s===-1)break;let a=pb(r,i,n);if(s>a){i=r.lastIndexOf(";",s-1)+1;continue}let c=Bs(r,i,s);t[c]===void 0&&(t[c]=o(Bs(r,s+1,a))),i=a+1}while(i<n);return t}function Yj(r,e){let t=e?.encode||encodeURIComponent,n=[];for(let o of Object.keys(r)){let i=r[o];if(i===void 0)continue;if(!AR.test(o))throw new TypeError(`cookie name is invalid: ${o}`);let s=t(i);if(!TR.test(s))throw new TypeError(`cookie val is invalid: ${i}`);n.push(`${o}=${s}`)}return n.join("; ")}function c3(r,e,t){let n=typeof r=="object"?r:{...t,name:r,value:String(e)},i=(typeof e=="object"?e:t)?.encode||encodeURIComponent;if(!AR.test(n.name))throw new TypeError(`argument name is invalid: ${n.name}`);let s=n.value?i(n.value):"";if(!TR.test(s))throw new TypeError(`argument val is invalid: ${n.value}`);let a=n.name+"="+s;if(n.maxAge!==void 0){if(!Number.isInteger(n.maxAge))throw new TypeError(`option maxAge is invalid: ${n.maxAge}`);a+="; Max-Age="+n.maxAge}if(n.domain){if(!Kj.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);a+="; Domain="+n.domain}if(n.path){if(!zj.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);a+="; Path="+n.path}if(n.expires){if(!Qj(n.expires)||!Number.isFinite(n.expires.valueOf()))throw new TypeError(`option expires is invalid: ${n.expires}`);a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.partitioned&&(a+="; Partitioned"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${n.priority}`)}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${n.sameSite}`)}return a}function Xj(r,e){let t=e?.decode||CR,n=r.length,o=pb(r,0,n),i=mb(r,0,o),s=i===-1?{name:"",value:t(Bs(r,0,o))}:{name:Bs(r,0,i),value:t(Bs(r,i+1,o))},a=o+1;for(;a<n;){let c=pb(r,a,n),l=mb(r,a,c),u=l===-1?Bs(r,a,c):Bs(r,a,l),d=l===-1?void 0:Bs(r,l+1,c);switch(u.toLowerCase()){case"httponly":s.httpOnly=!0;break;case"secure":s.secure=!0;break;case"partitioned":s.partitioned=!0;break;case"domain":s.domain=d;break;case"path":s.path=d;break;case"max-age":d&&Gj.test(d)&&(s.maxAge=Number(d));break;case"expires":if(!d)break;let f=new Date(d);Number.isFinite(f.valueOf())&&(s.expires=f);break;case"priority":if(!d)break;let h=d.toLowerCase();(h==="low"||h==="medium"||h==="high")&&(s.priority=h);break;case"samesite":if(!d)break;let p=d.toLowerCase();(p==="lax"||p==="strict"||p==="none")&&(s.sameSite=p);break}a=c+1}return s}function pb(r,e,t){let n=r.indexOf(";",e);return n===-1?t:n}function mb(r,e,t){let n=r.indexOf("=",e);return n<t?n:-1}function Bs(r,e,t){let n=e,o=t;do{let i=r.charCodeAt(n);if(i!==32&&i!==9)break}while(++n<o);for(;o>n;){let i=r.charCodeAt(o-1);if(i!==32&&i!==9)break;o--}return r.slice(n,o)}function CR(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function Qj(r){return Wj.call(r)==="[object Date]"}});var UD=$((kUe,FD)=>{FD.exports=p9;var MD=128,fX=127,hX=~fX,pX=Math.pow(2,31);function p9(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw p9.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=pX;)e[t++]=r&255|MD,r/=128;for(;r&hX;)e[t++]=r&255|MD,r>>>=7;return e[t]=r|0,p9.bytes=t-n+1,e}});var qD=$((RUe,HD)=>{HD.exports=m9;var mX=128,$D=127;function m9(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a||o>49)throw m9.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&$D)<<o:(s&$D)*Math.pow(2,o),o+=7}while(s>=mX);return m9.bytes=i-n,t}});var KD=$((PUe,VD)=>{var gX=Math.pow(2,7),yX=Math.pow(2,14),wX=Math.pow(2,21),bX=Math.pow(2,28),xX=Math.pow(2,35),EX=Math.pow(2,42),vX=Math.pow(2,49),SX=Math.pow(2,56),AX=Math.pow(2,63);VD.exports=function(r){return r<gX?1:r<yX?2:r<wX?3:r<bX?4:r<xX?5:r<EX?6:r<vX?7:r<SX?8:r<AX?9:10}});var Dy=$((DUe,zD)=>{zD.exports={encode:UD(),decode:qD(),encodingLength:KD()}});var uL=$((kHe,lL)=>{"use strict";lL.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let n=this._internalPositionFor(e,!1);if(t===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let o=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):o=!0,this._setInternalPos(n,e,t,o),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let t=this._internalPositionFor(e,!0);if(t!==-1)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let t=0;for(;t<this.length;)e(this.get(t),t,this),t++}map(e){let t=0,n=new Array(this.length);for(;t<this.length;)n[t]=e(this.get(t),t,this),t++;return n}reduce(e,t){let n=0,o=t;for(;n<this.length;){let i=this.get(n);o=e(o,i,n),n++}return o}find(e){let t=0,n,o;for(;t<this.length&&!n;)o=this.get(t),n=e(o),t++;return n?o:void 0}_internalPositionFor(e,t){let n=this._bytePosFor(e,t);if(n>=this._bitArrays.length)return-1;let o=this._bitArrays[n],i=e-n*7;if(!((o&1<<i)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(KX,0),c=~(4294967295<<i+1),l=cL(o&c);return a+l-1}_bytePosFor(e,t){let n=Math.floor(e/7),o=n+1;for(;!t&&this._bitArrays.length<o;)this._bitArrays.push(0);return n}_setBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]|=1<<e-t*7}_unsetBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]&=~(1<<e-t*7)}_setInternalPos(e,t,n,o){let i=this._data,s=[t,n];if(o)this._sortData(),i[e]=s;else{if(i.length)if(i[i.length-1][0]>=t)i.push(s);else if(i[0][0]<=t)i.unshift(s);else{let a=Math.round(i.length/2);this._data=i.slice(0,a).concat(s).concat(i.slice(a))}else this._data.push(s);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(zX),this._changedData=!1}bitField(){let e=[],t=8,n=0,o=0,i,s=this._bitArrays.slice();for(;s.length||n;){n===0&&(i=s.shift(),n=7);let c=Math.min(n,t),l=~(255<<c),u=i&l;o|=u<<8-t,i=i>>>c,n-=c,t-=c,(!t||!n&&!s.length)&&(e.push(o),o=0,t=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(GX)}};function KX(r,e){return r+cL(e)}function cL(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function zX(r,e){return r[0]-e[0]}function GX(r){return r[1]}});var QL=$((cze,XL)=>{"use strict";XL.exports={RTLD_LAZY:1,RTLD_NOW:2,RTLD_GLOBAL:256,RTLD_LOCAL:0,RTLD_DEEPBIND:8,E2BIG:7,EACCES:13,EADDRINUSE:98,EADDRNOTAVAIL:99,EAFNOSUPPORT:97,EAGAIN:11,EALREADY:114,EBADF:9,EBADMSG:74,EBUSY:16,ECANCELED:125,ECHILD:10,ECONNABORTED:103,ECONNREFUSED:111,ECONNRESET:104,EDEADLK:35,EDESTADDRREQ:89,EDOM:33,EDQUOT:122,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:113,EIDRM:43,EILSEQ:84,EINPROGRESS:115,EINTR:4,EINVAL:22,EIO:5,EISCONN:106,EISDIR:21,ELOOP:40,EMFILE:24,EMLINK:31,EMSGSIZE:90,EMULTIHOP:72,ENAMETOOLONG:36,ENETDOWN:100,ENETRESET:102,ENETUNREACH:101,ENFILE:23,ENOBUFS:105,ENODATA:61,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:37,ENOLINK:67,ENOMEM:12,ENOMSG:42,ENOPROTOOPT:92,ENOSPC:28,ENOSR:63,ENOSTR:60,ENOSYS:38,ENOTCONN:107,ENOTDIR:20,ENOTEMPTY:39,ENOTSOCK:88,ENOTSUP:95,ENOTTY:25,ENXIO:6,EOPNOTSUPP:95,EOVERFLOW:75,EPERM:1,EPIPE:32,EPROTO:71,EPROTONOSUPPORT:93,EPROTOTYPE:91,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:116,ETIME:62,ETIMEDOUT:110,ETXTBSY:26,EWOULDBLOCK:11,EXDEV:18,PRIORITY_LOW:19,PRIORITY_BELOW_NORMAL:10,PRIORITY_NORMAL:0,PRIORITY_ABOVE_NORMAL:-7,PRIORITY_HIGH:-14,PRIORITY_HIGHEST:-20,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:17,SIGSTKFLT:16,SIGCONT:18,SIGSTOP:19,SIGTSTP:20,SIGTTIN:21,SIGTTOU:22,SIGURG:23,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:29,SIGPOLL:29,SIGPWR:30,SIGSYS:31,UV_FS_SYMLINK_DIR:1,UV_FS_SYMLINK_JUNCTION:2,O_RDONLY:0,O_WRONLY:1,O_RDWR:2,UV_DIRENT_UNKNOWN:0,UV_DIRENT_FILE:1,UV_DIRENT_DIR:2,UV_DIRENT_LINK:3,UV_DIRENT_FIFO:4,UV_DIRENT_SOCKET:5,UV_DIRENT_CHAR:6,UV_DIRENT_BLOCK:7,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:64,O_EXCL:128,UV_FS_O_FILEMAP:0,O_NOCTTY:256,O_TRUNC:512,O_APPEND:1024,O_DIRECTORY:65536,O_NOATIME:262144,O_NOFOLLOW:131072,O_SYNC:1052672,O_DSYNC:4096,O_DIRECT:16384,O_NONBLOCK:2048,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,F_OK:0,R_OK:4,W_OK:2,X_OK:1,UV_FS_COPYFILE_EXCL:1,COPYFILE_EXCL:1,UV_FS_COPYFILE_FICLONE:2,COPYFILE_FICLONE:2,UV_FS_COPYFILE_FICLONE_FORCE:4,COPYFILE_FICLONE_FORCE:4,OPENSSL_VERSION_NUMBER:810549344,SSL_OP_ALL:2147485776,SSL_OP_ALLOW_NO_DHE_KEX:1024,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_ENCRYPT_THEN_MAC:524288,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_RENEGOTIATION:1073741824,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:0,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_NO_TLSv1_3:536870912,SSL_OP_PRIORITIZE_CHACHA:2097152,SSL_OP_TLS_ROLLBACK_BUG:8388608,ENGINE_METHOD_RSA:1,ENGINE_METHOD_DSA:2,ENGINE_METHOD_DH:4,ENGINE_METHOD_RAND:8,ENGINE_METHOD_EC:2048,ENGINE_METHOD_CIPHERS:64,ENGINE_METHOD_DIGESTS:128,ENGINE_METHOD_PKEY_METHS:512,ENGINE_METHOD_PKEY_ASN1_METHS:1024,ENGINE_METHOD_ALL:65535,ENGINE_METHOD_NONE:0,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,RSA_PKCS1_PADDING:1,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,RSA_PSS_SALTLEN_DIGEST:-1,RSA_PSS_SALTLEN_MAX_SIGN:-2,RSA_PSS_SALTLEN_AUTO:-2,defaultCoreCipherList:"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA",TLS1_VERSION:769,TLS1_1_VERSION:770,TLS1_2_VERSION:771,TLS1_3_VERSION:772,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}});var z9=$((Xze,iN)=>{"use strict";var oN=Object.prototype.toString;iN.exports=function(e){var t=oN.call(e),n=t==="[object Arguments]";return n||(n=t!=="[object Array]"&&e!==null&&typeof e=="object"&&typeof e.length=="number"&&e.length>=0&&oN.call(e.callee)==="[object Function]"),n}});var pN=$((Qze,hN)=>{"use strict";var fN;Object.keys||(up=Object.prototype.hasOwnProperty,G9=Object.prototype.toString,sN=z9(),W9=Object.prototype.propertyIsEnumerable,aN=!W9.call({toString:null},"toString"),cN=W9.call(function(){},"prototype"),dp=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],i4=function(r){var e=r.constructor;return e&&e.prototype===r},lN={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},uN=(function(){if(typeof window>"u")return!1;for(var r in window)try{if(!lN["$"+r]&&up.call(window,r)&&window[r]!==null&&typeof window[r]=="object")try{i4(window[r])}catch{return!0}}catch{return!0}return!1})(),dN=function(r){if(typeof window>"u"||!uN)return i4(r);try{return i4(r)}catch{return!1}},fN=function(e){var t=e!==null&&typeof e=="object",n=G9.call(e)==="[object Function]",o=sN(e),i=t&&G9.call(e)==="[object String]",s=[];if(!t&&!n&&!o)throw new TypeError("Object.keys called on a non-object");var a=cN&&n;if(i&&e.length>0&&!up.call(e,0))for(var c=0;c<e.length;++c)s.push(String(c));if(o&&e.length>0)for(var l=0;l<e.length;++l)s.push(String(l));else for(var u in e)!(a&&u==="prototype")&&up.call(e,u)&&s.push(String(u));if(aN)for(var d=dN(e),f=0;f<dp.length;++f)!(d&&dp[f]==="constructor")&&up.call(e,dp[f])&&s.push(dp[f]);return s});var up,G9,sN,W9,aN,cN,dp,i4,lN,uN,dN;hN.exports=fN});var wN=$((Zze,yN)=>{"use strict";var eZ=Array.prototype.slice,tZ=z9(),mN=Object.keys,s4=mN?function(e){return mN(e)}:pN(),gN=Object.keys;s4.shim=function(){if(Object.keys){var e=(function(){var t=Object.keys(arguments);return t&&t.length===arguments.length})(1,2);e||(Object.keys=function(n){return tZ(n)?gN(eZ.call(n)):gN(n)})}else Object.keys=s4;return Object.keys||s4};yN.exports=s4});var fp=$((Jze,bN)=>{"use strict";var a4=Object.defineProperty||!1;if(a4)try{a4({},"a",{value:1})}catch{a4=!1}bN.exports=a4});var j9=$((eGe,xN)=>{"use strict";xN.exports=SyntaxError});var Sr=$((tGe,EN)=>{"use strict";EN.exports=TypeError});var SN=$((rGe,vN)=>{"use strict";vN.exports=Object.getOwnPropertyDescriptor});var Bu=$((nGe,AN)=>{"use strict";var c4=SN();if(c4)try{c4([],"length")}catch{c4=null}AN.exports=c4});var Y9=$((oGe,CN)=>{"use strict";var TN=fp(),rZ=j9(),Mu=Sr(),_N=Bu();CN.exports=function(e,t,n){if(!e||typeof e!="object"&&typeof e!="function")throw new Mu("`obj` must be an object or a function`");if(typeof t!="string"&&typeof t!="symbol")throw new Mu("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Mu("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Mu("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Mu("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Mu("`loose`, if provided, must be a boolean");var o=arguments.length>3?arguments[3]:null,i=arguments.length>4?arguments[4]:null,s=arguments.length>5?arguments[5]:null,a=arguments.length>6?arguments[6]:!1,c=!!_N&&_N(e,t);if(TN)TN(e,t,{configurable:s===null&&c?c.configurable:!s,enumerable:o===null&&c?c.enumerable:!o,value:n,writable:i===null&&c?c.writable:!i});else if(a||!o&&!i&&!s)e[t]=n;else throw new rZ("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}});var Q9=$((iGe,kN)=>{"use strict";var X9=fp(),IN=function(){return!!X9};IN.hasArrayLengthDefineBug=function(){if(!X9)return null;try{return X9([],"length",{value:1}).length!==1}catch{return!0}};kN.exports=IN});var Z9=$((sGe,LN)=>{"use strict";var nZ=wN(),oZ=typeof Symbol=="function"&&typeof Symbol("foo")=="symbol",iZ=Object.prototype.toString,sZ=Array.prototype.concat,RN=Y9(),aZ=function(r){return typeof r=="function"&&iZ.call(r)==="[object Function]"},PN=Q9()(),cZ=function(r,e,t,n){if(e in r){if(n===!0){if(r[e]===t)return}else if(!aZ(n)||!n())return}PN?RN(r,e,t,!0):RN(r,e,t)},DN=function(r,e){var t=arguments.length>2?arguments[2]:{},n=nZ(e);oZ&&(n=sZ.call(n,Object.getOwnPropertySymbols(e)));for(var o=0;o<n.length;o+=1)cZ(r,n[o],e[n[o]],t[n[o]])};DN.supportsDescriptors=!!PN;LN.exports=DN});var J9=$((aGe,NN)=>{"use strict";NN.exports=Object});var BN=$((cGe,ON)=>{"use strict";ON.exports=Error});var FN=$((lGe,MN)=>{"use strict";MN.exports=EvalError});var $N=$((uGe,UN)=>{"use strict";UN.exports=RangeError});var qN=$((dGe,HN)=>{"use strict";HN.exports=ReferenceError});var KN=$((fGe,VN)=>{"use strict";VN.exports=URIError});var ex=$((hGe,zN)=>{"use strict";zN.exports=Math.abs});var hp=$((pGe,GN)=>{"use strict";GN.exports=Math.floor});var jN=$((mGe,WN)=>{"use strict";WN.exports=Math.max});var XN=$((gGe,YN)=>{"use strict";YN.exports=Math.min});var ZN=$((yGe,QN)=>{"use strict";QN.exports=Math.pow});var eO=$((wGe,JN)=>{"use strict";JN.exports=Math.round});var l4=$((bGe,tO)=>{"use strict";tO.exports=Number.isNaN||function(e){return e!==e}});var nO=$((xGe,rO)=>{"use strict";var lZ=l4();rO.exports=function(e){return lZ(e)||e===0?e:e<0?-1:1}});var tx=$((EGe,oO)=>{"use strict";oO.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},t=Symbol("test"),n=Object(t);if(typeof t=="string"||Object.prototype.toString.call(t)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var o=42;e[t]=o;for(var i in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var s=Object.getOwnPropertySymbols(e);if(s.length!==1||s[0]!==t||!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var a=Object.getOwnPropertyDescriptor(e,t);if(a.value!==o||a.enumerable!==!0)return!1}return!0}});var aO=$((vGe,sO)=>{"use strict";var iO=typeof Symbol<"u"&&Symbol,uZ=tx();sO.exports=function(){return typeof iO!="function"||typeof Symbol!="function"||typeof iO("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:uZ()}});var rx=$((SGe,cO)=>{"use strict";cO.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var nx=$((AGe,lO)=>{"use strict";var dZ=J9();lO.exports=dZ.getPrototypeOf||null});var fO=$((TGe,dO)=>{"use strict";var fZ="Function.prototype.bind called on incompatible ",hZ=Object.prototype.toString,pZ=Math.max,mZ="[object Function]",uO=function(e,t){for(var n=[],o=0;o<e.length;o+=1)n[o]=e[o];for(var i=0;i<t.length;i+=1)n[i+e.length]=t[i];return n},gZ=function(e,t){for(var n=[],o=t||0,i=0;o<e.length;o+=1,i+=1)n[i]=e[o];return n},yZ=function(r,e){for(var t="",n=0;n<r.length;n+=1)t+=r[n],n+1<r.length&&(t+=e);return t};dO.exports=function(e){var t=this;if(typeof t!="function"||hZ.apply(t)!==mZ)throw new TypeError(fZ+t);for(var n=gZ(arguments,1),o,i=function(){if(this instanceof o){var u=t.apply(this,uO(n,arguments));return Object(u)===u?u:this}return t.apply(e,uO(n,arguments))},s=pZ(0,t.length-n.length),a=[],c=0;c<s;c++)a[c]="$"+c;if(o=Function("binder","return function ("+yZ(a,",")+"){ return binder.apply(this,arguments); }")(i),t.prototype){var l=function(){};l.prototype=t.prototype,o.prototype=new l,l.prototype=null}return o}});var Fu=$((_Ge,hO)=>{"use strict";var wZ=fO();hO.exports=Function.prototype.bind||wZ});var u4=$((CGe,pO)=>{"use strict";pO.exports=Function.prototype.call});var d4=$((IGe,mO)=>{"use strict";mO.exports=Function.prototype.apply});var yO=$((kGe,gO)=>{"use strict";gO.exports=typeof Reflect<"u"&&Reflect&&Reflect.apply});var ox=$((RGe,wO)=>{"use strict";var bZ=Fu(),xZ=d4(),EZ=u4(),vZ=yO();wO.exports=vZ||bZ.call(EZ,xZ)});var f4=$((PGe,bO)=>{"use strict";var SZ=Fu(),AZ=Sr(),TZ=u4(),_Z=ox();bO.exports=function(e){if(e.length<1||typeof e[0]!="function")throw new AZ("a function is required");return _Z(SZ,TZ,e)}});var TO=$((DGe,AO)=>{"use strict";var CZ=f4(),xO=Bu(),vO;try{vO=[].__proto__===Array.prototype}catch(r){if(!r||typeof r!="object"||!("code"in r)||r.code!=="ERR_PROTO_ACCESS")throw r}var ix=!!vO&&xO&&xO(Object.prototype,"__proto__"),SO=Object,EO=SO.getPrototypeOf;AO.exports=ix&&typeof ix.get=="function"?CZ([ix.get]):typeof EO=="function"?function(e){return EO(e==null?e:SO(e))}:!1});var RO=$((LGe,kO)=>{"use strict";var _O=rx(),CO=nx(),IO=TO();kO.exports=_O?function(e){return _O(e)}:CO?function(e){if(!e||typeof e!="object"&&typeof e!="function")throw new TypeError("getProto: not an object");return CO(e)}:IO?function(e){return IO(e)}:null});var sx=$((NGe,PO)=>{"use strict";var IZ=Function.prototype.call,kZ=Object.prototype.hasOwnProperty,RZ=Fu();PO.exports=RZ.call(IZ,kZ)});var Vu=$((OGe,MO)=>{"use strict";var ge,PZ=J9(),DZ=BN(),LZ=FN(),NZ=$N(),OZ=qN(),qu=j9(),Hu=Sr(),BZ=KN(),MZ=ex(),FZ=hp(),UZ=jN(),$Z=XN(),HZ=ZN(),qZ=eO(),VZ=nO(),OO=Function,ax=function(r){try{return OO('"use strict"; return ('+r+").constructor;")()}catch{}},pp=Bu(),KZ=fp(),cx=function(){throw new Hu},zZ=pp?(function(){try{return arguments.callee,cx}catch{try{return pp(arguments,"callee").get}catch{return cx}}})():cx,Uu=aO()(),jt=RO(),GZ=nx(),WZ=rx(),BO=d4(),mp=u4(),$u={},jZ=typeof Uint8Array>"u"||!jt?ge:jt(Uint8Array),Dc={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?ge:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?ge:ArrayBuffer,"%ArrayIteratorPrototype%":Uu&&jt?jt([][Symbol.iterator]()):ge,"%AsyncFromSyncIteratorPrototype%":ge,"%AsyncFunction%":$u,"%AsyncGenerator%":$u,"%AsyncGeneratorFunction%":$u,"%AsyncIteratorPrototype%":$u,"%Atomics%":typeof Atomics>"u"?ge:Atomics,"%BigInt%":typeof BigInt>"u"?ge:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?ge:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?ge:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?ge:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":DZ,"%eval%":eval,"%EvalError%":LZ,"%Float16Array%":typeof Float16Array>"u"?ge:Float16Array,"%Float32Array%":typeof Float32Array>"u"?ge:Float32Array,"%Float64Array%":typeof Float64Array>"u"?ge:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?ge:FinalizationRegistry,"%Function%":OO,"%GeneratorFunction%":$u,"%Int8Array%":typeof Int8Array>"u"?ge:Int8Array,"%Int16Array%":typeof Int16Array>"u"?ge:Int16Array,"%Int32Array%":typeof Int32Array>"u"?ge:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Uu&&jt?jt(jt([][Symbol.iterator]())):ge,"%JSON%":typeof JSON=="object"?JSON:ge,"%Map%":typeof Map>"u"?ge:Map,"%MapIteratorPrototype%":typeof Map>"u"||!Uu||!jt?ge:jt(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":PZ,"%Object.getOwnPropertyDescriptor%":pp,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?ge:Promise,"%Proxy%":typeof Proxy>"u"?ge:Proxy,"%RangeError%":NZ,"%ReferenceError%":OZ,"%Reflect%":typeof Reflect>"u"?ge:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?ge:Set,"%SetIteratorPrototype%":typeof Set>"u"||!Uu||!jt?ge:jt(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?ge:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Uu&&jt?jt(""[Symbol.iterator]()):ge,"%Symbol%":Uu?Symbol:ge,"%SyntaxError%":qu,"%ThrowTypeError%":zZ,"%TypedArray%":jZ,"%TypeError%":Hu,"%Uint8Array%":typeof Uint8Array>"u"?ge:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?ge:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?ge:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?ge:Uint32Array,"%URIError%":BZ,"%WeakMap%":typeof WeakMap>"u"?ge:WeakMap,"%WeakRef%":typeof WeakRef>"u"?ge:WeakRef,"%WeakSet%":typeof WeakSet>"u"?ge:WeakSet,"%Function.prototype.call%":mp,"%Function.prototype.apply%":BO,"%Object.defineProperty%":KZ,"%Object.getPrototypeOf%":GZ,"%Math.abs%":MZ,"%Math.floor%":FZ,"%Math.max%":UZ,"%Math.min%":$Z,"%Math.pow%":HZ,"%Math.round%":qZ,"%Math.sign%":VZ,"%Reflect.getPrototypeOf%":WZ};if(jt)try{null.error}catch(r){DO=jt(jt(r)),Dc["%Error.prototype%"]=DO}var DO,YZ=function r(e){var t;if(e==="%AsyncFunction%")t=ax("async function () {}");else if(e==="%GeneratorFunction%")t=ax("function* () {}");else if(e==="%AsyncGeneratorFunction%")t=ax("async function* () {}");else if(e==="%AsyncGenerator%"){var n=r("%AsyncGeneratorFunction%");n&&(t=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var o=r("%AsyncGenerator%");o&&jt&&(t=jt(o.prototype))}return Dc[e]=t,t},LO={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},gp=Fu(),h4=sx(),XZ=gp.call(mp,Array.prototype.concat),QZ=gp.call(BO,Array.prototype.splice),NO=gp.call(mp,String.prototype.replace),p4=gp.call(mp,String.prototype.slice),ZZ=gp.call(mp,RegExp.prototype.exec),JZ=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,eJ=/\\(\\)?/g,tJ=function(e){var t=p4(e,0,1),n=p4(e,-1);if(t==="%"&&n!=="%")throw new qu("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&t!=="%")throw new qu("invalid intrinsic syntax, expected opening `%`");var o=[];return NO(e,JZ,function(i,s,a,c){o[o.length]=a?NO(c,eJ,"$1"):s||i}),o},rJ=function(e,t){var n=e,o;if(h4(LO,n)&&(o=LO[n],n="%"+o[0]+"%"),h4(Dc,n)){var i=Dc[n];if(i===$u&&(i=YZ(n)),typeof i>"u"&&!t)throw new Hu("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:o,name:n,value:i}}throw new qu("intrinsic "+e+" does not exist!")};MO.exports=function(e,t){if(typeof e!="string"||e.length===0)throw new Hu("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof t!="boolean")throw new Hu('"allowMissing" argument must be a boolean');if(ZZ(/^%?[^%]*%?$/,e)===null)throw new qu("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=tJ(e),o=n.length>0?n[0]:"",i=rJ("%"+o+"%",t),s=i.name,a=i.value,c=!1,l=i.alias;l&&(o=l[0],QZ(n,XZ([0,1],l)));for(var u=1,d=!0;u<n.length;u+=1){var f=n[u],h=p4(f,0,1),p=p4(f,-1);if((h==='"'||h==="'"||h==="`"||p==='"'||p==="'"||p==="`")&&h!==p)throw new qu("property names with quotes must have matching quotes");if((f==="constructor"||!d)&&(c=!0),o+="."+f,s="%"+o+"%",h4(Dc,s))a=Dc[s];else if(a!=null){if(!(f in a)){if(!t)throw new Hu("base intrinsic for "+e+" exists, but the property is not available.");return}if(pp&&u+1>=n.length){var y=pp(a,f);d=!!y,d&&"get"in y&&!("originalValue"in y.get)?a=y.get:a=a[f]}else d=h4(a,f),a=a[f];d&&!c&&(Dc[s]=a)}}return a}});var qO=$((BGe,HO)=>{"use strict";var nJ=Vu(),FO=Y9(),oJ=Q9()(),UO=Bu(),$O=Sr(),iJ=nJ("%Math.floor%");HO.exports=function(e,t){if(typeof e!="function")throw new $O("`fn` is not a function");if(typeof t!="number"||t<0||t>4294967295||iJ(t)!==t)throw new $O("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],o=!0,i=!0;if("length"in e&&UO){var s=UO(e,"length");s&&!s.configurable&&(o=!1),s&&!s.writable&&(i=!1)}return(o||i||!n)&&(oJ?FO(e,"length",t,!0,!0):FO(e,"length",t)),e}});var KO=$((MGe,VO)=>{"use strict";var sJ=Fu(),aJ=d4(),cJ=ox();VO.exports=function(){return cJ(sJ,aJ,arguments)}});var lx=$((FGe,m4)=>{"use strict";var lJ=qO(),zO=fp(),uJ=f4(),GO=KO();m4.exports=function(e){var t=uJ(arguments),n=1+e.length-(arguments.length-1);return lJ(t,n>0?n:0,!0)};zO?zO(m4.exports,"apply",{value:GO}):m4.exports.apply=GO});var ra=$((UGe,YO)=>{"use strict";var WO=Vu(),jO=f4(),dJ=jO([WO("%String.prototype.indexOf%")]);YO.exports=function(e,t){var n=WO(e,!!t);return typeof n=="function"&&dJ(e,".prototype.")>-1?jO([n]):n}});var QO=$(($Ge,XO)=>{"use strict";var fJ=l4();XO.exports=function(e){return(typeof e=="number"||typeof e=="bigint")&&!fJ(e)&&e!==1/0&&e!==-1/0}});var g4=$((HGe,ZO)=>{"use strict";var hJ=ex(),pJ=hp(),mJ=l4(),gJ=QO();ZO.exports=function(e){if(typeof e!="number"||mJ(e)||!gJ(e))return!1;var t=hJ(e);return pJ(t)===t}});var ux=$((qGe,eB)=>{"use strict";var JO=Sr(),yJ=ra(),wJ=g4(),bJ=yJ("Number.prototype.toString");eB.exports=function(e,t){if(typeof e!="number")throw new JO("Assertion failed: `x` must be a Number");if(!wJ(t)||t<2||t>36)throw new JO("Assertion failed: `radix` must be an integer >= 2 and <= 36");return bJ(e,t)}});var rB=$((VGe,tB)=>{"use strict";var xJ=ra(),dx=Sr(),EJ=g4(),vJ=xJ("String.prototype.slice");tB.exports=function(e,t,n){if(typeof e!="string")throw new dx("Assertion failed: `string` must be a String");if(typeof t!="string")throw new dx("Assertion failed: `searchValue` must be a String");if(!EJ(n)||n<0)throw new dx("Assertion failed: `fromIndex` must be a non-negative integer");var o=e.length;if(t===""&&n<=o)return n;for(var i=t.length,s=n;s<=o-i;s+=1){var a=vJ(e,s,s+i);if(a===t)return s}return-1}});var fx=$((KGe,nB)=>{"use strict";var y4=Sr(),SJ=ra(),AJ=g4(),TJ=SJ("String.prototype.slice");nB.exports=function(e,t,n,o){if(typeof e!="string")throw new y4("Assertion failed: `S` must be a String");if(!AJ(t)||t<0)throw new y4("Assertion failed: `maxLength` must be a non-negative integer");if(typeof n!="string")throw new y4("Assertion failed: `fillString` must be a String");if(o!=="start"&&o!=="end"&&o!=="START"&&o!=="END")throw new y4("Assertion failed: `placement` must be ~START~ or ~END~");var i=e.length;if(t<=i||n==="")return e;for(var s=t-i,a="";a.length<s;)a+=n;return a=TJ(a,0,s),o==="start"||o==="START"?a+e:e+a}});var sB=$((zGe,iB)=>{"use strict";var oB=Sr(),hx=ra(),_J=hx("String.prototype.charCodeAt"),CJ=hx("Number.prototype.toString"),IJ=hx("String.prototype.toLowerCase"),kJ=fx();iB.exports=function(e){if(typeof e!="string"||e.length!==1)throw new oB("Assertion failed: `C` must be a single code unit");var t=_J(e,0);if(t>65535)throw new oB("`Assertion failed: numeric value of `C` must be <= 0xFFFF");return"\\u"+kJ(IJ(CJ(t,16)),4,"0","start")}});var cB=$((GGe,aB)=>{"use strict";var RJ=hp();aB.exports=function(e){return typeof e=="bigint"?e:RJ(e)}});var uB=$((WGe,lB)=>{"use strict";var PJ=hp();lB.exports=function(e,t){var n=e%t;return PJ(n>=0?n:n+t)}});var fB=$((jGe,dB)=>{"use strict";dB.exports=uB()});var pB=$((YGe,hB)=>{"use strict";var DJ=fB();hB.exports=function(e,t){return DJ(e,t)}});var px=$((XGe,mB)=>{"use strict";mB.exports=function(e){return typeof e=="number"&&e>=0&&e<=1114111&&(e|0)===e}});var yB=$((QGe,gB)=>{"use strict";var LJ=Vu(),NJ=Sr(),mx=LJ("%String.fromCharCode%"),OJ=cB(),BJ=pB(),MJ=px();gB.exports=function(e){if(!MJ(e))throw new NJ("Assertion failed: `cp` must be >= 0 and <= 0x10FFFF");if(e<=65535)return mx(e);var t=mx(OJ((e-65536)/1024)+55296),n=mx(BJ(e-65536,1024)+56320);return t+n}});var w4=$((ZGe,wB)=>{"use strict";wB.exports=function(e){return typeof e=="number"&&e>=55296&&e<=56319}});var b4=$((JGe,bB)=>{"use strict";bB.exports=function(e){return typeof e=="number"&&e>=56320&&e<=57343}});var SB=$((eWe,vB)=>{"use strict";var EB=Function.prototype.toString,Ku=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,yx,x4;if(typeof Ku=="function"&&typeof Object.defineProperty=="function")try{yx=Object.defineProperty({},"length",{get:function(){throw x4}}),x4={},Ku(function(){throw 42},null,yx)}catch(r){r!==x4&&(Ku=null)}else Ku=null;var FJ=/^\s*class\b/,wx=function(e){try{var t=EB.call(e);return FJ.test(t)}catch{return!1}},gx=function(e){try{return wx(e)?!1:(EB.call(e),!0)}catch{return!1}},E4=Object.prototype.toString,UJ="[object Object]",$J="[object Function]",HJ="[object GeneratorFunction]",qJ="[object HTMLAllCollection]",VJ="[object HTML document.all class]",KJ="[object HTMLCollection]",zJ=typeof Symbol=="function"&&!!Symbol.toStringTag,GJ=!(0 in[,]),bx=function(){return!1};typeof document=="object"&&(xB=document.all,E4.call(xB)===E4.call(document.all)&&(bx=function(e){if((GJ||!e)&&(typeof e>"u"||typeof e=="object"))try{var t=E4.call(e);return(t===qJ||t===VJ||t===KJ||t===UJ)&&e("")==null}catch{}return!1}));var xB;vB.exports=Ku?function(e){if(bx(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;try{Ku(e,null,yx)}catch(t){if(t!==x4)return!1}return!wx(e)&&gx(e)}:function(e){if(bx(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;if(zJ)return gx(e);if(wx(e))return!1;var t=E4.call(e);return t!==$J&&t!==HJ&&!/^\[object HTML/.test(t)?!1:gx(e)}});var xx=$((tWe,TB)=>{"use strict";var WJ=SB(),jJ=Object.prototype.toString,AB=Object.prototype.hasOwnProperty,YJ=function(e,t,n){for(var o=0,i=e.length;o<i;o++)AB.call(e,o)&&(n==null?t(e[o],o,e):t.call(n,e[o],o,e))},XJ=function(e,t,n){for(var o=0,i=e.length;o<i;o++)n==null?t(e.charAt(o),o,e):t.call(n,e.charAt(o),o,e)},QJ=function(e,t,n){for(var o in e)AB.call(e,o)&&(n==null?t(e[o],o,e):t.call(n,e[o],o,e))};function ZJ(r){return jJ.call(r)==="[object Array]"}TB.exports=function(e,t,n){if(!WJ(t))throw new TypeError("iterator must be a function");var o;arguments.length>=3&&(o=n),ZJ(e)?YJ(e,t,o):typeof e=="string"?XJ(e,t,o):QJ(e,t,o)}});var CB=$((rWe,_B)=>{"use strict";var JJ=tx();_B.exports=function(){return JJ()&&!!Symbol.toStringTag}});var LB=$((nWe,DB)=>{"use strict";var IB=ra(),eee=CB()(),tee=sx(),ree=Bu(),Sx;eee?(kB=IB("RegExp.prototype.exec"),Ex={},v4=function(){throw Ex},vx={toString:v4,valueOf:v4},typeof Symbol.toPrimitive=="symbol"&&(vx[Symbol.toPrimitive]=v4),Sx=function(e){if(!e||typeof e!="object")return!1;var t=ree(e,"lastIndex"),n=t&&tee(t,"value");if(!n)return!1;try{kB(e,vx)}catch(o){return o===Ex}}):(RB=IB("Object.prototype.toString"),PB="[object RegExp]",Sx=function(e){return!e||typeof e!="object"&&typeof e!="function"?!1:RB(e)===PB});var kB,Ex,v4,vx,RB,PB;DB.exports=Sx});var Ax=$((oWe,NB)=>{"use strict";var nee=ra(),oee=LB(),iee=nee("RegExp.prototype.exec"),see=Sr();NB.exports=function(e){if(!oee(e))throw new see("`regex` must be a RegExp");return function(n){return iee(e,n)!==null}}});var UB=$((iWe,FB)=>{"use strict";var aee=ux(),OB=rB(),cee=fx(),lee=sB(),uee=yB(),dee=w4(),fee=b4(),hee=Sr(),pee=px(),mee=xx(),MB=Ax(),gee=MB(/^\s$/),yee=MB(/^[\n\r\u2028\u2029]$/),wee="^$\\.*+?()[]{}|",bee=",-=<>#&!%:;@~'`\"",BB={" ":"t","\n":"n","\v":"v","\f":"f","\r":"r",__proto__:null};FB.exports=function(e){if(!pee(e))throw new hee("Assertion failed: `c` must be a valid Unicode code point");var t=uee(e);if(OB(wee,t,0)>-1||t==="/")return"\\"+t;if(t in BB)return"\\"+BB[t];if(OB(bee,t,0)>-1||gee(t)||yee(t)||dee(e)||fee(e)){if(e<255){var n=aee(e,16);return"\\x"+cee(n,2,"0","START")}var o="",i=t;return mee(i,function(s){o+=lee(s)}),o}return t}});var qB=$((sWe,HB)=>{"use strict";var xee=Vu(),Eee=Sr(),$B=xee("%String.fromCharCode%"),vee=w4(),See=b4();HB.exports=function(e,t){if(!vee(e)||!See(t))throw new Eee("Assertion failed: `lead` must be a leading surrogate char code, and `trail` must be a trailing surrogate char code");return $B(e)+$B(t)}});var jB=$((aWe,WB)=>{"use strict";var VB=Sr(),GB=ra(),Aee=w4(),KB=b4(),Tee=qB(),_ee=GB("String.prototype.charAt"),zB=GB("String.prototype.charCodeAt");WB.exports=function(e,t){if(typeof e!="string")throw new VB("Assertion failed: `string` must be a String");var n=e.length;if(t<0||t>=n)throw new VB("Assertion failed: `position` must be >= 0, and < the length of `string`");var o=zB(e,t),i=_ee(e,t),s=Aee(o),a=KB(o);if(!s&&!a)return{"[[CodePoint]]":i,"[[CodeUnitCount]]":1,"[[IsUnpairedSurrogate]]":!1};if(a||t+1===n)return{"[[CodePoint]]":i,"[[CodeUnitCount]]":1,"[[IsUnpairedSurrogate]]":!0};var c=zB(e,t+1);return KB(c)?{"[[CodePoint]]":Tee(o,c),"[[CodeUnitCount]]":2,"[[IsUnpairedSurrogate]]":!1}:{"[[CodePoint]]":i,"[[CodeUnitCount]]":1,"[[IsUnpairedSurrogate]]":!0}}});var XB=$((cWe,YB)=>{"use strict";var Cee=Sr(),Iee=jB();YB.exports=function(e){if(typeof e!="string")throw new Cee("Assertion failed: `string` must be a String");for(var t=[],n=e.length,o=0;o<n;){var i=Iee(e,o);t[t.length]=i["[[CodePoint]]"],o+=i["[[CodeUnitCount]]"]}return t}});var eM=$((lWe,JB)=>{"use strict";var QB=Vu(),ZB=lx(),kee=ZB(QB("String.prototype.indexOf"));JB.exports=function(e,t){var n=QB(e,!!t);return typeof n=="function"&&kee(e,".prototype.")>-1?ZB(n):n}});var Tx=$((uWe,nM)=>{"use strict";var Ree=UB(),Pee=ux(),Dee=XB(),Lee=Ax(),Nee=xx(),Oee=Sr(),Bee=Lee(/^[\da-zA-Z]$/),Mee=eM(),tM=Mee("String.prototype.charCodeAt"),rM=function(e){var t=tM(e,0);if(t<55296||t>56319||e.length===1)return t;var n=tM(e,1);return n<56320||n>57343?t:(t-55296)*1024+(n-56320)+65536};nM.exports=function(e){if(typeof e!="string")throw new Oee("`S` must be a String");var t="",n=Dee(e);return Nee(n,function(o){if(t===""&&Bee(o)){var i=Pee(rM(o),16);t+="\\x"+i}else t+=Ree(rM(o))}),t}});var _x=$((dWe,oM)=>{"use strict";var Fee=Tx();oM.exports=function(){return RegExp.escape||Fee}});var sM=$((fWe,iM)=>{"use strict";var Uee=Z9(),$ee=_x()();iM.exports=function(){return Uee(RegExp,{escape:$ee}),RegExp.escape}});var lM=$((hWe,cM)=>{"use strict";var Hee=Z9(),qee=lx(),Cx=Tx(),Vee=_x(),Kee=sM(),aM=qee(Cx,null);Hee(aM,{getPolyfill:Vee,implementation:Cx,method:Cx,shim:Kee});cM.exports=aM});var mM=$(Ix=>{Ix.read=function(r,e,t,n,o){var i,s,a=o*8-n-1,c=(1<<a)-1,l=c>>1,u=-7,d=t?o-1:0,f=t?-1:1,h=r[e+d];for(d+=f,i=h&(1<<-u)-1,h>>=-u,u+=a;u>0;i=i*256+r[e+d],d+=f,u-=8);for(s=i&(1<<-u)-1,i>>=-u,u+=n;u>0;s=s*256+r[e+d],d+=f,u-=8);if(i===0)i=1-l;else{if(i===c)return s?NaN:(h?-1:1)*(1/0);s=s+Math.pow(2,n),i=i-l}return(h?-1:1)*s*Math.pow(2,i-n)};Ix.write=function(r,e,t,n,o,i){var s,a,c,l=i*8-o-1,u=(1<<l)-1,d=u>>1,f=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:i-1,p=n?1:-1,y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=u):(s=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-s))<1&&(s--,c*=2),s+d>=1?e+=f/c:e+=f*Math.pow(2,1-d),e*c>=2&&(s++,c/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(e*c-1)*Math.pow(2,o),s=s+d):(a=e*Math.pow(2,d-1)*Math.pow(2,o),s=0));o>=8;r[t+h]=a&255,h+=p,a/=256,o-=8);for(s=s<<o|a,l+=o;l>0;r[t+h]=s&255,h+=p,s/=256,l-=8);r[t+h-p]|=y*128}});var _M=$((Sje,TM)=>{var ju=1e3,Yu=ju*60,Xu=Yu*60,Bc=Xu*24,lte=Bc*7,ute=Bc*365.25;TM.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return dte(r);if(t==="number"&&isFinite(r))return e.long?hte(r):fte(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function dte(r){if(r=String(r),!(r.length>100)){var 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){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*ute;case"weeks":case"week":case"w":return t*lte;case"days":case"day":case"d":return t*Bc;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Xu;case"minutes":case"minute":case"mins":case"min":case"m":return t*Yu;case"seconds":case"second":case"secs":case"sec":case"s":return t*ju;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function fte(r){var e=Math.abs(r);return e>=Bc?Math.round(r/Bc)+"d":e>=Xu?Math.round(r/Xu)+"h":e>=Yu?Math.round(r/Yu)+"m":e>=ju?Math.round(r/ju)+"s":r+"ms"}function hte(r){var e=Math.abs(r);return e>=Bc?R4(r,e,Bc,"day"):e>=Xu?R4(r,e,Xu,"hour"):e>=Yu?R4(r,e,Yu,"minute"):e>=ju?R4(r,e,ju,"second"):r+" ms"}function R4(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var IM=$((Aje,CM)=>{function pte(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=a,t.humanize=_M(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let f=0;f<u.length;f++)d=(d<<5)-d+u.charCodeAt(f),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u){let d,f=null,h,p;function y(...g){if(!y.enabled)return;let m=y,b=Number(new Date),_=b-(d||b);m.diff=_,m.prev=d,m.curr=b,d=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let R=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(O,U)=>{if(O==="%%")return"%";R++;let C=t.formatters[U];if(typeof C=="function"){let L=g[R];O=C.call(m,L),g.splice(R,1),R--}return O}),t.formatArgs.call(m,g),(m.log||t.log).apply(m,g)}return y.namespace=u,y.useColors=t.useColors(),y.color=t.selectColor(u),y.extend=n,y.destroy=t.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(u)),p),set:g=>{f=g}}),typeof t.init=="function"&&t.init(y),y}function n(u,d){let f=t(this.namespace+(typeof d>"u"?":":d)+u);return f.log=this.log,f}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let f of d)f[0]==="-"?t.skips.push(f.slice(1)):t.names.push(f)}function i(u,d){let f=0,h=0,p=-1,y=0;for(;f<u.length;)if(h<d.length&&(d[h]===u[f]||d[h]==="*"))d[h]==="*"?(p=h,y=f,h++):(f++,h++);else if(p!==-1)h=p+1,y++,f=y;else return!1;for(;h<d.length&&d[h]==="*";)h++;return h===d.length}function s(){let u=[...t.names,...t.skips.map(d=>"-"+d)].join(",");return t.enable(""),u}function a(u){for(let d of t.skips)if(i(u,d))return!1;for(let d of t.names)if(i(u,d))return!0;return!1}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.enable(t.load()),t}CM.exports=pte});var kM=$((Qr,P4)=>{Qr.formatArgs=gte;Qr.save=yte;Qr.load=wte;Qr.useColors=mte;Qr.storage=bte();Qr.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Qr.colors=["#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 mte(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function gte(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+P4.exports.humanize(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)}Qr.log=console.debug||console.log||(()=>{});function yte(r){try{r?Qr.storage.setItem("debug",r):Qr.storage.removeItem("debug")}catch{}}function wte(){let r;try{r=Qr.storage.getItem("debug")||Qr.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function bte(){try{return localStorage}catch{}}P4.exports=IM()(Qr);var{formatters:xte}=P4.exports;xte.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var bre={};xt(bre,{BasePlugin:()=>vr,DuplicatePlaceholderError:()=>cp,InvalidRangeError:()=>Fr,InvalidRedirectStatusCodeError:()=>ap,InvalidRedirectsFileError:()=>sp,MEDIA_TYPE_CAR:()=>Cc,MEDIA_TYPE_CBOR:()=>vn,MEDIA_TYPE_DAG_CBOR:()=>En,MEDIA_TYPE_DAG_JSON:()=>Sn,MEDIA_TYPE_DAG_PB:()=>np,MEDIA_TYPE_IPNS_RECORD:()=>_c,MEDIA_TYPE_JSON:()=>An,MEDIA_TYPE_OCTET_STREAM:()=>Ft,MEDIA_TYPE_RAW:()=>sr,MEDIA_TYPE_TAR:()=>Nu,NoContentError:()=>L9,RedirectsFileTooLargeError:()=>ip,SubdomainNotSupportedError:()=>N9,createVerifiedFetch:()=>Ux,createVerifiedFetchWithHelia:()=>mF,isAbortWithServerTimingError:()=>yQ,verifiedFetch:()=>M4});var Vx=Symbol.for("@libp2p/connection");var si=Symbol.for("@libp2p/content-routing");var Tr=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},Ap=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Tp=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},E=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},ai=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Ju=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},ed=class extends Error{static name="UnsupportedOperationError";constructor(e="Unsupported operation"){super(e),this.name="UnsupportedOperationError"}};var oa=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},$c=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Xn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},Hc=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var Io=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},td=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},qe=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},qc=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},ko=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},_p=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Wi=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Vc=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},he=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},ia=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Ro=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Qn=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var ji=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},sa=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},rd=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Cp=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Kc=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Zn=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Ip=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},Yi=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},kp=class extends Yi{constructor(e,t){super(!0,e,t)}},Rp=class extends Yi{constructor(e,t){super(!1,e,t)}};function Pp(r){return r==null?!1:(r.type==="RSA"||r.type==="Ed25519"||r.type==="secp256k1"||r.type==="ECDSA")&&r.raw instanceof Uint8Array&&typeof r.equals=="function"&&typeof r.toMultihash=="function"&&typeof r.toCID=="function"&&typeof r.verify=="function"}var aa=Symbol.for("@libp2p/peer-discovery");var Dp=Symbol.for("@libp2p/peer-id");function pt(r){return!!r?.[Dp]}var ci=Symbol.for("@libp2p/peer-routing");var ca="keep-alive";function Lp(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Rt(...r){let e=[];for(let t of r)Lp(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 Ut(...r){let e=[];for(let t of r)Lp(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 Xi=Symbol.for("@libp2p/transport");var nd;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(nd||(nd={}));function vF(r){return typeof r?.handleEvent=="function"}function SF(r){return(r!==!0&&r!==!1&&r?.once)??!1}var se=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){let o=SF(n);super.addEventListener(e,s=>{if(o){let a=this.#e.get(s.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(s.type,a))}vF(t)?t.handleEvent(s):t(s)},n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:i})=>i!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var be=Symbol.for("@libp2p/service-capabilities"),Zr=Symbol.for("@libp2p/service-dependencies");function ae(r){let e=new globalThis.AbortController;function t(){let i=r.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(i);for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var k=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function AF(r){return r.buffer instanceof ArrayBuffer}function Pt(r){return AF(r)?r:r.slice()}var od=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},id=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Np=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var At={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Np("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 V4={};xt(V4,{base58btc:()=>Ce,base58flickr:()=>PF});var une=new Uint8Array(0);function Kx(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 Jn(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 zx(r){return new TextEncoder().encode(r)}function Gx(r){return new TextDecoder().decode(r)}function TF(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 i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,g=0,m=0,b=p.length;m!==b&&p[m]===0;)m++,y++;for(var _=(b-m)*u+1>>>0,R=new Uint8Array(_);m!==b;){for(var D=p[m],O=0,U=_-1;(D!==0||O<g)&&U!==-1;U--,O++)D+=256*R[U]>>>0,R[U]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");g=O,m++}for(var C=_-g;C!==_&&R[C]===0;)C++;for(var L=c.repeat(y);C<_;++C)L+=r.charAt(R[C]);return L}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var g=0,m=0;p[y]===c;)g++,y++;for(var b=(p.length-y)*l+1>>>0,_=new Uint8Array(b);p[y];){var R=t[p.charCodeAt(y)];if(R===255)return;for(var D=0,O=b-1;(R!==0||D<m)&&O!==-1;O--,D++)R+=a*_[O]>>>0,_[O]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");m=D,y++}if(p[y]!==" "){for(var U=b-m;U!==b&&_[U]===0;)U++;for(var C=new Uint8Array(g+(b-U)),L=g;U!==b;)C[L++]=_[U++];return C}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var _F=TF,CF=_F,Wx=CF;var U4=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")}},$4=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 jx(this,e)}},H4=class{decoders;constructor(e){this.decoders=e}or(e){return jx(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 jx(r,e){return new H4({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var q4=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new U4(e,t,n),this.decoder=new $4(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function zc({name:r,prefix:e,encode:t,decode:n}){return new q4(r,e,t,n)}function Qi({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Wx(t,r);return zc({prefix:e,name:r,encode:n,decode:i=>Jn(o(i))})}function IF(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),s=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,s+=t,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function kF(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function RF(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function mt({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=RF(n);return zc({prefix:e,name:r,encode(i){return kF(i,n,t)},decode(i){return IF(i,o,t,r)}})}var Ce=Qi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),PF=Qi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var K4={};xt(K4,{base32:()=>$t,base32hex:()=>OF,base32hexpad:()=>MF,base32hexpadupper:()=>FF,base32hexupper:()=>BF,base32pad:()=>LF,base32padupper:()=>NF,base32upper:()=>DF,base32z:()=>UF});var $t=mt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),DF=mt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),LF=mt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),NF=mt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),OF=mt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),BF=mt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),MF=mt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),FF=mt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),UF=mt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var z4={};xt(z4,{base36:()=>_r,base36upper:()=>$F});var _r=Qi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),$F=Qi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ve={};xt(Ve,{Digest:()=>la,create:()=>Cr,decode:()=>xe,equals:()=>W4,hasCode:()=>iU});var HF=Qx,Yx=128,qF=127,VF=~qF,KF=Math.pow(2,31);function Qx(r,e,t){e=e||[],t=t||0;for(var n=t;r>=KF;)e[t++]=r&255|Yx,r/=128;for(;r&VF;)e[t++]=r&255|Yx,r>>>=7;return e[t]=r|0,Qx.bytes=t-n+1,e}var zF=G4,GF=128,Xx=127;function G4(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw G4.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&Xx)<<o:(s&Xx)*Math.pow(2,o),o+=7}while(s>=GF);return G4.bytes=i-n,t}var WF=Math.pow(2,7),jF=Math.pow(2,14),YF=Math.pow(2,21),XF=Math.pow(2,28),QF=Math.pow(2,35),ZF=Math.pow(2,42),JF=Math.pow(2,49),eU=Math.pow(2,56),tU=Math.pow(2,63),rU=function(r){return r<WF?1:r<jF?2:r<YF?3:r<XF?4:r<QF?5:r<ZF?6:r<JF?7:r<eU?8:r<tU?9:10},nU={encode:HF,decode:zF,encodingLength:rU},oU=nU,sd=oU;function ad(r,e=0){return[sd.decode(r,e),sd.decode.bytes]}function Gc(r,e,t=0){return sd.encode(r,e,t),e}function Wc(r){return sd.encodingLength(r)}function Cr(r,e){let t=e.byteLength,n=Wc(r),o=n+Wc(t),i=new Uint8Array(o+t);return Gc(r,i,0),Gc(t,i,n),i.set(e,o),new la(r,t,e,i)}function xe(r){let e=Jn(r),[t,n]=ad(e),[o,i]=ad(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new la(t,o,s,e)}function W4(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Kx(r.bytes,t.bytes)}}var la=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function iU(r,e){return r.code===e}function Zx(r,e){let{bytes:t,version:n}=r;return n===0?aU(t,j4(r),e??Ce.encoder):cU(t,j4(r),e??$t.encoder)}var Jx=new WeakMap;function j4(r){let e=Jx.get(r);if(e==null){let t=new Map;return Jx.set(r,t),t}return e}var F=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!==cd)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==lU)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=Cr(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&&W4(e.multihash,n.multihash)}toString(e){return Zx(this,e)}toJSON(){return{"/":Zx(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:i,bytes:s}=t;return new r(n,o,i,s??eE(n,o,i.bytes))}else if(t[uU]===!0){let{version:n,multihash:o,code:i}=t,s=xe(o);return r.create(n,i,s)}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!==cd)throw new Error(`Version 0 CID must use dag-pb (code: ${cd}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=eE(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,cd,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=Jn(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new la(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,f]=ad(e.subarray(t));return t+=f,d},o=n(),i=cd;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,u=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=sU(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return j4(i).set(n,e),i}};function sU(r,e){switch(r[0]){case"Q":{let t=e??Ce;return[Ce.prefix,t.decode(`${Ce.prefix}${r}`)]}case Ce.prefix:{let t=e??Ce;return[Ce.prefix,t.decode(r)]}case $t.prefix:{let t=e??$t;return[$t.prefix,t.decode(r)]}case _r.prefix:{let t=e??_r;return[_r.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 aU(r,e,t){let{prefix:n}=t;if(n!==Ce.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function cU(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var cd=112,lU=18;function eE(r,e,t){let n=Wc(r),o=n+Wc(e),i=new Uint8Array(o+t.byteLength);return Gc(r,i,0),Gc(e,i,n),i.set(t,o),i}var uU=Symbol.for("@ipld/js-cid/CID");var Y4={};xt(Y4,{identity:()=>Ke});var tE=0,dU="identity",rE=Jn;function fU(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 Cr(tE,rE(r))}var Ke={code:tE,name:dU,encode:rE,digest:fU};function Dn(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 nE="1.2.840.10045.3.1.7",oE="1.3.132.0.34",iE="1.3.132.0.35";async function sE(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 aE(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,Pt(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function cE(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 i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Pt(e),Pt(t.subarray()));return n?.signal?.throwIfAborted(),i}function rt(r=0){return new Uint8Array(r)}function nt(r=0){return new Uint8Array(r)}function Ln(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=nt(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function gt(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 uE=Symbol.for("@achingbrain/uint8arraylist");function lE(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 Nn(r){return!!r?.[uE]}var G=class r{bufs;length;[uE]=!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(Nn(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Nn(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=lE(this.bufs,e);return t.buf[t.index]}set(e,t){let n=lE(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(Nn(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 Ln(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ln(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),i=new r;return i.length=o,i.bufs=n,i}_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 i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.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(s);break}let d=e-a;n.push(s.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(u){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Nn(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 i=256,s=new Int32Array(i);for(let d=0;d<i;d++)s[d]=-1;for(let d=0;d<o;d++)s[n[d]]=d;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let f=l;f>=0;f--){let h=this.get(d+f);if(n[f]!==h){u=Math.max(1,f-a[h]);break}}if(u===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=nt(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=rt(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=rt(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=rt(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=nt(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=rt(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=rt(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=rt(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=rt(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=rt(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(!gt(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,i)=>o+i.byteLength,0)),n.length=t,n}};var X4={};xt(X4,{base10:()=>pU});var pU=Qi({prefix:"9",name:"base10",alphabet:"0123456789"});var Q4={};xt(Q4,{base16:()=>mU,base16upper:()=>gU});var mU=mt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),gU=mt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Z4={};xt(Z4,{base2:()=>yU});var yU=mt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var J4={};xt(J4,{base256emoji:()=>vU});var dE=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}"),wU=dE.reduce((r,e,t)=>(r[t]=e,r),[]),bU=dE.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function xU(r){return r.reduce((e,t)=>(e+=wU[t],e),"")}function EU(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=bU[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var vU=zc({prefix:"\u{1F680}",name:"base256emoji",encode:xU,decode:EU});var e6={};xt(e6,{base64:()=>Tt,base64pad:()=>ld,base64url:()=>ud,base64urlpad:()=>SU});var Tt=mt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ld=mt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ud=mt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),SU=mt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var t6={};xt(t6,{base8:()=>AU});var AU=mt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var r6={};xt(r6,{identity:()=>TU});var TU=zc({prefix:"\0",name:"identity",encode:r=>Gx(r),decode:r=>zx(r)});var Po={};xt(Po,{code:()=>ar,decode:()=>ua,encode:()=>kU,name:()=>IU});var _U=new TextEncoder,CU=new TextDecoder,IU="json",ar=512;function kU(r){return _U.encode(JSON.stringify(r))}function ua(r){return JSON.parse(CU.decode(r))}var Jr={};xt(Jr,{code:()=>Ie,decode:()=>DU,encode:()=>PU,name:()=>RU});var RU="raw",Ie=85;function PU(r){return Jn(r)}function DU(r){return Jn(r)}var o6={};xt(o6,{sha256:()=>ct,sha512:()=>Bp});var LU=20;function li({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new n6(r,e,t,n,o)}var n6=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??LU,this.maxDigestLength=i}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?fE(n,this.code,t?.truncate):n.then(o=>fE(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function fE(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 Cr(e,r)}function pE(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ct=li({name:"sha2-256",code:18,encode:pE("SHA-256")}),Bp=li({name:"sha2-512",code:19,encode:pE("SHA-512")});var oe={...r6,...Z4,...t6,...X4,...Q4,...K4,...z4,...V4,...e6,...J4},soe={...o6,...Y4};function Mp(r=0){return new Uint8Array(r)}function gE(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var mE=gE("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),i6=gE("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=Mp(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),NU={utf8:mE,"utf-8":mE,hex:oe.base16,latin1:i6,ascii:i6,binary:i6,...oe},Fp=NU;function lt(r,e="utf8"){let t=Fp[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function ze(r,e="utf8"){let t=Fp[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var OU=parseInt("11111",2),s6=parseInt("10000000",2),BU=parseInt("01111111",2),yE={0:dd,1:dd,2:MU,3:$U,4:HU,5:UU,6:FU,16:dd,22:dd,48:dd};function On(r,e={offset:0}){let t=r[e.offset]&OU;if(e.offset++,yE[t]!=null)return yE[t](r,e);throw new Error("No decoder for tag "+t)}function fd(r,e){let t=0;if((r[e.offset]&s6)===s6){let n=r[e.offset]&BU,o="0x";e.offset++;for(let i=0;i<n;i++,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 dd(r,e){fd(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=On(r,e);if(n===null)break;t.push(n)}return t}function MU(r,e){let t=fd(r,e),n=e.offset,o=e.offset+t,i=[];for(let s=n;s<o;s++)s===n&&r[s]===0||i.push(r[s]);return e.offset+=t,Uint8Array.from(i)}function FU(r,e){let t=fd(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,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 d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function UU(r,e){return e.offset++,null}function $U(r,e){let t=fd(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 HU(r,e){let t=fd(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function qU(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new G;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Up(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=qU(r.byteLength);return new G(Uint8Array.from([e.byteLength|s6]),e)}function Ir(r){let e=new G,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new G(Uint8Array.from([2]),Up(e),e)}function hd(r){let e=Uint8Array.from([0]),t=new G(e,r);return new G(Uint8Array.from([3]),Up(t),t)}function wE(r){return new G(Uint8Array.from([4]),Up(r),r)}function eo(r,e=48){let t=new G;for(let n of r)t.append(n);return new G(Uint8Array.from([e]),Up(t),t)}var VU=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),KU=Uint8Array.from([6,5,43,129,4,0,34]),zU=Uint8Array.from([6,5,43,129,4,0,35]),bE={ext:!0,kty:"EC",crv:"P-256"},xE={ext:!0,kty:"EC",crv:"P-384"},EE={ext:!0,kty:"EC",crv:"P-521"},jc=32,Yc=48,Xc=66;function vE(r){let e=On(r);return a6(e)}function a6(r){let e=r[1],t=ze(e,"base64url"),n=r[2][1][0],o=1,i,s;if(e.byteLength===jc)return i=ze(n.subarray(o,o+jc),"base64url"),s=ze(n.subarray(o+jc),"base64url"),new fa({...bE,key_ops:["sign"],d:t,x:i,y:s});if(e.byteLength===Yc)return i=ze(n.subarray(o,o+Yc),"base64url"),s=ze(n.subarray(o+Yc),"base64url"),new fa({...xE,key_ops:["sign"],d:t,x:i,y:s});if(e.byteLength===Xc)return i=ze(n.subarray(o,o+Xc),"base64url"),s=ze(n.subarray(o+Xc),"base64url"),new fa({...EE,key_ops:["sign"],d:t,x:i,y:s});throw new E(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function c6(r){let e=On(r);return SE(e)}function SE(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===jc*2+1)return n=ze(e.subarray(t,t+jc),"base64url"),o=ze(e.subarray(t+jc),"base64url"),new da({...bE,key_ops:["verify"],x:n,y:o});if(e.byteLength===Yc*2+1)return n=ze(e.subarray(t,t+Yc),"base64url"),o=ze(e.subarray(t+Yc),"base64url"),new da({...xE,key_ops:["verify"],x:n,y:o});if(e.byteLength===Xc*2+1)return n=ze(e.subarray(t,t+Xc),"base64url"),o=ze(e.subarray(t+Xc),"base64url"),new da({...EE,key_ops:["verify"],x:n,y:o});throw new E(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function AE(r){return eo([Ir(Uint8Array.from([1])),wE(lt(r.d??"","base64url")),eo([_E(r.crv)],160),eo([hd(new G(Uint8Array.from([4]),lt(r.x??"","base64url"),lt(r.y??"","base64url")))],161)]).subarray()}function TE(r){return eo([Ir(Uint8Array.from([1])),eo([_E(r.crv)],160),eo([hd(new G(Uint8Array.from([4]),lt(r.x??"","base64url"),lt(r.y??"","base64url")))],161)]).subarray()}function _E(r){if(r==="P-256")return VU;if(r==="P-384")return KU;if(r==="P-521")return zU;throw new E(`Invalid curve ${r}`)}async function CE(r="P-256"){let e=await sE(r);return new fa(e.privateKey)}var da=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=TE(this.jwk)),this._raw}toMultihash(){return Ke.digest(Ht(this))}toCID(){return F.createV1(114,this.toMultihash())}toString(){return Ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}async verify(e,t,n){return cE(this.jwk,t,e,n)}},fa=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new da({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=AE(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}async sign(e,t){return aE(this.jwk,e,t)}};function l6(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Ur(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Xt(r,e,t=""){let n=l6(r),o=r?.length,i=e!==void 0;if(!n||i&&o!==e){let s=t&&`"${t}" `,a=i?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function di(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(Ur(r.outputLen),Ur(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Qc(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 $p(r,e){Xt(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function cr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ha(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function to(r,e){return r<<32-e|r>>>e}function Hp(r,e){return r<<e|r>>>32-e>>>0}var kE=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",GU=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function qp(r){if(Xt(r),kE)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=GU[r[t]];return e}var ui={_0:48,_9:57,A:65,F:70,a:97,f:102};function IE(r){if(r>=ui._0&&r<=ui._9)return r-ui._0;if(r>=ui.A&&r<=ui.F)return r-(ui.A-10);if(r>=ui.a&&r<=ui.f)return r-(ui.a-10)}function pd(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(kE)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,i=0;o<t;o++,i+=2){let s=IE(r.charCodeAt(i)),a=IE(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}var WU=async()=>{};async function RE(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let i=Date.now()-n;i>=0&&i<e||(await WU(),n+=i)}}function jU(r){if(typeof r!="string")throw new TypeError("string expected");return new Uint8Array(new TextEncoder().encode(r))}function u6(r,e=""){return typeof r=="string"?jU(r):Xt(r,void 0,e)}function d6(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Xt(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}function PE(r,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new TypeError("options must be object or undefined");return Object.assign(r,e)}function md(r,e={}){let t=(o,i)=>r(i).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Vp(r=32){Ur(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var f6=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Kp(r,e,t){return r&e^~r&t}function zp(r,e,t){return r&e^r&t^e&t}var pa=class{blockLen;outputLen;canXOF=!1;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=ha(this.buffer)}update(e){Qc(this),Xt(e);let{view:t,buffer:n,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=ha(e);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Qc(this),$p(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;t[s++]=128,cr(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let d=s;d<o;d++)t[d]=0;n.setBigUint64(o-8,BigInt(this.length*8),i),this.process(n,0);let a=ha(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 d=0;d<l;d++)a.setUint32(4*d,u[d],i)}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:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},fi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Qt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Gp=BigInt(4294967295),DE=BigInt(32);function YU(r,e=!1){return e?{h:Number(r&Gp),l:Number(r>>DE&Gp)}:{h:Number(r>>DE&Gp)|0,l:Number(r&Gp)|0}}function LE(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let i=0;i<t;i++){let{h:s,l:a}=YU(r[i],e);[n[i],o[i]]=[s,a]}return[n,o]}var h6=(r,e,t)=>r>>>t,p6=(r,e,t)=>r<<32-t|e>>>t,ma=(r,e,t)=>r>>>t|e<<32-t,ga=(r,e,t)=>r<<32-t|e>>>t,gd=(r,e,t)=>r<<64-t|e>>>t-32,yd=(r,e,t)=>r>>>t-32|e<<64-t;function Do(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var NE=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),OE=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,BE=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),ME=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,FE=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),UE=(r,e,t,n,o,i)=>e+t+n+o+i+(r/2**32|0)|0;var QU=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]),Zi=new Uint32Array(64),m6=class extends pa{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[e,t,n,o,i,s,a,c]}set(e,t,n,o,i,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)Zi[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=Zi[d-15],h=Zi[d-2],p=to(f,7)^to(f,18)^f>>>3,y=to(h,17)^to(h,19)^h>>>10;Zi[d]=y+Zi[d-7]+p+Zi[d-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=to(a,6)^to(a,11)^to(a,25),h=u+f+Kp(a,c,l)+QU[d]+Zi[d]|0,y=(to(n,2)^to(n,13)^to(n,22))+zp(n,o,i)|0;u=l,l=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+y|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,i,s,a,c,l,u)}roundClean(){cr(Zi)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),cr(this.buffer)}},g6=class extends m6{A=fi[0]|0;B=fi[1]|0;C=fi[2]|0;D=fi[3]|0;E=fi[4]|0;F=fi[5]|0;G=fi[6]|0;H=fi[7]|0;constructor(){super(32)}};var $E=LE(["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))),ZU=$E[0],JU=$E[1],Ji=new Uint32Array(80),es=new Uint32Array(80),y6=class extends pa{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:h,Gl:p,Hh:y,Hl:g}=this;return[e,t,n,o,i,s,a,c,l,u,d,f,h,p,y,g]}set(e,t,n,o,i,s,a,c,l,u,d,f,h,p,y,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=h|0,this.Gl=p|0,this.Hh=y|0,this.Hl=g|0}process(e,t){for(let _=0;_<16;_++,t+=4)Ji[_]=e.getUint32(t),es[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let R=Ji[_-15]|0,D=es[_-15]|0,O=ma(R,D,1)^ma(R,D,8)^h6(R,D,7),U=ga(R,D,1)^ga(R,D,8)^p6(R,D,7),C=Ji[_-2]|0,L=es[_-2]|0,H=ma(C,L,19)^gd(C,L,61)^h6(C,L,6),M=ga(C,L,19)^yd(C,L,61)^p6(C,L,6),x=BE(U,M,es[_-7],es[_-16]),A=ME(x,O,H,Ji[_-7],Ji[_-16]);Ji[_]=A|0,es[_]=x|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:h,Fl:p,Gh:y,Gl:g,Hh:m,Hl:b}=this;for(let _=0;_<80;_++){let R=ma(d,f,14)^ma(d,f,18)^gd(d,f,41),D=ga(d,f,14)^ga(d,f,18)^yd(d,f,41),O=d&h^~d&y,U=f&p^~f&g,C=FE(b,D,U,JU[_],es[_]),L=UE(C,m,R,O,ZU[_],Ji[_]),H=C|0,M=ma(n,o,28)^gd(n,o,34)^gd(n,o,39),x=ga(n,o,28)^yd(n,o,34)^yd(n,o,39),A=n&i^n&a^i&a,T=o&s^o&c^s&c;m=y|0,b=g|0,y=h|0,g=p|0,h=d|0,p=f|0,{h:d,l:f}=Do(l|0,u|0,L|0,H|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let v=NE(H,x,T);n=OE(v,L,M,A),o=v|0}({h:n,l:o}=Do(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Do(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Do(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Do(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:f}=Do(this.Eh|0,this.El|0,d|0,f|0),{h,l:p}=Do(this.Fh|0,this.Fl|0,h|0,p|0),{h:y,l:g}=Do(this.Gh|0,this.Gl|0,y|0,g|0),{h:m,l:b}=Do(this.Hh|0,this.Hl|0,m|0,b|0),this.set(n,o,i,s,a,c,l,u,d,f,h,p,y,g,m,b)}roundClean(){cr(Ji,es)}destroy(){this.destroyed=!0,cr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},w6=class extends y6{Ah=Qt[0]|0;Al=Qt[1]|0;Bh=Qt[2]|0;Bl=Qt[3]|0;Ch=Qt[4]|0;Cl=Qt[5]|0;Dh=Qt[6]|0;Dl=Qt[7]|0;Eh=Qt[8]|0;El=Qt[9]|0;Fh=Qt[10]|0;Fl=Qt[11]|0;Gh=Qt[12]|0;Gl=Qt[13]|0;Hh=Qt[14]|0;Hl=Qt[15]|0;constructor(){super(64)}};var Bn=md(()=>new g6,f6(1));var Lo=md(()=>new w6,f6(3));var pe=(r,e,t)=>Xt(r,e,t),x6=Ur,Zc=qp,Dt=(...r)=>d6(...r),Jc=r=>pd(r),ya=l6,wa=r=>Vp(r),jp=BigInt(0),b6=BigInt(1);function ro(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Yp(r){if(typeof r=="bigint"){if(!Wp(r))throw new RangeError("positive bigint expected, got "+r)}else x6(r);return r}function no(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function wd(r){let e=Yp(r).toString(16);return e.length&1?"0"+e:e}function HE(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?jp:BigInt("0x"+r)}function ba(r){return HE(qp(r))}function en(r){return HE(qp(ts(Xt(r)).reverse()))}function Xp(r,e){if(Ur(e),e===0)throw new RangeError("zero length");r=Yp(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return pd(t.padStart(e*2,"0"))}function bd(r,e){return Xp(r,e).reverse()}function qE(r,e){if(r=pe(r),e=pe(e),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 ts(r){return Uint8Array.from(pe(r))}function Qp(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Wp=r=>typeof r=="bigint"&&jp<=r;function e$(r,e,t){return Wp(r)&&Wp(e)&&Wp(t)&&e<=r&&r<t}function hi(r,e,t,n){if(!e$(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function el(r){if(r<jp)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>jp;r>>=b6,e+=1);return e}var xd=r=>(b6<<BigInt(r))-b6;function VE(r,e,t){if(Ur(r,"hashLen"),Ur(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=g=>new Uint8Array(g),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},f=(...g)=>t(l,Dt(c,...g)),h=(g=o)=>{l=f(i,g),c=f(),g.length!==0&&(l=f(s,g),c=f())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,m=[];for(;g<e;){c=f();let b=c.slice();m.push(b),g+=c.length}return Dt(...m)};return(g,m)=>{d(),h(g);let b;for(;(b=m(p()))===void 0;)h();return d(),b}}function tn(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(r,i))throw new TypeError(`param "${i}" is invalid: expected own property`);let c=r[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new TypeError(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.entries(i).forEach(([a,c])=>n(a,c,s));o(e,!1),o(t,!0)}var E6=()=>{throw new Error("not implemented")};var Zt=BigInt(0),yt=BigInt(1),xa=BigInt(2),WE=BigInt(3),jE=BigInt(4),YE=BigInt(5),t$=BigInt(7),XE=BigInt(8),r$=BigInt(9),QE=BigInt(16);function ot(r,e){if(e<=Zt)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=Zt?t:e+t}function Qe(r,e,t){if(e<Zt)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >Zt;)n*=n,n%=t;return n}function KE(r,e){if(r===Zt)throw new Error("invert: expected non-zero number");if(e<=Zt)throw new Error("invert: expected positive modulus, got "+e);let t=ot(r,e),n=e,o=Zt,i=yt,s=yt,a=Zt;for(;t!==Zt;){let l=n/t,u=n-t*l,d=o-s*l,f=i-a*l;n=t,t=u,o=s,i=a,s=d,a=f}if(n!==yt)throw new Error("invert: does not exist");return ot(o,e)}function v6(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function ZE(r,e){let t=r,n=(t.ORDER+yt)/jE,o=t.pow(e,n);return v6(t,o,e),o}function n$(r,e){let t=r,n=(t.ORDER-YE)/XE,o=t.mul(e,xa),i=t.pow(o,n),s=t.mul(e,i),a=t.mul(t.mul(s,xa),i),c=t.mul(s,t.sub(a,t.ONE));return v6(t,c,e),c}function o$(r){let e=tl(r),t=JE(r),n=t(e,e.neg(e.ONE)),o=t(e,n),i=t(e,e.neg(n)),s=(r+t$)/QE;return((a,c)=>{let l=a,u=l.pow(c,s),d=l.mul(u,n),f=l.mul(u,o),h=l.mul(u,i),p=l.eql(l.sqr(d),c),y=l.eql(l.sqr(f),c);u=l.cmov(u,d,p),d=l.cmov(h,f,y);let g=l.eql(l.sqr(d),c),m=l.cmov(u,d,g);return v6(l,m,c),m})}function JE(r){if(r<WE)throw new Error("sqrt is not defined for small field");let e=r-yt,t=0;for(;e%xa===Zt;)e/=xa,t++;let n=xa,o=tl(r);for(;zE(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ZE;let i=o.pow(n,e),s=(e+yt)/xa;return function(c,l){let u=c;if(u.is0(l))return l;if(zE(u,l)!==1)throw new Error("Cannot find square root");let d=t,f=u.mul(u.ONE,i),h=u.pow(l,e),p=u.pow(l,s);for(;!u.eql(h,u.ONE);){if(u.is0(h))return u.ZERO;let y=1,g=u.sqr(h);for(;!u.eql(g,u.ONE);)if(y++,g=u.sqr(g),y===d)throw new Error("Cannot find square root");let m=yt<<BigInt(d-y-1),b=u.pow(f,m);d=y,f=u.sqr(b),h=u.mul(h,f),p=u.mul(p,b)}return p}}function i$(r){return r%jE===WE?ZE:r%XE===YE?n$:r%QE===r$?o$(r):JE(r)}var pi=(r,e)=>(ot(r,e)&yt)===yt,s$=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function S6(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=s$.reduce((n,o)=>(n[o]="function",n),e);if(tn(r,t),no(r.BYTES,"BYTES"),no(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=yt)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function a$(r,e,t){let n=r;if(t<Zt)throw new Error("invalid exponent, negatives unsupported");if(t===Zt)return n.ONE;if(t===yt)return e;let o=n.ONE,i=e;for(;t>Zt;)t&yt&&(o=n.mul(o,i)),i=n.sqr(i),t>>=yt;return o}function Ed(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),i=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),s=n.inv(i);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),s),o}function zE(r,e){let t=r,n=(t.ORDER-yt)/xa,o=t.pow(e,n),i=t.eql(o,t.ONE),s=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function c$(r,e){if(e!==void 0&&x6(e),r<=Zt)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=el(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var GE=new WeakMap,Zp=class{ORDER;BITS;BYTES;isLE;ZERO=Zt;ONE=yt;_lengths;_mod;constructor(e,t={}){if(e<=yt)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:i}=c$(e,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,Object.freeze(this)}create(e){return ot(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Zt<=e&&e<this.ORDER}is0(e){return e===Zt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&yt)===yt}neg(e){return ot(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ot(e*e,this.ORDER)}add(e,t){return ot(e+t,this.ORDER)}sub(e,t){return ot(e-t,this.ORDER)}mul(e,t){return ot(e*t,this.ORDER)}pow(e,t){return a$(this,e,t)}div(e,t){return ot(e*KE(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 KE(e,this.ORDER)}sqrt(e){let t=GE.get(this);return t||GE.set(this,t=i$(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?bd(e,this.BYTES):Xp(e,this.BYTES)}fromBytes(e,t=!1){pe(e);let{_lengths:n,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(n){if(e.length<1||!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,i?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?en(e):ba(e);if(a&&(c=ot(c,s)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Ed(this,e)}cmov(e,t,n){return ro(n,"condition"),n?t:e}};Object.freeze(Zp.prototype);function tl(r,e={}){return new Zp(r,e)}function ev(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=yt)throw new Error("field order must be greater than 1");let e=el(r-yt);return Math.ceil(e/8)}function A6(r){let e=ev(r);return e+Math.ceil(e/2)}function T6(r,e,t=!1){pe(r);let n=r.length,o=ev(e),i=Math.max(A6(e),16);if(n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=t?en(r):ba(r),a=ot(s,e-yt)+yt;return t?bd(a,o):Xp(a,o)}var rl=BigInt(0),Ea=BigInt(1);function vd(r,e){let t=e.negate();return r?t:e}function va(r,e){let t=Ed(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function ov(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function _6(r,e){ov(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,i=xd(r),s=BigInt(r);return{windows:t,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function tv(r,e,t){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=t,a=Number(r&o),c=r>>s;a>n&&(a-=i,c+=Ea);let l=e*n,u=l+Math.abs(a)-1,d=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:l}}var C6=new WeakMap,iv=new WeakMap;function I6(r){return iv.get(r)||1}function rv(r){if(r!==rl)throw new Error("invalid wNAF")}var nl=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>rl;)t&Ea&&(n=n.add(o)),o=o.double(),t>>=Ea;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=_6(t,this.bits),i=[],s=e,a=s;for(let c=0;c<n;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=_6(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:f,offsetF:h}=tv(n,a,s);n=c,u?i=i.add(vd(f,t[h])):o=o.add(vd(d,t[l]))}return rv(n),{p:o,f:i}}wNAFUnsafe(e,t,n,o=this.ZERO){let i=_6(e,this.bits);for(let s=0;s<i.windows&&n!==rl;s++){let{nextN:a,offset:c,isZero:l,isNeg:u}=tv(n,s,i);if(n=a,!l){let d=t[c];o=o.add(u?d.negate():d)}}return rv(n),o}getPrecomputes(e,t,n){let o=C6.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),C6.set(t,o))),o}cached(e,t,n){let o=I6(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let i=I6(e);return i===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,o)}createCache(e,t){ov(t,this.bits),iv.set(e,t),C6.delete(e)}hasCache(e){return I6(e)!==1}};function sv(r,e,t,n){let o=e,i=r.ZERO,s=r.ZERO;for(;t>rl||n>rl;)t&Ea&&(i=i.add(o)),n&Ea&&(s=s.add(o)),o=o.double(),t>>=Ea,n>>=Ea;return{p1:i,p2:s}}function nv(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return S6(e),e}else return tl(r,{isLE:t})}function Jp(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>rl))throw new Error(`CURVE.${c} must be positive bigint`)}let o=nv(e.p,t.Fp,n),i=nv(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:i}}function ol(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var rs=BigInt(0),qt=BigInt(1),k6=BigInt(2),l$=BigInt(8);function u$(r,e,t,n){let o=r.sqr(t),i=r.sqr(n),s=r.add(r.mul(e.a,o),i),a=r.add(r.ONE,r.mul(e.d,r.mul(o,i)));return r.eql(s,a)}function av(r,e={}){let t=e,n=Jp("edwards",r,t,t.FpFnLE),{Fp:o,Fn:i}=n,s=n.CURVE,{h:a}=s;tn(t,{},{uvRatio:"function"});let c=k6<<BigInt(i.BYTES*8)-qt,l=y=>o.create(y),u=t.uvRatio===void 0?(y,g)=>{try{return{isValid:!0,value:o.sqrt(o.div(y,g))}}catch{return{isValid:!1,value:rs}}}:t.uvRatio;if(!u$(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(y,g,m=!1){let b=m?qt:rs;return hi("coordinate "+y,g,b,c),g}function f(y){if(!(y instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,qt,l(s.Gx*s.Gy));static ZERO=new h(rs,qt,qt,rs);static Fp=o;static Fn=i;X;Y;Z;T;constructor(g,m,b,_){this.X=d("x",g),this.Y=d("y",m),this.Z=d("z",b,!0),this.T=d("t",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof h)throw new Error("extended point not allowed");let{x:m,y:b}=g||{};return d("x",m),d("y",b),new h(m,b,qt,l(m*b))}static fromBytes(g,m=!1){let b=o.BYTES,{a:_,d:R}=s;g=ts(pe(g,b,"point")),ro(m,"zip215");let D=ts(g),O=g[b-1];D[b-1]=O&-129;let U=en(D),C=m?c:o.ORDER;hi("point.y",U,rs,C);let L=l(U*U),H=l(L-qt),M=l(R*L-_),{isValid:x,value:A}=u(H,M);if(!x)throw new Error("bad point: invalid y coordinate");let T=(A&qt)===qt,v=(O&128)!==0;if(!m&&A===rs&&v)throw new Error("bad point: x=0 and x_0=1");return v!==T&&(A=l(-A)),h.fromAffine({x:A,y:U})}static fromHex(g,m=!1){return h.fromBytes(Jc(g),m)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,m=!0){return p.createCache(this,g),m||this.multiply(k6),this}assertValidity(){let g=this,{a:m,d:b}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:_,Y:R,Z:D,T:O}=g,U=l(_*_),C=l(R*R),L=l(D*D),H=l(L*L),M=l(U*m),x=l(L*l(M+C)),A=l(H+l(b*l(U*C)));if(x!==A)throw new Error("bad point: equation left != right (1)");let T=l(_*R),v=l(D*O);if(T!==v)throw new Error("bad point: equation left != right (2)")}equals(g){f(g);let{X:m,Y:b,Z:_}=this,{X:R,Y:D,Z:O}=g,U=l(m*O),C=l(R*_),L=l(b*O),H=l(D*_);return U===C&&L===H}is0(){return this.equals(h.ZERO)}negate(){return new h(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:g}=s,{X:m,Y:b,Z:_}=this,R=l(m*m),D=l(b*b),O=l(k6*l(_*_)),U=l(g*R),C=m+b,L=l(l(C*C)-R-D),H=U+D,M=H-O,x=U-D,A=l(L*M),T=l(H*x),v=l(L*x),S=l(M*H);return new h(A,T,S,v)}add(g){f(g);let{a:m,d:b}=s,{X:_,Y:R,Z:D,T:O}=this,{X:U,Y:C,Z:L,T:H}=g,M=l(_*U),x=l(R*C),A=l(O*b*H),T=l(D*L),v=l((_+R)*(U+C)-M-x),S=T-A,P=T+A,B=l(x-m*M),I=l(v*S),q=l(P*B),V=l(v*B),Z=l(S*P);return new h(I,q,Z,V)}subtract(g){return f(g),this.add(g.negate())}multiply(g){if(!i.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:m,f:b}=p.cached(this,g,_=>va(h,_));return va(h,[m,b])[0]}multiplyUnsafe(g){if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===rs?h.ZERO:this.is0()||g===qt?this:p.unsafe(this,g,m=>va(h,m))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return p.unsafe(this,s.n).is0()}toAffine(g){let m=this,b=g,{X:_,Y:R,Z:D}=m,O=m.is0();b==null&&(b=O?l$:o.inv(D));let U=l(_*b),C=l(R*b),L=o.mul(D,b);if(O)return{x:rs,y:qt};if(L!==qt)throw new Error("invZ was invalid");return{x:U,y:C}}clearCofactor(){return a===qt?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:m}=this.toAffine(),b=o.toBytes(m);return b[b.length-1]|=g&qt?128:0,b}toHex(){return Zc(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new nl(h,i.BITS);return i.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var em=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){E6()}static fromHex(e){E6()}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 Zc(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.ep.precompute(e,t),this}};function cv(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;tn(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(no(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=o.randomBytes===void 0?wa:o.randomBytes,f=o.adjustScalarBytes===void 0?x=>x:o.adjustScalarBytes,h=o.domain===void 0?(x,A,T)=>{if(ro(T,"phflag"),A.length||T)throw new Error("Contexts/pre-hash are not supported");return x}:o.domain;function p(x){return c.create(en(x))}function y(x){let A=U.secretKey;pe(x,U.secretKey,"secretKey");let T=pe(n(x),2*A,"hashedSecretKey"),v=f(T.slice(0,A)),S=T.slice(A,2*A),P=p(v);return{head:v,prefix:S,scalar:P}}function g(x){let{head:A,prefix:T,scalar:v}=y(x),S=s.multiply(v),P=S.toBytes();return{head:A,prefix:T,scalar:v,point:S,pointBytes:P}}function m(x){return g(x).pointBytes}function b(x=Uint8Array.of(),...A){let T=Dt(...A);return p(n(h(T,pe(x,void 0,"context"),!!i)))}function _(x,A,T={}){x=pe(x,void 0,"message"),i&&(x=i(x));let{prefix:v,scalar:S,pointBytes:P}=g(A),B=b(T.context,v,x),I=s.multiply(B).toBytes(),q=b(T.context,I,P,x),V=c.create(B+q*S);if(!c.isValid(V))throw new Error("sign failed: invalid s");let Z=Dt(I,c.toBytes(V));return pe(Z,U.signature,"result")}let R={zip215:o.zip215};function D(x,A,T,v=R){let{context:S}=v,P=v.zip215===void 0?!!R.zip215:v.zip215,B=U.signature;x=pe(x,B,"signature"),A=pe(A,void 0,"message"),T=pe(T,U.publicKey,"publicKey"),P!==void 0&&ro(P,"zip215"),i&&(A=i(A));let I=B/2,q=x.subarray(0,I),V=en(x.subarray(I,B)),Z,fe,ce;try{Z=r.fromBytes(T,P),fe=r.fromBytes(q,P),ce=s.multiplyUnsafe(V)}catch{return!1}if(!P&&Z.isSmallOrder())return!1;let Fe=b(S,q,T,A);return fe.add(Z.multiplyUnsafe(Fe)).subtract(ce).clearCofactor().is0()}let O=a.BYTES,U={secretKey:O,publicKey:O,signature:2*O,seed:O};function C(x){return x=x===void 0?d(U.seed):x,pe(x,U.seed,"seed")}function L(x){return ya(x)&&x.length===U.secretKey}function H(x,A){try{return!!r.fromBytes(x,A===void 0?R.zip215:A)}catch{return!1}}let M={getExtendedPublicKey:g,randomSecretKey:C,isValidSecretKey:L,isValidPublicKey:H,toMontgomery(x){let{y:A}=r.fromBytes(x),T=U.publicKey,v=T===32;if(!v&&T!==57)throw new Error("only defined for 25519 and 448");let S=v?a.div(qt+A,qt-A):a.div(A-qt,A+qt);return a.toBytes(S)},toMontgomerySecret(x){let A=U.secretKey;pe(x,A);let T=n(x.subarray(0,A));return f(T).subarray(0,A)}};return Object.freeze(U),Object.freeze(M),Object.freeze({keygen:ol(C,m),getPublicKey:m,sign:_,verify:D,utils:M,Point:r,lengths:U})}function Sd(r,e){if(no(r),no(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function d$(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function f$(r){if(!ya(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?Qp(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function R6(r,e,t,n){pe(r),no(t),e=f$(e),e.length>255&&(e=n(Dt(Qp("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:i}=n,s=Math.ceil(t/o);if(t>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=Dt(e,Sd(e.length,1)),c=new Uint8Array(i),l=Sd(t,2),u=new Array(s),d=n(Dt(c,r,l,Sd(0,1),a));u[0]=n(Dt(d,Sd(1,1),a));for(let h=1;h<s;h++){let p=[d$(d,u[h-1]),Sd(h+1,1),a];u[h]=n(Dt(...p))}return Dt(...u).slice(0,t)}var lv="HashToScalar-";var Ad=BigInt(0),il=BigInt(1),tm=BigInt(2);function h$(r){return tn(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...r})}function uv(r){let e=h$(r),{P:t,type:n,adjustScalarBytes:o,powPminus2:i,randomBytes:s}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=s===void 0?wa:s,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),f=BigInt(a?121665:39081),h=a?tm**BigInt(254):tm**BigInt(447),p=a?BigInt(8)*tm**BigInt(251)-il:BigInt(4)*tm**BigInt(445)-il,y=h+p+il,g=T=>ot(T,t),m=b(d);function b(T){return bd(g(T),u)}function _(T){let v=ts(pe(T,u,"uCoordinate"));return a&&(v[31]&=127),g(en(v))}function R(T){return en(o(ts(pe(T,u,"scalar"))))}function D(T,v){let S=H(_(v),R(T));if(S===Ad)throw new Error("invalid private or public key received");return b(S)}function O(T){return D(T,m)}let U=O,C=D;function L(T,v,S){let P=g(T*(v-S));return v=g(v-P),S=g(S+P),{x_2:v,x_3:S}}function H(T,v){hi("u",T,Ad,t),hi("scalar",v,h,y);let S=v,P=T,B=il,I=Ad,q=T,V=il,Z=Ad;for(let ce=BigInt(l-1);ce>=Ad;ce--){let Fe=S>>ce&il;Z^=Fe,{x_2:B,x_3:q}=L(Z,B,q),{x_2:I,x_3:V}=L(Z,I,V),Z=Fe;let Ue=B+I,$e=g(Ue*Ue),_e=B-I,tt=g(_e*_e),ii=$e-tt,na=q+V,Uc=q-V,Qu=g(Uc*Ue),Zu=g(na*_e),$x=Qu+Zu,Hx=Qu-Zu;q=g($x*$x),V=g(P*g(Hx*Hx)),B=g($e*tt),I=g(ii*($e+g(f*ii)))}({x_2:B,x_3:q}=L(Z,B,q)),{x_2:I,x_3:V}=L(Z,I,V);let fe=i(I);return g(B*fe)}let M={secretKey:u,publicKey:u,seed:u},x=T=>(T=T===void 0?c(u):T,pe(T,M.seed,"seed"),T),A={randomSecretKey:x};return Object.freeze(M),Object.freeze(A),Object.freeze({keygen:ol(x,U),getSharedSecret:C,getPublicKey:U,scalarMult:D,scalarMultBase:O,utils:A,GuBytes:m.slice(),lengths:M})}var p$=BigInt(0),mi=BigInt(1),dv=BigInt(2),m$=BigInt(3),g$=BigInt(5),y$=BigInt(8),Sa=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),N6={p:Sa,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:y$,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function pv(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),i=Sa,a=r*r%i*r%i,c=Qe(a,dv,i)*a%i,l=Qe(c,mi,i)*r%i,u=Qe(l,g$,i)*l%i,d=Qe(u,e,i)*u%i,f=Qe(d,t,i)*d%i,h=Qe(f,n,i)*f%i,p=Qe(h,o,i)*h%i,y=Qe(p,o,i)*h%i,g=Qe(y,e,i)*u%i;return{pow_p_5_8:Qe(g,dv,i)*r%i,b2:a}}function mv(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var P6=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function O6(r,e){let t=Sa,n=ot(e*e*e,t),o=ot(n*n*e,t),i=pv(r*o).pow_p_5_8,s=ot(r*n*i,t),a=ot(e*s*s,t),c=s,l=ot(s*P6,t),u=a===r,d=a===ot(-r,t),f=a===ot(-r*P6,t);return u&&(s=c),(d||f)&&(s=l),pi(s,t)&&(s=ot(-s,t)),{isValid:u||d,value:s}}var os=av(N6,{uvRatio:O6}),ns=os.Fp,gv=os.Fn;function w$(r){return cv(os,Lo,Object.assign({adjustScalarBytes:mv,zip215:!0},r))}var Td=w$({});var _d=(()=>{let r=Sa;return uv({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=pv(e);return ot(Qe(t,m$,r)*n,r)},adjustScalarBytes:mv})})();var D6=P6,b$=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),x$=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),E$=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),v$=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),fv=r=>O6(mi,r),S$=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),L6=r=>ns.create(en(r)&S$);function hv(r){let{d:e}=N6,t=Sa,n=m=>ns.create(m),o=n(D6*r*r),i=n((o+mi)*E$),s=BigInt(-1),a=n((s-e*o)*n(o+e)),{isValid:c,value:l}=O6(i,a),u=n(l*r);pi(u,t)||(u=n(-u)),c||(l=u),c||(s=o);let d=n(s*(o-mi)*v$-a),f=l*l,h=n((l+l)*a),p=n(d*b$),y=n(mi-f),g=n(mi+f);return new os(n(h*g),n(y*p),n(p*g),n(h*y))}var is=class r extends em{static BASE=new r(os.BASE);static ZERO=new r(os.ZERO);static Fp=ns;static Fn=gv;constructor(e){super(e)}static fromAffine(e){return new r(os.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Xt(e,32);let{a:t,d:n}=N6,o=Sa,i=R=>ns.create(R),s=L6(e);if(!qE(ns.toBytes(s),e)||pi(s,o))throw new Error("invalid ristretto255 encoding 1");let a=i(s*s),c=i(mi+t*a),l=i(mi-t*a),u=i(c*c),d=i(l*l),f=i(t*n*u-d),{isValid:h,value:p}=fv(i(f*d)),y=i(p*l),g=i(p*y*f),m=i((s+s)*y);pi(m,o)&&(m=i(-m));let b=i(c*g),_=i(m*b);if(!h||pi(_,o)||b===p$)throw new Error("invalid ristretto255 encoding 2");return new r(new os(m,b,mi,_))}static fromHex(e){return r.fromBytes(pd(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,i=Sa,s=g=>ns.create(g),a=s(s(n+t)*s(n-t)),c=s(e*t),l=s(c*c),{value:u}=fv(s(a*l)),d=s(u*a),f=s(u*c),h=s(d*f*o),p;if(pi(o*h,i)){let g=s(t*D6),m=s(e*D6);e=g,t=m,p=s(d*x$)}else p=f;pi(e*h,i)&&(t=s(-t));let y=s((n-t)*p);return pi(y,i)&&(y=s(-y)),ns.toBytes(y)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:i}=e.ep,s=l=>ns.create(l),a=s(t*i)===s(n*o),c=s(n*i)===s(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(is.BASE);Object.freeze(is.ZERO);Object.freeze(is.prototype);Object.freeze(is);var A$=Object.freeze({Point:is,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=R6(r,t,64,Lo);return A$.deriveToCurve(n)},hashToScalar(r,e={DST:lv}){let t=R6(r,e.DST,64,Lo);return gv.create(en(t))},deriveToCurve(r){Xt(r,64);let e=L6(r.subarray(0,32)),t=hv(e),n=L6(r.subarray(32,64)),o=hv(n);return new is(t.add(o))}});var Aa=32,rn=64,B6=32;var sl,yv=(async()=>{try{return await At.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function wv(){let r=Td.utils.randomSecretKey(),e=Td.getPublicKey(r);return{privateKey:k$(r,e),publicKey:e}}async function T$(r,e){let t;r.length===rn?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:ze(r.subarray(32),"base64url"),d:ze(t,"base64url"),ext:!0,key_ops:["sign"]},o=await At.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),i=await At.get().subtle.sign({name:"Ed25519"},o,Pt(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(i,0,i.byteLength)}function _$(r,e){let t=r.subarray(0,B6);return Td.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function bv(r,e){return sl==null&&(sl=await yv),sl?T$(r,e):_$(r,e)}async function C$(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await At.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await At.get().subtle.verify({name:"Ed25519"},n,Pt(e),Pt(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function I$(r,e,t){return Td.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function xv(r,e,t){return sl==null&&(sl=await yv),sl?C$(r,e,t):I$(r,e,t)}function k$(r,e){let t=new Uint8Array(rn);for(let n=0;n<B6;n++)t[n]=r[n],t[B6+n]=e[n];return t}function R$(r){return r?.buffer instanceof ArrayBuffer}function vv(r){if(R$(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function M6(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=Mp(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return vv(t)}function al(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Cd=class{type="Ed25519";raw;constructor(e){this.raw=ll(e,Aa)}toMultihash(){return Ke.digest(Ht(this))}toCID(){return F.createV1(114,this.toMultihash())}toString(){return Ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=xv(this.raw,t,e);return al(o)?o.then(i=>(n?.signal?.throwIfAborted(),i)):o}},cl=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=ll(e,rn),this.publicKey=new Cd(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=bv(this.raw,e);return al(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function F6(r){if(r.length>rn){r=ll(r,rn+Aa);let n=r.subarray(0,rn),o=r.subarray(rn,r.length);return new cl(n,o)}r=ll(r,rn);let e=r.subarray(0,rn),t=r.subarray(Aa);return new cl(e,t)}function U6(r){return r=ll(r,Aa),new Cd(r)}async function Sv(){let{privateKey:r,publicKey:e}=wv();return new cl(r,e)}function ll(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new E(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var P$=Math.pow(2,7),D$=Math.pow(2,14),L$=Math.pow(2,21),$6=Math.pow(2,28),H6=Math.pow(2,35),q6=Math.pow(2,42),V6=Math.pow(2,49),Ne=128,lr=127;function ye(r){if(r<P$)return 1;if(r<D$)return 2;if(r<L$)return 3;if(r<$6)return 4;if(r<H6)return 5;if(r<q6)return 6;if(r<V6)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Id(r,e,t=0){switch(ye(r)){case 8:e[t++]=r&255|Ne,r/=128;case 7:e[t++]=r&255|Ne,r/=128;case 6:e[t++]=r&255|Ne,r/=128;case 5:e[t++]=r&255|Ne,r/=128;case 4:e[t++]=r&255|Ne,r>>>=7;case 3:e[t++]=r&255|Ne,r>>>=7;case 2:e[t++]=r&255|Ne,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function N$(r,e,t=0){switch(ye(r)){case 8:e.set(t++,r&255|Ne),r/=128;case 7:e.set(t++,r&255|Ne),r/=128;case 6:e.set(t++,r&255|Ne),r/=128;case 5:e.set(t++,r&255|Ne),r/=128;case 4:e.set(t++,r&255|Ne),r>>>=7;case 3:e.set(t++,r&255|Ne),r>>>=7;case 2:e.set(t++,r&255|Ne),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function kd(r,e){let t=r[e],n=0;if(n+=t&lr,t<Ne||(t=r[e+1],n+=(t&lr)<<7,t<Ne)||(t=r[e+2],n+=(t&lr)<<14,t<Ne)||(t=r[e+3],n+=(t&lr)<<21,t<Ne)||(t=r[e+4],n+=(t&lr)*$6,t<Ne)||(t=r[e+5],n+=(t&lr)*H6,t<Ne)||(t=r[e+6],n+=(t&lr)*q6,t<Ne)||(t=r[e+7],n+=(t&lr)*V6,t<Ne))return n;throw new RangeError("Could not decode varint")}function O$(r,e){let t=r.get(e),n=0;if(n+=t&lr,t<Ne||(t=r.get(e+1),n+=(t&lr)<<7,t<Ne)||(t=r.get(e+2),n+=(t&lr)<<14,t<Ne)||(t=r.get(e+3),n+=(t&lr)<<21,t<Ne)||(t=r.get(e+4),n+=(t&lr)*$6,t<Ne)||(t=r.get(e+5),n+=(t&lr)*H6,t<Ne)||(t=r.get(e+6),n+=(t&lr)*q6,t<Ne)||(t=r.get(e+7),n+=(t&lr)*V6,t<Ne))return n;throw new RangeError("Could not decode varint")}function ur(r,e,t=0){return e==null&&(e=nt(ye(r))),e instanceof Uint8Array?Id(r,e,t):N$(r,e,t)}function No(r,e=0){return r instanceof Uint8Array?kd(r,e):O$(r,e)}var K6=new Float32Array([-0]),as=new Uint8Array(K6.buffer);function Av(r,e,t){K6[0]=r,e[t]=as[0],e[t+1]=as[1],e[t+2]=as[2],e[t+3]=as[3]}function Tv(r,e){return as[0]=r[e],as[1]=r[e+1],as[2]=r[e+2],as[3]=r[e+3],K6[0]}var z6=new Float64Array([-0]),dr=new Uint8Array(z6.buffer);function _v(r,e,t){z6[0]=r,e[t]=dr[0],e[t+1]=dr[1],e[t+2]=dr[2],e[t+3]=dr[3],e[t+4]=dr[4],e[t+5]=dr[5],e[t+6]=dr[6],e[t+7]=dr[7]}function Cv(r,e){return dr[0]=r[e],dr[1]=r[e+1],dr[2]=r[e+2],dr[3]=r[e+3],dr[4]=r[e+4],dr[5]=r[e+5],dr[6]=r[e+6],dr[7]=r[e+7],z6[0]}var B$=BigInt(Number.MAX_SAFE_INTEGER),M$=BigInt(Number.MIN_SAFE_INTEGER),nn=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 Ta;if(e<B$&&e>M$)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>Iv&&(o=0n,++n>Iv&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Ta;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):Ta}},Ta=new nn(0,0);Ta.toBigInt=function(){return 0n};Ta.zzEncode=Ta.zzDecode=function(){return this};Ta.length=function(){return 1};var Iv=4294967296n;function kv(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 Rv(r,e,t){if(t-e<1)return"";let o,i=[],s=0,a;for(;e<t;)a=r[e++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(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,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function G6(r,e,t){let n=t,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,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 oo(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function rm(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var W6=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,oo(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 oo(this,4);return rm(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw oo(this,4);return rm(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw oo(this,4);let e=Tv(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw oo(this,4);let e=Cv(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 oo(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Rv(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw oo(this,e);this.pos+=e}else do if(this.pos>=this.len)throw oo(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 nn(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 oo(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 oo(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 oo(this,8);let e=rm(this.buf,this.pos+=4),t=rm(this.buf,this.pos+=4);return new nn(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=kd(this.buf,this.pos);return this.pos+=ye(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 Rd(r){return new W6(r instanceof Uint8Array?r:r.subarray())}function J(r,e,t){let n=Rd(r);return e.decode(n,void 0,t)}function Lv(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Dv=Lv("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),j6=Lv("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=nt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),F$={utf8:Dv,"utf-8":Dv,hex:oe.base16,latin1:j6,ascii:j6,binary:j6,...oe},nm=F$;function K(r,e="utf8"){let t=nm[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Y6(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return nt(s);o+s>e&&(n=nt(e),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var _a=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function X6(){}var Z6=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},U$=Y6();function $$(r){return globalThis.Buffer!=null?nt(r):U$(r)}var Dd=class{len;head;tail;states;constructor(){this.len=0,this.head=new _a(X6,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new _a(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new J6((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(om,10,nn.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=nn.fromBigInt(e);return this._push(om,t.length(),t)}uint64Number(e){return this._push(Id,ye(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=nn.fromBigInt(e).zzEncode();return this._push(om,t.length(),t)}sint64Number(e){let t=nn.fromNumber(e).zzEncode();return this._push(om,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Q6,1,e?1:0)}fixed32(e){return this._push(Pd,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=nn.fromBigInt(e);return this._push(Pd,4,t.lo)._push(Pd,4,t.hi)}fixed64Number(e){let t=nn.fromNumber(e);return this._push(Pd,4,t.lo)._push(Pd,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(Av,4,e)}double(e){return this._push(_v,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Q6,1,0):this.uint32(t)._push(q$,t,e)}string(e){let t=kv(e);return t!==0?this.uint32(t)._push(G6,t,e):this._push(Q6,1,0)}fork(){return this.states=new Z6(this),this.head=this.tail=new _a(X6,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 _a(X6,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=$$(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Q6(r,e,t){e[t]=r&255}function H$(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var J6=class extends _a{next;constructor(e,t){super(H$,e,t),this.next=void 0}};function om(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 Pd(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 q$(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Dd.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(V$,e,r),this},Dd.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(K$,e,r),this});function V$(r,e,t){e.set(r,t)}function K$(r,e,t){r.length<40?G6(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(K(r),t)}function e8(){return new Dd}function ee(r,e){let t=e8();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*te(r,e,t){let n=Rd(r);yield*e.stream(n,void 0,"$",t)}var im={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function sm(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function Ye(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(s,a){let c=e(s);a.int32(c)},n=function(s){let a=s.int32();return e(a)},o=function*(s){let a=s.int32();yield e(a)};return sm("enum",im.VARINT,t,n,o)}function re(r,e,t){return sm("message",im.LENGTH_DELIMITED,r,e,t)}var le=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Ld=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var Ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Ge||(Ge={}));var t8;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(t8||(t8={}));(function(r){r.codec=()=>Ye(t8)})(Ge||(Ge={}));var Oo;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Type!=null&&(s.uint32(8),Ge.codec().encode(i.Type,s)),i.Data!=null&&(s.uint32(18),s.bytes(i.Data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.Type=Ge.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Ge.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Oo||(Oo={}));var Nd;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Type!=null&&(s.uint32(8),Ge.codec().encode(i.Type,s)),i.Data!=null&&(s.uint32(18),s.bytes(i.Data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.Type=Ge.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Ge.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Nd||(Nd={}));function kr(r){if(isNaN(r)||r<=0)throw new E("random bytes length must be a Number bigger than 0");return Vp(r)}var Bd={};xt(Bd,{MAX_RSA_KEY_SIZE:()=>r8,generateRSAKeyPair:()=>d8,jwkToJWKKeyPair:()=>Mv,jwkToPkcs1:()=>j$,jwkToPkix:()=>s8,jwkToRSAPrivateKey:()=>u8,pkcs1MessageToJwk:()=>o8,pkcs1MessageToRSAPrivateKey:()=>am,pkcs1ToJwk:()=>W$,pkcs1ToRSAPrivateKey:()=>a8,pkixMessageToJwk:()=>i8,pkixMessageToRSAPublicKey:()=>l8,pkixToJwk:()=>Y$,pkixToRSAPublicKey:()=>c8});var ul=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Bd.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return F.createV1(114,this._multihash)}toString(){return Ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}verify(e,t,n){return Bv(this.jwk,t,e,n)}},Od=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Bd.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}sign(e,t){return Ov(this.jwk,e,t)}};var r8=8192,n8=18,z$=1062,G$=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function W$(r){let e=On(r);return o8(e)}function o8(r){return{n:ze(r[1],"base64url"),e:ze(r[2],"base64url"),d:ze(r[3],"base64url"),p:ze(r[4],"base64url"),q:ze(r[5],"base64url"),dp:ze(r[6],"base64url"),dq:ze(r[7],"base64url"),qi:ze(r[8],"base64url"),kty:"RSA"}}function j$(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 E("JWK was missing components");return eo([Ir(Uint8Array.from([0])),Ir(lt(r.n,"base64url")),Ir(lt(r.e,"base64url")),Ir(lt(r.d,"base64url")),Ir(lt(r.p,"base64url")),Ir(lt(r.q,"base64url")),Ir(lt(r.dp,"base64url")),Ir(lt(r.dq,"base64url")),Ir(lt(r.qi,"base64url"))]).subarray()}function Y$(r){let e=On(r,{offset:0});return i8(e)}function i8(r){let e=On(r[1],{offset:0});return{kty:"RSA",n:ze(e[0],"base64url"),e:ze(e[1],"base64url")}}function s8(r){if(r.n==null||r.e==null)throw new E("JWK was missing components");return eo([G$,hd(eo([Ir(lt(r.n,"base64url")),Ir(lt(r.e,"base64url"))]))]).subarray()}function a8(r){let e=On(r);return am(e)}function am(r){let e=o8(r);return u8(e)}function c8(r,e){if(r.byteLength>=z$)throw new ai("Key size is too large");let t=On(r,{offset:0});return l8(t,r,e)}function l8(r,e,t){let n=i8(r);if(t==null){let o=Bn(Oo.encode({Type:Ge.RSA,Data:e}));t=Cr(n8,o)}return new ul(n,t)}function u8(r){if(Uv(r)>r8)throw new E("Key size is too large");let e=Mv(r),t=Bn(Oo.encode({Type:Ge.RSA,Data:s8(e.publicKey)})),n=Cr(n8,t);return new Od(e.privateKey,new ul(e.publicKey,n))}async function d8(r){if(r>r8)throw new E("Key size is too large");let e=await Fv(r),t=Bn(Oo.encode({Type:Ge.RSA,Data:s8(e.publicKey)})),n=Cr(n8,t);return new Od(e.privateKey,new ul(e.publicKey,n))}function Mv(r){if(r==null)throw new E("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Fv(r,e){let t=await At.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 X$(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Ov(r,e,t){let n=await At.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await At.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Pt(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Bv(r,e,t,n){let o=await At.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let i=await At.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Pt(e),Pt(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),i}async function X$(r,e){if(r.privateKey==null||r.publicKey==null)throw new E("Private and public key are required");let t=await Promise.all([At.get().subtle.exportKey("jwk",r.privateKey),At.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Uv(r){if(r.kty!=="RSA")throw new E("invalid key type");if(r.n==null)throw new E("invalid key modulus");return lt(r.n,"base64url").length*8}var cm=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(di(e),Xt(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 i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),cr(o)}update(e){return Qc(this),this.iHash.update(e),this}digestInto(e){Qc(this),$p(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),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:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ca=(()=>{let r=((e,t,n)=>new cm(e,t).update(n).digest());return r.create=(e,t)=>new cm(e,t),r})();var $v=(r,e)=>(r+(r>=0?e:-e)/Hv)/e;function Q$(r,e,t){hi("scalar",r,Bo,t);let[[n,o],[i,s]]=e,a=$v(s*r,t),c=$v(-o*r,t),l=r-a*n-c*i,u=-a*o-c*s,d=l<Bo,f=u<Bo;d&&(l=-l),f&&(u=-u);let h=xd(Math.ceil(el(t)/2))+cs;if(l<Bo||l>=h||u<Bo||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:f,k2:u}}function h8(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function f8(r,e){tn(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return ro(t.lowS,"lowS"),ro(t.prehash,"prehash"),t.format!==void 0&&h8(t.format),t}var p8=class extends Error{constructor(e=""){super(e)}},io={Err:p8,_tlv:{encode:(r,e)=>{let{Err:t}=io;if(no(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=wd(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?wd(o.length/2|128):"";return wd(r)+i+o+e},decode(r,e){let{Err:t}=io;e=pe(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(r){let{Err:e}=io;if(Yp(r),r<Bo)throw new e("integer: negative integers are not allowed");let t=wd(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}=io;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return ba(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=io,o=pe(r,void 0,"signature"),{v:i,l:s}=n.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=io,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),i=n+o;return e.encode(48,i)}};Object.freeze(io._tlv);Object.freeze(io._int);Object.freeze(io);var Bo=BigInt(0),cs=BigInt(1),Hv=BigInt(2),lm=BigInt(3),Z$=BigInt(4);function qv(r,e={}){let t=Jp("weierstrass",r,e),n=t.Fp,o=t.Fn,i=t.CURVE,{h:s,n:a}=i;tn(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Kv(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(M,x,A){if(l&&x.is0())return Uint8Array.of(0);let{x:T,y:v}=x.toAffine(),S=n.toBytes(T);if(ro(A,"isCompressed"),A){d();let P=!n.isOdd(v);return Dt(Vv(P),S)}else return Dt(Uint8Array.of(4),S,n.toBytes(v))}function h(M){pe(M,void 0,"Point");let{publicKey:x,publicKeyUncompressed:A}=u,T=M.length,v=M[0],S=M.subarray(1);if(l&&T===1&&v===0)return{x:n.ZERO,y:n.ZERO};if(T===x&&(v===2||v===3)){let P=n.fromBytes(S);if(!n.isValid(P))throw new Error("bad point: is not on curve, wrong x");let B=g(P),I;try{I=n.sqrt(B)}catch(Z){let fe=Z instanceof Error?": "+Z.message:"";throw new Error("bad point: is not on curve, sqrt error"+fe)}d();let q=n.isOdd(I);return(v&1)===1!==q&&(I=n.neg(I)),{x:P,y:I}}else if(T===A&&v===4){let P=n.BYTES,B=n.fromBytes(S.subarray(0,P)),I=n.fromBytes(S.subarray(P,P*2));if(!m(B,I))throw new Error("bad point: is not on curve");return{x:B,y:I}}else throw new Error(`bad point: got length ${T}, expected compressed=${x} or uncompressed=${A}`)}let p=e.toBytes===void 0?f:e.toBytes,y=e.fromBytes===void 0?h:e.fromBytes;function g(M){let x=n.sqr(M),A=n.mul(x,M);return n.add(n.add(A,n.mul(M,i.a)),i.b)}function m(M,x){let A=n.sqr(x),T=g(M);return n.eql(A,T)}if(!m(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let b=n.mul(n.pow(i.a,lm),Z$),_=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(b,_)))throw new Error("bad curve params: a or b");function R(M,x,A=!1){if(!n.isValid(x)||A&&n.is0(x))throw new Error(`bad point coordinate ${M}`);return x}function D(M){if(!(M instanceof C))throw new Error("Weierstrass Point expected")}function O(M){if(!c||!c.basises)throw new Error("no endo");return Q$(M,c.basises,o.ORDER)}function U(M,x,A,T,v){return A=new C(n.mul(A.X,M),A.Y,A.Z),x=vd(T,x),A=vd(v,A),x.add(A)}class C{static BASE=new C(i.Gx,i.Gy,n.ONE);static ZERO=new C(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(x,A,T){this.X=R("x",x),this.Y=R("y",A,!0),this.Z=R("z",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){let{x:A,y:T}=x||{};if(!x||!n.isValid(A)||!n.isValid(T))throw new Error("invalid affine point");if(x instanceof C)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(T)?C.ZERO:new C(A,T,n.ONE)}static fromBytes(x){let A=C.fromAffine(y(pe(x,void 0,"point")));return A.assertValidity(),A}static fromHex(x){return C.fromBytes(Jc(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,A=!0){return H.createCache(this,x),A||this.multiply(lm),this}assertValidity(){let x=this;if(x.is0()){if(e.allowInfinityPoint&&n.is0(x.X)&&n.eql(x.Y,n.ONE)&&n.is0(x.Z))return;throw new Error("bad point: ZERO")}let{x:A,y:T}=x.toAffine();if(!n.isValid(A)||!n.isValid(T))throw new Error("bad point: x or y not field elements");if(!m(A,T))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){D(x);let{X:A,Y:T,Z:v}=this,{X:S,Y:P,Z:B}=x,I=n.eql(n.mul(A,B),n.mul(S,v)),q=n.eql(n.mul(T,B),n.mul(P,v));return I&&q}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:A}=i,T=n.mul(A,lm),{X:v,Y:S,Z:P}=this,B=n.ZERO,I=n.ZERO,q=n.ZERO,V=n.mul(v,v),Z=n.mul(S,S),fe=n.mul(P,P),ce=n.mul(v,S);return ce=n.add(ce,ce),q=n.mul(v,P),q=n.add(q,q),B=n.mul(x,q),I=n.mul(T,fe),I=n.add(B,I),B=n.sub(Z,I),I=n.add(Z,I),I=n.mul(B,I),B=n.mul(ce,B),q=n.mul(T,q),fe=n.mul(x,fe),ce=n.sub(V,fe),ce=n.mul(x,ce),ce=n.add(ce,q),q=n.add(V,V),V=n.add(q,V),V=n.add(V,fe),V=n.mul(V,ce),I=n.add(I,V),fe=n.mul(S,P),fe=n.add(fe,fe),V=n.mul(fe,ce),B=n.sub(B,V),q=n.mul(fe,Z),q=n.add(q,q),q=n.add(q,q),new C(B,I,q)}add(x){D(x);let{X:A,Y:T,Z:v}=this,{X:S,Y:P,Z:B}=x,I=n.ZERO,q=n.ZERO,V=n.ZERO,Z=i.a,fe=n.mul(i.b,lm),ce=n.mul(A,S),Fe=n.mul(T,P),Ue=n.mul(v,B),$e=n.add(A,T),_e=n.add(S,P);$e=n.mul($e,_e),_e=n.add(ce,Fe),$e=n.sub($e,_e),_e=n.add(A,v);let tt=n.add(S,B);return _e=n.mul(_e,tt),tt=n.add(ce,Ue),_e=n.sub(_e,tt),tt=n.add(T,v),I=n.add(P,B),tt=n.mul(tt,I),I=n.add(Fe,Ue),tt=n.sub(tt,I),V=n.mul(Z,_e),I=n.mul(fe,Ue),V=n.add(I,V),I=n.sub(Fe,V),V=n.add(Fe,V),q=n.mul(I,V),Fe=n.add(ce,ce),Fe=n.add(Fe,ce),Ue=n.mul(Z,Ue),_e=n.mul(fe,_e),Fe=n.add(Fe,Ue),Ue=n.sub(ce,Ue),Ue=n.mul(Z,Ue),_e=n.add(_e,Ue),ce=n.mul(Fe,_e),q=n.add(q,ce),ce=n.mul(tt,_e),I=n.mul($e,I),I=n.sub(I,ce),ce=n.mul($e,Fe),V=n.mul(tt,V),V=n.add(V,ce),new C(I,q,V)}subtract(x){return D(x),this.add(x.negate())}is0(){return this.equals(C.ZERO)}multiply(x){let{endo:A}=e;if(!o.isValidNot0(x))throw new RangeError("invalid scalar: out of range");let T,v,S=P=>H.cached(this,P,B=>va(C,B));if(A){let{k1neg:P,k1:B,k2neg:I,k2:q}=O(x),{p:V,f:Z}=S(B),{p:fe,f:ce}=S(q);v=Z.add(ce),T=U(A.beta,V,fe,P,I)}else{let{p:P,f:B}=S(x);T=P,v=B}return va(C,[T,v])[0]}multiplyUnsafe(x){let{endo:A}=e,T=this,v=x;if(!o.isValid(v))throw new RangeError("invalid scalar: out of range");if(v===Bo||T.is0())return C.ZERO;if(v===cs)return T;if(H.hasCache(this))return this.multiply(v);if(A){let{k1neg:S,k1:P,k2neg:B,k2:I}=O(v),{p1:q,p2:V}=sv(C,T,P,I);return U(A.beta,q,V,S,B)}else return H.unsafe(T,v)}toAffine(x){let A=this,T=x,{X:v,Y:S,Z:P}=A;if(n.eql(P,n.ONE))return{x:v,y:S};let B=A.is0();T==null&&(T=B?n.ONE:n.inv(P));let I=n.mul(v,T),q=n.mul(S,T),V=n.mul(P,T);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(V,n.ONE))throw new Error("invZ was invalid");return{x:I,y:q}}isTorsionFree(){let{isTorsionFree:x}=e;return s===cs?!0:x?x(C,this):H.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return s===cs?this:x?x(C,this):this.multiplyUnsafe(s)}isSmallOrder(){return s===cs?this.is0():this.clearCofactor().is0()}toBytes(x=!0){return ro(x,"isCompressed"),this.assertValidity(),p(C,this,x)}toHex(x=!0){return Zc(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let L=o.BITS,H=new nl(C,e.endo?Math.ceil(L/2):L);return L>=8&&C.BASE.precompute(8),Object.freeze(C.prototype),Object.freeze(C),C}function Vv(r){return Uint8Array.of(r?2:3)}function Kv(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function J$(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?wa:e.randomBytes,o=Object.assign(Kv(r.Fp,t),{seed:Math.max(A6(t.ORDER),16)});function i(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function s(h,p){let{publicKey:y,publicKeyUncompressed:g}=o;try{let m=h.length;return p===!0&&m!==y||p===!1&&m!==g?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,T6(pe(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:y,publicKeyUncompressed:g}=o,m=t._lengths;if(!ya(h))return;let b=pe(h,void 0,"key").length,_=b===y||b===g,R=b===p||!!m?.includes(b);if(!(_&&R))return _}function u(h,p,y=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(h);return r.fromBytes(p).multiply(g).toBytes(y)}let d={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},f=ol(a,c);return Object.freeze(d),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:f,Point:r,utils:d,lengths:o})}function zv(r,e,t={}){let n=e;di(n),tn(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?wa:t.randomBytes,i=t.hmac===void 0?(v,S)=>Ca(n,v,S):t.hmac,{Fp:s,Fn:a}=r,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=J$(r,t),y={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},g=c*Hv+cs<s.ORDER;function m(v){let S=c>>cs;return v>S}function b(v,S){if(!a.isValidNot0(S))throw new Error(`invalid signature ${v}: out of range 1..Point.Fn.ORDER`);return S}function _(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function R(v,S){h8(S);let P=p.signature,B=S==="compact"?P:S==="recovered"?P+1:void 0;return pe(v,B)}class D{r;s;recovery;constructor(S,P,B){if(this.r=b("r",S),this.s=b("s",P),B!=null){if(_(),![0,1,2,3].includes(B))throw new Error("invalid recovery id");this.recovery=B}Object.freeze(this)}static fromBytes(S,P=y.format){R(S,P);let B;if(P==="der"){let{r:Z,s:fe}=io.toSig(pe(S));return new D(Z,fe)}P==="recovered"&&(B=S[0],P="compact",S=S.subarray(1));let I=p.signature/2,q=S.subarray(0,I),V=S.subarray(I,I*2);return new D(a.fromBytes(q),a.fromBytes(V),B)}static fromHex(S,P){return this.fromBytes(Jc(S),P)}assertRecovery(){let{recovery:S}=this;if(S==null)throw new Error("invalid recovery id: must be present");return S}addRecoveryBit(S){return new D(this.r,this.s,S)}recoverPublicKey(S){let{r:P,s:B}=this,I=this.assertRecovery(),q=I===2||I===3?P+c:P;if(!s.isValid(q))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let V=s.toBytes(q),Z=r.fromBytes(Dt(Vv((I&1)===0),V)),fe=a.inv(q),ce=U(pe(S,void 0,"msgHash")),Fe=a.create(-ce*fe),Ue=a.create(B*fe),$e=r.BASE.multiplyUnsafe(Fe).add(Z.multiplyUnsafe(Ue));if($e.is0())throw new Error("invalid recovery: point at infinify");return $e.assertValidity(),$e}hasHighS(){return m(this.s)}toBytes(S=y.format){if(h8(S),S==="der")return Jc(io.hexFromSig(this));let{r:P,s:B}=this,I=a.toBytes(P),q=a.toBytes(B);return S==="recovered"?(_(),Dt(Uint8Array.of(this.assertRecovery()),I,q)):Dt(I,q)}toHex(S){return Zc(this.toBytes(S))}}Object.freeze(D.prototype),Object.freeze(D);let O=t.bits2int===void 0?function(S){if(S.length>8192)throw new Error("input is too large");let P=ba(S),B=S.length*8-l;return B>0?P>>BigInt(B):P}:t.bits2int,U=t.bits2int_modN===void 0?function(S){return a.create(O(S))}:t.bits2int_modN,C=xd(l);function L(v){return hi("num < 2^"+l,v,Bo,C),a.toBytes(v)}function H(v,S){return pe(v,void 0,"message"),S?pe(n(v),void 0,"prehashed message"):v}function M(v,S,P){let{lowS:B,prehash:I,extraEntropy:q}=f8(P,y);v=H(v,I);let V=U(v),Z=a.fromBytes(S);if(!a.isValidNot0(Z))throw new Error("invalid private key");let fe=[L(Z),L(V)];if(q!=null&&q!==!1){let $e=q===!0?o(p.secretKey):q;fe.push(pe($e,void 0,"extraEntropy"))}let ce=Dt(...fe),Fe=V;function Ue($e){let _e=O($e);if(!a.isValidNot0(_e))return;let tt=a.inv(_e),ii=r.BASE.multiply(_e).toAffine(),na=a.create(ii.x);if(na===Bo)return;let Uc=a.create(tt*a.create(Fe+na*Z));if(Uc===Bo)return;let Qu=(ii.x===na?0:2)|Number(ii.y&cs),Zu=Uc;return B&&m(Uc)&&(Zu=a.neg(Uc),Qu^=1),new D(na,Zu,g?void 0:Qu)}return{seed:ce,k2sig:Ue}}function x(v,S,P={}){let{seed:B,k2sig:I}=M(v,S,P);return VE(n.outputLen,a.BYTES,i)(B,I).toBytes(P.format)}function A(v,S,P,B={}){let{lowS:I,prehash:q,format:V}=f8(B,y);if(P=pe(P,void 0,"publicKey"),S=H(S,q),!ya(v)){let Z=v instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+Z)}R(v,V);try{let Z=D.fromBytes(v,V),fe=r.fromBytes(P);if(I&&Z.hasHighS())return!1;let{r:ce,s:Fe}=Z,Ue=U(S),$e=a.inv(Fe),_e=a.create(Ue*$e),tt=a.create(ce*$e),ii=r.BASE.multiplyUnsafe(_e).add(fe.multiplyUnsafe(tt));return ii.is0()?!1:a.create(ii.x)===ce}catch{return!1}}function T(v,S,P={}){let{prehash:B}=f8(P,y);return S=H(S,B),D.fromBytes(v,"recovered").recoverPublicKey(S).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:r,sign:x,verify:A,recoverPublicKey:T,Signature:D,hash:n})}var g8={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},eH={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Gv=BigInt(2);function tH(r){let e=g8.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=Qe(u,t,e)*u%e,f=Qe(d,t,e)*u%e,h=Qe(f,Gv,e)*l%e,p=Qe(h,o,e)*h%e,y=Qe(p,i,e)*p%e,g=Qe(y,a,e)*y%e,m=Qe(g,c,e)*g%e,b=Qe(m,a,e)*y%e,_=Qe(b,t,e)*u%e,R=Qe(_,s,e)*p%e,D=Qe(R,n,e)*l%e,O=Qe(D,Gv,e);if(!m8.eql(m8.sqr(O),r))throw new Error("Cannot find square root");return O}var m8=tl(g8.p,{sqrt:tH}),rH=qv(g8,{Fp:m8,endo:eH}),so=zv(rH,Bn);var Wv=32;function jv(r,e,t){let n=ct.digest(e instanceof Uint8Array?e:e.subarray());if(al(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),so.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new od(String(o))});try{return so.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new od(String(o))}}function Yv(r,e,t,n){let o=ct.digest(t instanceof Uint8Array?t:t.subarray());if(al(o))return o.then(({digest:i})=>(n?.signal?.throwIfAborted(),so.verify(e,i,r,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new id(String(i))});try{return n?.signal?.throwIfAborted(),so.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(i){throw new id(String(i))}}var Md=class{type="secp256k1";raw;_key;constructor(e){this._key=Zv(e),this.raw=Xv(this._key)}toMultihash(){return Ke.digest(Ht(this))}toCID(){return F.createV1(114,this.toMultihash())}toString(){return Ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}verify(e,t,n){return Yv(this._key,t,e,n)}},Fd=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Qv(e),this.publicKey=new Md(t??Jv(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}sign(e,t){return jv(this.raw,e,t)}};function y8(r){return new Fd(r)}function w8(r){return new Md(r)}async function eS(){let r=nH();return new Fd(r)}function Xv(r){return so.Point.fromBytes(r).toBytes()}function Qv(r){try{return so.getPublicKey(r,!0),r}catch(e){throw new Ju(String(e))}}function Zv(r){try{return so.Point.fromBytes(r),r}catch(e){throw new ai(String(e))}}function Jv(r){try{return so.getPublicKey(r,!0)}catch(e){throw new Ju(String(e))}}function nH(){return so.utils.randomSecretKey()}async function um(r,e){if(r==="Ed25519")return Sv();if(r==="secp256k1")return eS();if(r==="RSA")return d8(oH(e));if(r==="ECDSA")return CE(iH(e));throw new Zn}function Et(r,e){let{Type:t,Data:n}=Oo.decode(r),o=n??new Uint8Array;switch(t){case Ge.RSA:return c8(o,e);case Ge.Ed25519:return U6(o);case Ge.secp256k1:return w8(o);case Ge.ECDSA:return c6(o);default:throw new Zn}}function dm(r){let{Type:e,Data:t}=Oo.decode(r.digest),n=t??new Uint8Array;switch(e){case Ge.Ed25519:return U6(n);case Ge.secp256k1:return w8(n);case Ge.ECDSA:return c6(n);default:throw new Zn}}function Ht(r){return Oo.encode({Type:Ge[r.type],Data:r.raw})}function tS(r){let e=Nd.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Ge.RSA:return a8(t);case Ge.Ed25519:return F6(t);case Ge.secp256k1:return y8(t);case Ge.ECDSA:return vE(t);default:throw new Zn}}function rS(r){if(r.byteLength===rn)return F6(r);if(r.byteLength===Wv)return y8(r);let e=On(r),t=e[2]?.[0];if(t===nE||t===oE||t===iE)return a6(e);if(e.length>8)return am(e);throw new E("Could not extract private key from raw bytes")}function Ia(r){return Nd.encode({Type:Ge[r.type],Data:r.raw})}function oH(r){return r==null?2048:parseInt(r,10)}function iH(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 E("Unsupported curve, should be P-256, P-384 or P-521")}var Ud=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),ls=new Uint32Array(80),b8=class extends pa{A=Ud[0]|0;B=Ud[1]|0;C=Ud[2]|0;D=Ud[3]|0;E=Ud[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:i}=this;return[e,t,n,o,i]}set(e,t,n,o,i){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0}process(e,t){for(let c=0;c<16;c++,t+=4)ls[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)ls[c]=Hp(ls[c-3]^ls[c-8]^ls[c-14]^ls[c-16],1);let{A:n,B:o,C:i,D:s,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=Kp(o,i,s),u=1518500249):c<40?(l=o^i^s,u=1859775393):c<60?(l=zp(o,i,s),u=2400959708):(l=o^i^s,u=3395469782);let d=Hp(n,5)+l+a+u+ls[c]|0;a=s,s=i,i=Hp(o,30),o=n,n=d}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,o,i,s,a)}roundClean(){cr(ls)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),cr(this.buffer)}},nS=md(()=>new b8);function oS(r,e,t,n){di(r);let o=PE({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(Ur(i,"c"),Ur(s,"dkLen"),Ur(a,"asyncTick"),i<1)throw new Error("iterations (c) must be >= 1");if(s<1)throw new Error('"dkLen" must be >= 1');if(s>(2**32-1)*r.outputLen)throw new Error("derived key too long");let c=u6(e,"password"),l=u6(t,"salt"),u=new Uint8Array(s),d=Ca.create(r,c),f=d._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:a,DK:u,PRF:d,PRFSalt:f}}function iS(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),cr(o),t}function sS(r,e,t,n){let{c:o,dkLen:i,DK:s,PRF:a,PRFSalt:c}=oS(r,e,t,n),l,u=new Uint8Array(4),d=ha(u),f=new Uint8Array(a.outputLen);for(let h=1,p=0;p<i;h++,p+=a.outputLen){let y=s.subarray(p,p+a.outputLen);d.setInt32(0,h,!1),(l=c._cloneInto(l)).update(u).digestInto(f),y.set(f.subarray(0,y.length));for(let g=1;g<o;g++){a._cloneInto(l).update(f).digestInto(f);for(let m=0;m<y.length;m++)y[m]^=f[m]}}return iS(a,c,s,l,f)}async function fm(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=oS(r,e,t,n),u,d=new Uint8Array(4),f=ha(d),h=new Uint8Array(c.outputLen);for(let p=1,y=0;y<i;p++,y+=c.outputLen){let g=a.subarray(y,y+c.outputLen);f.setInt32(0,p,!1),(u=l._cloneInto(u)).update(d).digestInto(h),g.set(h.subarray(0,g.length)),await RE(o-1,s,()=>{c._cloneInto(u).update(h).digestInto(h);for(let m=0;m<g.length;m++)g[m]^=h[m]})}return iS(c,l,a,u,h)}var aS={sha1:nS,"sha2-256":Bn,"sha2-512":Lo};function $d(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(aS).join(" / ");throw new E(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let i=aS[o],s=sS(i,r,e,{c:t,dkLen:n});return Tt.encode(s).substring(1)}function cS(r=0){return new Uint8Array(r)}function lS(r=0){return new Uint8Array(r)}function dS(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var uS=dS("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),x8=dS("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=lS(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),sH={utf8:uS,"utf-8":uS,hex:oe.base16,latin1:x8,ascii:x8,binary:x8,...oe},fS=sH;function Mo(r,e="utf8"){let t=fS[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var E8={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},hS={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},pS=new globalThis.TextEncoder;function aH(r,e){let t=E8[e],n=hS[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function cH(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=E8[e],o=hS[e],i=r;for(;i.length>0;){let s=pS.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function v8(r,{size:e=32,utf8Buffer:t}={}){if(!E8[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 cH(r,e,t);r=pS.encode(r)}return aH(r,e)}var Hd={hash:r=>Number(v8(r,{size:32})),hashV:(r,e)=>lH(Hd.hash(r,e))};function lH(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),Mo(e,"base16")}function mS(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 S8=64,ao=class{fp;h;seed;constructor(e,t,n,o=2){if(o>S8)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=cS(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?mS(this.fp,e.fp):!1}};function ka(r,e){return Math.floor(Math.random()*(e-r))+r}var Ra=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ao))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ao))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 ao))throw new TypeError("Invalid Fingerprint");let t=ka(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ao))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var uH=500,qd=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??Hd,this.seed=e.seed??ka(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=Mo(e));let t=new ao(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 Ra(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ra(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[ka(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Ra(this.bucketSize));for(let a=0;a<uH;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new Ra(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=Mo(e));let t=new ao(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=Mo(e));let t=new ao(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},dH={1:.5,2:.84,4:.95,8:.98};function fH(r=.001){return r>.002?2:r>1e-5?4:8}function gS(r,e=.001){let t=fH(e),n=dH[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),S8);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var hm=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??Hd,this.seed=e.seed??ka(0,Math.pow(2,10)),this.filterSeries=[new qd({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=Mo(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 qd({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=Mo(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=Mo(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 Lt(r,e=.001,t){return new hm({...gS(r,e),...t??{}})}function A8(r){let e=r.getComponents(),t={},n=0;return 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?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function ie(r){let e=A8(r);if(e==null)throw new E(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var pm=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let f=Number.parseInt(d,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(i*=e,i+=u,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var yS=45,hH=15,dl=new pm;function mm(r){if(!(r.length>hH))return dl.new(r).parseWith(()=>dl.readIPv4Addr())}function gm(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>yS))return dl.new(r).parseWith(()=>dl.readIPv6Addr())}function fl(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>yS)return;let t=dl.new(r).parseWith(()=>dl.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 wS(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 bS(r,e,t,n){let o=0;for(let i of r)if(!(o<t)){if(o>n)break;if(i!==e[o])return!1;o++}return!0}function T8(r){switch(r.length){case Pa:return r.join(".");case Da:{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 xS(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 ES(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Pa=4,Da=16,Oce=parseInt("0xFFFF",16),pH=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Vd(r,e){e.length===Da&&r.length===Pa&&wS(e,0,11)&&(e=e.slice(12)),e.length===Pa&&r.length===Da&&bS(r,pH,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 vS(r,e){if(typeof e=="string"&&(e=fl(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 _8(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=Pa,o=mm(e);if(o==null&&(n=Da,o=gm(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let i=parseInt(t,10);if(Number.isNaN(i)||String(i).length!==t.length||i<0||i>n*8)throw new Error("Failed to parse given CIDR: "+r);let s=C8(i,8*n);return{network:Vd(o,s),mask:s}}function C8(r,e){if(e!==8*Pa&&e!==8*Da)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 La=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=_8(e));else{let n=fl(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let i=fl(t);if(i==null)throw new Error("Failed to parse mask");this.mask=i}else this.mask=C8(o,8*n.length);this.network=Vd(n,this.mask)}}contains(e){return vS({network:this.network,mask:this.mask},e)}toString(){let e=xS(this.mask),t=e!==-1?String(e):ES(this.mask);return T8(this.network)+"/"+t}};function SS(r,e){return new La(r).contains(e)}function ym(r){try{let e=ie(r);return e.type==="ip6"?SS("2000::/3",e.host):!1}catch{return!1}}function AS(r){try{let e=ie(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 TS(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Kd(r){try{let e=ie(r);switch(e.type){case"ip4":case"ip6":return TS(e.host);default:return!1}}catch{return!1}}function Jt(r){return A8(r)!==null}function co(r){return!!mm(r)}function wm(r){return!!gm(r)}var kS=Yt(IS(),1),EH=["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"],vH=EH.map(r=>new kS.Netmask(r));function N8(r){for(let e of vH)if(e.contains(r))return!0;return!1}function SH(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function AH(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 N8(o)}function TH(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function _H(r){let e=r.split(":"),t=e[e.length-1];return N8(t)}function CH(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 gl(r){if(co(r))return N8(r);if(SH(r))return AH(r);if(TH(r))return _H(r);if(wm(r))return CH(r)}function wt(r){try{let e=ie(r);switch(e.type){case"ip4":case"ip6":return gl(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function O8(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 Oa(r=0){return new Uint8Array(r)}var IH=Math.pow(2,7),kH=Math.pow(2,14),RH=Math.pow(2,21),B8=Math.pow(2,28),M8=Math.pow(2,35),F8=Math.pow(2,42),U8=Math.pow(2,49),ut=128,fr=127;function yl(r){if(r<IH)return 1;if(r<kH)return 2;if(r<RH)return 3;if(r<B8)return 4;if(r<M8)return 5;if(r<F8)return 6;if(r<U8)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $8(r,e,t=0){switch(yl(r)){case 8:e[t++]=r&255|ut,r/=128;case 7:e[t++]=r&255|ut,r/=128;case 6:e[t++]=r&255|ut,r/=128;case 5:e[t++]=r&255|ut,r/=128;case 4:e[t++]=r&255|ut,r>>>=7;case 3:e[t++]=r&255|ut,r>>>=7;case 2:e[t++]=r&255|ut,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function PH(r,e){let t=r[e],n=0;if(n+=t&fr,t<ut||(t=r[e+1],n+=(t&fr)<<7,t<ut)||(t=r[e+2],n+=(t&fr)<<14,t<ut)||(t=r[e+3],n+=(t&fr)<<21,t<ut)||(t=r[e+4],n+=(t&fr)*B8,t<ut)||(t=r[e+5],n+=(t&fr)*M8,t<ut)||(t=r[e+6],n+=(t&fr)*F8,t<ut)||(t=r[e+7],n+=(t&fr)*U8,t<ut))return n;throw new RangeError("Could not decode varint")}function DH(r,e){let t=r.get(e),n=0;if(n+=t&fr,t<ut||(t=r.get(e+1),n+=(t&fr)<<7,t<ut)||(t=r.get(e+2),n+=(t&fr)<<14,t<ut)||(t=r.get(e+3),n+=(t&fr)<<21,t<ut)||(t=r.get(e+4),n+=(t&fr)*B8,t<ut)||(t=r.get(e+5),n+=(t&fr)*M8,t<ut)||(t=r.get(e+6),n+=(t&fr)*F8,t<ut)||(t=r.get(e+7),n+=(t&fr)*U8,t<ut))return n;throw new RangeError("Could not decode varint")}function H8(r,e=0){return r instanceof Uint8Array?PH(r,e):DH(r,e)}function NH(r){return r.buffer instanceof ArrayBuffer}function q8(r){return NH(r)?r:r.slice()}function OH(r){return r?.buffer instanceof ArrayBuffer}function V8(r){if(OH(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function wl(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=Oa(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return V8(t)}function PS(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var RS=PS("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),K8=PS("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=Oa(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),BH={utf8:RS,"utf-8":RS,hex:oe.base16,latin1:K8,ascii:K8,binary:K8,...oe},xm=BH;function bl(r,e="utf8"){let t=xm[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function ds(r,e="utf8"){let t=xm[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var er=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},gi=class extends Error{static name="ValidationError";name="ValidationError"},Em=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},vm=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function G8(r){return e=>ds(e,r)}function W8(r){return e=>bl(e,r)}function xl(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ba(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function DS(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=bl(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=Ba(n);return wl([t,o],t.length+o.length)}function LS(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=$t.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=Ba(n);return wl([t,o],t.length+o.length)}function j8(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=ds(e,"base32"),o=xl(t);return`${n}:${o}`}var Y8=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 er("Invalid byte value in IP address");e[n]=o}),e},NS=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=co(t[n]),s;i&&(s=Y8(t[n]),t[n]=ds(s.subarray(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,ds(s.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 i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let i=parseInt(t[n],16);if(isNaN(i)||i<0||i>65535)throw new er("Invalid byte value in IP address");o[e++]=i>>8&255,o[e++]=i&255}return o},OS=function(r){if(r.byteLength!==4)throw new er("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},BS=function(r){if(r.byteLength!==16)throw new er("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],i=r[n+1],s=`${o.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`;e.push(s)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new er(`Invalid IPv6 address "${t}"`)}};function MS(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new er(`Invalid IPv6 address "${r}"`)}}var z8=Object.values(oe).map(r=>r.decoder),MH=(function(){let r=z8[0].or(z8[1]);return z8.slice(2).forEach(e=>r=r.or(e)),r})();function FS(r){return MH.decode(r)}function US(r){return e=>r.encoder.encode(e)}function FH(r){if(parseInt(r).toString()!==r)throw new gi("Value must be an integer")}function UH(r){if(r<0)throw new gi("Value must be a positive integer, or zero")}function $H(r){return e=>{if(e>r)throw new gi(`Value must be smaller than or equal to ${r}`)}}function HH(...r){return e=>{for(let t of r)t(e)}}var zd=HH(FH,UH,$H(65535));var Vt=-1,X8=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 vm(`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)}))}},wi=new X8,tq=[{code:4,name:"ip4",size:32,valueToBytes:Y8,bytesToValue:OS,validate:r=>{if(!co(r))throw new gi(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ba,bytesToValue:xl,validate:zd},{code:273,name:"udp",size:16,valueToBytes:Ba,bytesToValue:xl,validate:zd},{code:33,name:"dccp",size:16,valueToBytes:Ba,bytesToValue:xl,validate:zd},{code:41,name:"ip6",size:128,valueToBytes:NS,bytesToValue:BS,stringToValue:MS,validate:r=>{if(!wm(r))throw new gi(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:Vt},{code:43,name:"ipcidr",size:8,bytesToValue:G8("base10"),valueToBytes:W8("base10")},{code:53,name:"dns",size:Vt},{code:54,name:"dns4",size:Vt},{code:55,name:"dns6",size:Vt},{code:56,name:"dnsaddr",size:Vt},{code:132,name:"sctp",size:16,valueToBytes:Ba,bytesToValue:xl,validate:zd},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Vt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:Vt,bytesToValue:G8("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?W8("base58btc")(r):F.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:j8,valueToBytes:DS},{code:445,name:"onion3",size:296,bytesToValue:j8,valueToBytes:LS},{code:446,name:"garlic64",size:Vt},{code:447,name:"garlic32",size:Vt},{code:448,name:"tls"},{code:449,name:"sni",size:Vt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Vt,bytesToValue:US(ud),valueToBytes:FS},{code:480,name:"http"},{code:481,name:"http-path",size:Vt,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:Vt}];tq.forEach(r=>{wi.addProtocol(r)});function $S(r){let e=[],t=0;for(;t<r.length;){let n=H8(r,t),o=wi.getProtocol(n),i=yl(n),s=rq(o,r,t+i),a=0;s>0&&o.size===Vt&&(a=yl(s));let c=i+a+s,l={code:n,name:o.name,bytes:q8(r.subarray(t,t+c))};if(s>0){let u=t+i+a,d=r.subarray(u,u+s);l.value=o.bytesToValue?.(d)??ds(d)}e.push(l),t+=c}return e}function HS(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=wi.getProtocol(n.code),i=yl(n.code),s,a=0,c=0;n.value!=null&&(s=o.valueToBytes?.(n.value)??bl(n.value),a=s.byteLength,o.size===Vt&&(c=yl(a)));let l=new Uint8Array(i+c+a),u=0;$8(n.code,l,u),u+=i,s!=null&&(o.size===Vt&&($8(a,l,u),u+=c),l.set(s,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return wl(t,e)}function qS(r){if(r.charAt(0)!=="/")throw new er('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let i=1;i<r.length;i++){let s=r.charAt(i);s!=="/"&&(t==="protocol"?o+=r.charAt(i):n+=r.charAt(i));let a=i===r.length-1;if(s==="/"||a){let c=wi.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 er(`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 er(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new er("Incomplete multiaddr");return e}function VS(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=wi.getProtocol(e.code);if(t==null)throw new er(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function rq(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:H8(e,t)}var nq=Symbol.for("nodejs.util.inspect.custom"),i5=Symbol.for("@multiformats/multiaddr");function oq(r){if(r==null&&(r="/"),$o(r))return r.getComponents();if(r instanceof Uint8Array)return $S(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),qS(r);if(Array.isArray(r))return r;throw new er("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Cm=class r{[i5]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=oq(e),t.validate!==!1&&iq(this)}get bytes(){return this.#r==null&&(this.#r=HS(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=VS(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 Em(`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 O8(this.bytes,e.bytes)}[nq](){return`Multiaddr(${this.toString()})`}};function iq(r){r.getComponents().forEach(e=>{let t=wi.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function $o(r){return!!r?.[i5]}function j(r){return new Cm(r)}var Oe=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),ne=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),KS=r=>({match:e=>r.match(e)===!1?e:!1}),we=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),hr=(...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 Be(...r){function e(o){if(o==null)return!1;let i=o.getComponents();for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function t(o){return e(o)!==!1}function n(o){let i=e(o);return i===!1?!1:i.length===0}return{matchers:r,matches:t,exactMatch:n}}var sq=ne(421),zS=Be(sq),km=ne(54),Rm=ne(55),Pm=ne(56),a5=ne(53),$ue=Be(km,we(ne(421))),Hue=Be(Rm,we(ne(421))),que=Be(Pm,we(ne(421))),Dm=Be(hr(a5,Pm,km,Rm),we(ne(421))),GS=Ae(ne(4),we(ne(43))),WS=Ae(we(ne(42)),ne(41),we(ne(43))),c5=hr(GS,WS),Al=hr(c5,a5,km,Rm,Pm),jS=Be(hr(c5,Ae(hr(a5,Pm,km,Rm),we(ne(421))))),l5=Be(GS),u5=Be(WS),YS=Be(c5),d5=Ae(Al,ne(6)),Qd=Ae(Al,ne(273)),bi=Be(Ae(d5,we(ne(421)))),Vue=Be(Qd),f5=Ae(Qd,Oe(460),we(ne(421))),Lm=Ae(Qd,Oe(461),we(ne(421))),aq=hr(f5,Lm),XS=Be(f5),Nm=Be(Lm),s5=hr(Al,d5,Qd,f5,Lm),QS=hr(Ae(s5,Oe(477),we(ne(421)))),fo=Be(QS),ZS=hr(Ae(s5,Oe(478),we(ne(421))),Ae(s5,Oe(448),we(ne(449)),Oe(477),we(ne(421)))),xi=Be(ZS),JS=Ae(Qd,Oe(280),we(ne(466)),we(ne(466)),we(ne(421))),Fa=Be(JS),eA=Ae(Lm,Oe(465),we(ne(466)),we(ne(466)),we(ne(421))),Zd=Be(eA),Im=hr(QS,ZS,Ae(d5,we(ne(421))),Ae(aq,we(ne(421))),Ae(Al,we(ne(421))),JS,eA,ne(421)),Tl=Be(Im),cq=Ae(we(Im),Oe(290),KS(Oe(281)),we(ne(421))),Kt=Be(cq),lq=hr(Ae(Im,Oe(290),Oe(281),we(ne(421))),Ae(Im,Oe(281),we(ne(421))),Ae(Oe(281),we(ne(421)))),Ua=Be(lq),uq=Ae(Al,hr(Ae(ne(6,"80")),Ae(ne(6),Oe(480)),Oe(480)),we(ne(481)),we(ne(421))),Om=Be(uq),dq=Ae(Al,hr(Ae(ne(6,"443")),Ae(ne(6,"443"),Oe(480)),Ae(ne(6),Oe(443)),Ae(ne(6),Oe(448),Oe(480)),Ae(Oe(448),Oe(480)),Oe(448),Oe(443)),we(ne(481)),we(ne(421))),Bm=Be(dq),fq=hr(Ae(ne(777),we(ne(421)))),Kue=Be(fq),hq=hr(Ae(ne(400),we(ne(421)))),zue=Be(hq);function tA(r,e){let t=bi.exactMatch(r),n=bi.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let o=xi.exactMatch(r),i=xi.exactMatch(e);if(o&&!i)return-1;if(!o&&i)return 1;let s=fo.exactMatch(r),a=fo.exactMatch(e);if(s&&!a)return-1;if(!s&&a)return 1;let c=Ua.exactMatch(r),l=Ua.exactMatch(e);if(c&&!l)return-1;if(!c&&l)return 1;let u=Fa.exactMatch(r),d=Fa.exactMatch(e);if(u&&!d)return-1;if(!u&&d)return 1;let f=Zd.exactMatch(r),h=Zd.exactMatch(e);return f&&!h?-1:!f&&h?1:0}function rA(r,e){let t=Kd(r),n=Kd(e);return t&&!n?1:!t&&n?-1:0}function nA(r,e){let t=wt(r),n=wt(e);return t&&!n?1:!t&&n?-1:0}function oA(r,e){let t=Kt.exactMatch(r),n=Kt.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function me(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Mm=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}},_l=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Mm(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 Mm(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 h5=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Nt(r={}){return pq(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 pq(r,e){e=e??{};let t=e.onEnd,n=new _l,o,i,s,a=me(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((g,m)=>{i=b=>{i=null,n.push(b);try{g(r(n))}catch(_){m(_)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=me()})}},l=g=>i!=null?i(g):(n.push(g),o),u=g=>(n=new _l,i!=null?i({error:g}):(n.push({error:g}),o)),d=g=>{if(s)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},f=g=>s?o:(s=!0,g!=null?u(g):l({done:!0})),h=()=>(n=new _l,f(),{done:!0}),p=g=>(f(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:d,end:f,get readableLength(){return n.size},onEmpty:async g=>{let m=g?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let b,_;m!=null&&(b=new Promise((R,D)=>{_=()=>{D(new h5)},m.addEventListener("abort",_)}));try{await Promise.race([a.promise,b])}finally{_!=null&&m!=null&&m?.removeEventListener("abort",_)}}},t==null)return o;let y=o;return o={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(g){return y.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return y.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(g){return y.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return y.readableLength},onEmpty:g=>y.onEmpty(g)},o}var p5=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},iA=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Jd(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout},signal:s}=e,a,c,u=new Promise((d,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(s?.aborted){f(iA(s));return}if(s&&(c=()=>{f(iA(s))},s.addEventListener("abort",c,{once:!0})),r.then(d,f),t===Number.POSITIVE_INFINITY)return;let h=new p5;a=i.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${t} milliseconds`,f(h))},t)}).finally(()=>{u.clear(),c&&s&&s.removeEventListener("abort",c)});return u.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},u}var mq=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 gq(r,e,t){let n,o=new Promise((i,s)=>{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}=mq(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),s(y);return}c.push(p),t.count===c.length&&(n(),i(c))},f=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=Jd(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function ke(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=gq(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function Ei(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 Fm=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}},Um=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},$a=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},$m=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Hm=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function yq(r){return r.reason}async function Me(r,e,t){if(e==null)return r;let n=t?.translateError??yq;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((i,s)=>{o=()=>{s(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var qm=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=me(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Tr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function wq(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Vm=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=wq(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,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 Tr),this.cleanup())}async join(e){let t=new qm(e);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 Me(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),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 vt=class extends se{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=Ei(this.emitEmpty.bind(this),1),this.emitIdle=Ei(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 Um;let n=new Vm(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{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:i}}),i});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Tr)}),this.clear()}async onEmpty(e){this.size!==0&&await ke(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await ke(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ke(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=Nt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new Tr("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var bq=Math.pow(2,20)*4,hs=class extends se{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??bq,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new G,this.writeBuffer=new G,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(o){this.log.error("processSendQueue threw - %e",o)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=o=>{this.onDrainPromise?.reject(o.error??new Hm)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Me(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Nt(),t=i=>{e.push(i.data)};this.addEventListener("message",t);let n=i=>{e.end(i.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Io(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new kp(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Io("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Io("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Io(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Io(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new Hc;this.dispatchEvent(new Rp(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new Yi))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let i=this.writeBuffer.sublist(0,o),s=new G(i);this.writeBuffer.consume(i.byteLength);let a;try{a=this.sendData(i)}catch(c){throw this.writeBuffer.prepend(s),this.abort(c),c}if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==s.byteLength&&(s.consume(a.sentBytes),this.writeBuffer.prepend(s)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Ip(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new td(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new td(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var ps=class extends hs{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await ke(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await ke(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function ms(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var gs=class extends se{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=s=>{try{this.onData(s.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(s=>{s.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let i=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",i)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await Me(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new Xn;let t=this.onCreateStream({...this.streamOptions,...e});return ms(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new $m(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let o=this.streams.findIndex(i=>i===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var ys=class extends hs{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await ke(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await ke(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};var Cl=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,i=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var xq=1.2,Eq=2,vq=5e3,Sq=6e4,Aq=5e3,ho=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??Aq;this.success=new Cl(t),this.failure=new Cl(t),this.next=new Cl(t),this.failureMultiplier=e.failureMultiplier??Eq,this.timeoutMultiplier=e.timeoutMultiplier??xq,this.minTimeout=e.minTimeout??vq,this.maxTimeout=e.maxTimeout??Sq,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=ae([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();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 m5=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=me(),this.haveNext=me()}[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=me(),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=me(),await Me(this.readNext.promise,t?.signal,t)}};function sA(){return new m5}function Tq(r){return r[Symbol.asyncIterator]!=null}async function _q(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*Cq(r){let e=new AbortController,t=sA();_q(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Iq(r){for(let e of r)yield*e}function kq(...r){let e=[];for(let t of r)Tq(t)||e.push(t);return e.length===r.length?Iq(e):Cq(r)}var Rr=kq;function on(r,...e){if(r==null)throw new Error("Empty pipeline");if(g5(r)){let n=r;r=()=>n.source}else if(cA(r)||aA(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&g5(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)g5(t[n])&&(t[n]=Pq(t[n]));return Rq(...t)}var Rq=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},aA=r=>r?.[Symbol.asyncIterator]!=null,cA=r=>r?.[Symbol.iterator]!=null,g5=r=>r==null?!1:r.sink!=null&&r.source!=null,Pq=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Nt({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(aA(i))o=async function*(){yield*i,n.end()};else if(cA(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Rr(n,o())}return r.source};var Dq=4194304,Km=class extends Error{static name="UnwrappedError";name="UnwrappedError"},ef=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},w5=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},b5=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Lq(r){return typeof r?.closeRead=="function"}function Nq(r){return typeof r?.close=="function"}function y5(r){return Lq(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Nq(r)?r.status!=="open":!1}function Oq(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function zm(r,e){let t=e?.maxBufferSize??Dq,n=new G,o,i=!1;if(!Oq(r))throw new E("Argument should be a Stream or a Multiaddr");let s=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}o?.resolve()};r.addEventListener("message",s);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(i===!0)throw new Km("Stream was unwrapped");if(y5(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new $a(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await Me(o.promise,u?.signal),y5(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let f=u?.bytes??n.byteLength;if(n.byteLength<f){if(y5(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,f),new $a(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return l.read(u)}let h=n.sublist(0,f);return n.consume(f),h},async write(u,d){if(i===!0)throw new Km("Stream was unwrapped");r.send(u)||await ke(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return i||(i=!0,r.removeEventListener("message",s),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return l}function ws(r,e={}){let t=zm(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ye(e.maxDataLength));let n=e?.lengthDecoder??No,o=e?.lengthEncoder??ur;return{async read(s){let a=-1,c=new G;for(;;){let u=await t.read({...s,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new ef("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new b5(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new w5(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...s,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new $a(`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 $a(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(s,a){await t.write(new G(o(s.byteLength),s),a)},async writeV(s,a){let c=new G(...s.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Xe(r,e){let t=ws(r,e),n={read:async(o,i)=>{let s=await t.read(i);return o.decode(s)},write:async(o,i,s)=>{await t.write(i.encode(o),s)},writeV:async(o,i,s)=>{await t.writeV(o.map(a=>i.encode(a)),s)},pb:o=>({read:async i=>n.read(o,i),write:async(i,s)=>n.write(i,o,s),writeV:async(i,s)=>n.writeV(i,o,s),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var Bq=1024*1024*4,Mq=1024*1024*4,Gm=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new G,this.maxBufferSize=e.maxBufferSize??Bq,this.maxDataLength=e.maxDataLength??Mq,this.lengthDecoder=e.lengthDecoder??No,this.encodingLength=e.encodingLength??ye}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new E(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(i){if(i instanceof RangeError)break;throw i}if(t<0||t>this.maxDataLength)throw new ef("Invalid message length");let n=this.encodingLength(t),o=n+t;if(this.buffer.byteLength>=o){let i=this.buffer.sublist(n,o);this.buffer.consume(o),i.byteLength>0&&(yield i)}else break}}};var Fq=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function x5(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(r instanceof Uint8Array)return"Uint8Array";if(r.constructor===Object)return"Object";let t=Uq(r);return t||"Object"}function Uq(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(Fq.includes(e))return e}var w=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}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};w.uint=new w(0,"uint",!0);w.negint=new w(1,"negint",!0);w.bytes=new w(2,"bytes",!0);w.string=new w(3,"string",!0);w.array=new w(4,"array",!1);w.map=new w(5,"map",!1);w.tag=new w(6,"tag",!1);w.float=new w(7,"float",!0);w.false=new w(7,"false",!0);w.true=new w(7,"true",!0);w.null=new w(7,"null",!0);w.undefined=new w(7,"undefined",!0);w.break=new w(7,"break",!0);var N=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 tf=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",$q=new TextEncoder;function Wm(r){return tf&&globalThis.Buffer.isBuffer(r)}function Ha(r){return r instanceof Uint8Array?Wm(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Hq=24,qq=200,Il=tf?r=>r.length>=Hq?globalThis.Buffer.from(r):lA(r):r=>r.length>=qq?$q.encode(r):lA(r),Ho=r=>Uint8Array.from(r),dA=tf?(r,e,t)=>Wm(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),fA=tf?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Ha(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},hA=tf?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function jm(r,e){if(Wm(r)&&Wm(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 lA(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):(o>=55296&&o<=57343&&(o=65533),e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}var uA=4096;function pA(r){let e=r.length;if(e<=uA)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=uA));return t}var Vq=256,rf=class{constructor(e=Vq){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=hA(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=dA(n,0,this.cursor)}else t=fA(this.chunks,this.cursor);return e&&this.reset(),t}},Ym=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var W="CBOR decode error:",qo="CBOR encode error:",nf=[];nf[23]=1;nf[24]=2;nf[25]=3;nf[26]=5;nf[27]=9;function vi(r,e,t){if(r.length-e<t)throw new Error(`${W} not enough data for type`)}var zt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function sn(r,e,t){vi(r,e,1);let n=r[e];if(t.strict===!0&&n<zt[0])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);return n}function an(r,e,t){vi(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<zt[1])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);return n}function cn(r,e,t){vi(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<zt[2])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);return n}function ln(r,e,t){vi(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<zt[3])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${W} integers outside of the safe integer range are not supported`)}function mA(r,e,t,n){return new N(w.uint,sn(r,e+1,n),2)}function gA(r,e,t,n){return new N(w.uint,an(r,e+1,n),3)}function yA(r,e,t,n){return new N(w.uint,cn(r,e+1,n),5)}function wA(r,e,t,n){return new N(w.uint,ln(r,e+1,n),9)}function Mn(r,e){return Ze(r,0,e.value)}function Ze(r,e,t){if(t<zt[0]){let n=Number(t);r.push([e|n])}else if(t<zt[1]){let n=Number(t);r.push([e|24,n])}else if(t<zt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<zt[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<zt[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${W} encountered BigInt larger than allowable range`)}}Mn.encodedSize=function(e){return Ze.encodedSize(e.value)};Ze.encodedSize=function(e){return e<zt[0]?1:e<zt[1]?2:e<zt[2]?3:e<zt[3]?5:9};Mn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function bA(r,e,t,n){return new N(w.negint,-1-sn(r,e+1,n),2)}function xA(r,e,t,n){return new N(w.negint,-1-an(r,e+1,n),3)}function EA(r,e,t,n){return new N(w.negint,-1-cn(r,e+1,n),5)}var E5=BigInt(-1),vA=BigInt(1);function SA(r,e,t,n){let o=ln(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new N(w.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${W} integers outside of the safe integer range are not supported`);return new N(w.negint,E5-BigInt(o),9)}function Xm(r,e){let t=e.value,n=typeof t=="bigint"?t*E5-vA:t*-1-1;Ze(r,e.type.majorEncoded,n)}Xm.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*E5-vA:t*-1-1;return n<zt[0]?1:n<zt[1]?2:n<zt[2]?3:n<zt[3]?5:9};Xm.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function of(r,e,t,n){vi(r,e,t+n);let o=r.slice(e+t,e+t+n);return new N(w.bytes,o,t+n)}function AA(r,e,t,n){return of(r,e,1,t)}function TA(r,e,t,n){return of(r,e,2,sn(r,e+1,n))}function _A(r,e,t,n){return of(r,e,3,an(r,e+1,n))}function CA(r,e,t,n){return of(r,e,5,cn(r,e+1,n))}function IA(r,e,t,n){let o=ln(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer bytes lengths not supported`);return of(r,e,9,o)}function Qm(r){return r.encodedBytes===void 0&&(r.encodedBytes=w.equals(r.type,w.string)?Il(r.value):r.value),r.encodedBytes}function kl(r,e){let t=Qm(e);Ze(r,e.type.majorEncoded,t.length),r.push(t)}kl.encodedSize=function(e){let t=Qm(e);return Ze.encodedSize(t.length)+t.length};kl.compareTokens=function(e,t){return zq(Qm(e),Qm(t))};function zq(r,e){return r.length<e.length?-1:r.length>e.length?1:jm(r,e)}var kA=new TextDecoder,Wq=32;function jq(r,e,t){if(t-e<Wq){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return kA.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return kA.decode(r.subarray(e,t))}function sf(r,e,t,n,o){let i=t+n;vi(r,e,i);let s=new N(w.string,jq(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function RA(r,e,t,n){return sf(r,e,1,t,n)}function PA(r,e,t,n){return sf(r,e,2,sn(r,e+1,n),n)}function DA(r,e,t,n){return sf(r,e,3,an(r,e+1,n),n)}function LA(r,e,t,n){return sf(r,e,5,cn(r,e+1,n),n)}function NA(r,e,t,n){let o=ln(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer string lengths not supported`);return sf(r,e,9,o,n)}var OA=kl;function Rl(r,e,t,n){return new N(w.array,n,t)}function BA(r,e,t,n){return Rl(r,e,1,t)}function MA(r,e,t,n){return Rl(r,e,2,sn(r,e+1,n))}function FA(r,e,t,n){return Rl(r,e,3,an(r,e+1,n))}function UA(r,e,t,n){return Rl(r,e,5,cn(r,e+1,n))}function $A(r,e,t,n){let o=ln(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer array lengths not supported`);return Rl(r,e,9,o)}function HA(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${W} indefinite length items not allowed`);return Rl(r,e,1,1/0)}function Zm(r,e){Ze(r,w.array.majorEncoded,e.value)}Zm.compareTokens=Mn.compareTokens;Zm.encodedSize=function(e){return Ze.encodedSize(e.value)};function Pl(r,e,t,n){return new N(w.map,n,t)}function qA(r,e,t,n){return Pl(r,e,1,t)}function VA(r,e,t,n){return Pl(r,e,2,sn(r,e+1,n))}function KA(r,e,t,n){return Pl(r,e,3,an(r,e+1,n))}function zA(r,e,t,n){return Pl(r,e,5,cn(r,e+1,n))}function GA(r,e,t,n){let o=ln(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer map lengths not supported`);return Pl(r,e,9,o)}function WA(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${W} indefinite length items not allowed`);return Pl(r,e,1,1/0)}function Jm(r,e){Ze(r,w.map.majorEncoded,e.value)}Jm.compareTokens=Mn.compareTokens;Jm.encodedSize=function(e){return Ze.encodedSize(e.value)};function jA(r,e,t,n){return new N(w.tag,t,1)}function YA(r,e,t,n){return new N(w.tag,sn(r,e+1,n),2)}function XA(r,e,t,n){return new N(w.tag,an(r,e+1,n),3)}function QA(r,e,t,n){return new N(w.tag,cn(r,e+1,n),5)}function ZA(r,e,t,n){return new N(w.tag,ln(r,e+1,n),9)}function e1(r,e){Ze(r,w.tag.majorEncoded,e.value)}e1.compareTokens=Mn.compareTokens;e1.encodedSize=function(e){return Ze.encodedSize(e.value)};var v5=20,S5=21,A5=22,T5=23;function JA(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${W} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new N(w.null,null,1):new N(w.undefined,void 0,1)}function eT(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${W} indefinite length items not allowed`);return new N(w.break,void 0,1)}function _5(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${W} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${W} Infinity values are not supported`)}return new N(w.float,r,e)}function tT(r,e,t,n){return _5(C5(r,e+1),3,n)}function rT(r,e,t,n){return _5(I5(r,e+1),5,n)}function nT(r,e,t,n){return _5(aT(r,e+1),9,n)}function af(r,e,t){let n=e.value;if(n===!1)r.push([w.float.majorEncoded|v5]);else if(n===!0)r.push([w.float.majorEncoded|S5]);else if(n===null)r.push([w.float.majorEncoded|A5]);else if(n===void 0)r.push([w.float.majorEncoded|T5]);else{let o,i=!1;(!t||t.float64!==!0)&&(iT(n),o=C5(po,1),n===o||Number.isNaN(n)?(po[0]=249,r.push(po.slice(0,3)),i=!0):(sT(n),o=I5(po,1),n===o&&(po[0]=250,r.push(po.slice(0,5)),i=!0))),i||(Jq(n),o=aT(po,1),po[0]=251,r.push(po.slice(0,9)))}}af.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){iT(n);let o=C5(po,1);if(n===o||Number.isNaN(n))return 3;if(sT(n),o=I5(po,1),n===o)return 5}return 9};var oT=new ArrayBuffer(9),Fn=new DataView(oT,1),po=new Uint8Array(oT,0);function iT(r){if(r===1/0)Fn.setUint16(0,31744,!1);else if(r===-1/0)Fn.setUint16(0,64512,!1);else if(Number.isNaN(r))Fn.setUint16(0,32256,!1);else{Fn.setFloat32(0,r);let e=Fn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Fn.setUint16(0,31744,!1);else if(t===0)Fn.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Fn.setUint16(0,0):o<-14?Fn.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Fn.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function C5(r,e){if(r.length-e<2)throw new Error(`${W} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function sT(r){Fn.setFloat32(0,r,!1)}function I5(r,e){if(r.length-e<4)throw new Error(`${W} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Jq(r){Fn.setFloat64(0,r,!1)}function aT(r,e){if(r.length-e<8)throw new Error(`${W} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}af.compareTokens=Mn.compareTokens;function Re(r,e,t){throw new Error(`${W} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function t1(r){return()=>{throw new Error(`${W} ${r}`)}}var z=[];for(let r=0;r<=23;r++)z[r]=Re;z[24]=mA;z[25]=gA;z[26]=yA;z[27]=wA;z[28]=Re;z[29]=Re;z[30]=Re;z[31]=Re;for(let r=32;r<=55;r++)z[r]=Re;z[56]=bA;z[57]=xA;z[58]=EA;z[59]=SA;z[60]=Re;z[61]=Re;z[62]=Re;z[63]=Re;for(let r=64;r<=87;r++)z[r]=AA;z[88]=TA;z[89]=_A;z[90]=CA;z[91]=IA;z[92]=Re;z[93]=Re;z[94]=Re;z[95]=t1("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)z[r]=RA;z[120]=PA;z[121]=DA;z[122]=LA;z[123]=NA;z[124]=Re;z[125]=Re;z[126]=Re;z[127]=t1("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)z[r]=BA;z[152]=MA;z[153]=FA;z[154]=UA;z[155]=$A;z[156]=Re;z[157]=Re;z[158]=Re;z[159]=HA;for(let r=160;r<=183;r++)z[r]=qA;z[184]=VA;z[185]=KA;z[186]=zA;z[187]=GA;z[188]=Re;z[189]=Re;z[190]=Re;z[191]=WA;for(let r=192;r<=215;r++)z[r]=jA;z[216]=YA;z[217]=XA;z[218]=QA;z[219]=ZA;z[220]=Re;z[221]=Re;z[222]=Re;z[223]=Re;for(let r=224;r<=243;r++)z[r]=t1("simple values are not supported");z[244]=Re;z[245]=Re;z[246]=Re;z[247]=JA;z[248]=t1("simple values are not supported");z[249]=tT;z[250]=rT;z[251]=nT;z[252]=Re;z[253]=Re;z[254]=Re;z[255]=eT;var mo=[];for(let r=0;r<24;r++)mo[r]=new N(w.uint,r,1);for(let r=-1;r>=-24;r--)mo[31-r]=new N(w.negint,r,1);mo[64]=new N(w.bytes,new Uint8Array(0),1);mo[96]=new N(w.string,"",1);mo[128]=new N(w.array,0,1);mo[160]=new N(w.map,0,1);mo[244]=new N(w.false,!1,1);mo[245]=new N(w.true,!0,1);mo[246]=new N(w.null,null,1);function r1(r){switch(r.type){case w.false:return Ho([244]);case w.true:return Ho([245]);case w.null:return Ho([246]);case w.bytes:return r.value.length?void 0:Ho([64]);case w.string:return r.value===""?Ho([96]):void 0;case w.array:return r.value===0?Ho([128]):void 0;case w.map:return r.value===0?Ho([160]):void 0;case w.uint:return r.value<24?Ho([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return Ho([31-Number(r.value)])}}var tV={float64:!1,mapSorter:nV,quickEncodeToken:r1},fT=Object.freeze({float64:!0,mapSorter:oV,quickEncodeToken:r1});function k5(){let r=[];return r[w.uint.major]=Mn,r[w.negint.major]=Xm,r[w.bytes.major]=kl,r[w.string.major]=OA,r[w.array.major]=Zm,r[w.map.major]=Jm,r[w.tag.major]=e1,r[w.float.major]=af,r}var Dl=k5(),n1=new rf,lf=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(`${qo} object contains circular references`);return new r(t,e)}},bs={null:new N(w.null,null),undefined:new N(w.undefined,void 0),true:new N(w.true,!0),false:new N(w.false,!1),emptyArray:new N(w.array,0),emptyMap:new N(w.map,0)},Vo={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new N(w.float,r):r>=0?new N(w.uint,r):new N(w.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new N(w.uint,r):new N(w.negint,r)},Uint8Array(r,e,t,n){return new N(w.bytes,r)},string(r,e,t,n){return new N(w.string,r)},boolean(r,e,t,n){return r?bs.true:bs.false},null(r,e,t,n){return bs.null},undefined(r,e,t,n){return bs.undefined},ArrayBuffer(r,e,t,n){return new N(w.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new N(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[bs.emptyArray,new N(w.break)]:bs.emptyArray;n=lf.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Va(s,t,n);return t.addBreakTokens?[new N(w.array,r.length),o,new N(w.break)]:[new N(w.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length,a;if(s){a=new Array(s),n=lf.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let u of i){let d=o?r.get(u):r[u];c&&d===void 0||(a[l++]=[Va(u,t,n),Va(d,t,n)])}l<s&&(a.length=l)}return a?.length?(rV(a,t),t.addBreakTokens?[new N(w.map,a.length),a,new N(w.break)]:[new N(w.map,a.length),a]):t.addBreakTokens===!0?[bs.emptyMap,new N(w.break)]:bs.emptyMap},Tagged(r,e,t,n){return[new N(w.tag,r.tag),Va(r.value,t,n)]}};Vo.Map=Vo.Object;Vo.Buffer=Vo.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Vo[`${r}Array`]=Vo.DataView;function Va(r,e={},t){let n=x5(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Vo[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=Vo[n];if(!i)throw new Error(`${qo} unsupported type: ${n}`);return i(r,n,e,t)}function rV(r,e){e.mapSorter&&r.sort(e.mapSorter)}function nV(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=Dl[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function oV(r,e){if(r[0]instanceof N&&e[0]instanceof N){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=cT(t.value)),n._keyBytes||(n._keyBytes=cT(n.value)),jm(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function cT(r){return o1(r,Dl,fT)}function cf(r,e,t,n){if(Array.isArray(e))for(let o of e)cf(r,o,t,n);else t[e.type.major](r,e,n)}var lT=w.uint.majorEncoded,uT=w.negint.majorEncoded,iV=w.bytes.majorEncoded,sV=w.string.majorEncoded,dT=w.array.majorEncoded,aV=w.float.majorEncoded|v5,cV=w.float.majorEncoded|S5,lV=w.float.majorEncoded|A5,uV=w.float.majorEncoded|T5,dV=BigInt(-1),fV=BigInt(1);function hV(r){return r.addBreakTokens!==!0}function hT(r,e,t,n){let o=x5(e),i=t.typeEncoders&&t.typeEncoders[o];if(i){let s=i(e,o,t,n);if(s!=null){cf(r,s,Dl,t);return}}switch(o){case"null":r.push([lV]);return;case"undefined":r.push([uV]);return;case"boolean":r.push([e?cV:aV]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?af(r,new N(w.float,e),t):e>=0?Ze(r,lT,e):Ze(r,uT,e*-1-1);return;case"bigint":e>=BigInt(0)?Ze(r,lT,e):Ze(r,uT,e*dV-fV);return;case"string":{let s=Il(e);Ze(r,sV,s.length),r.push(s);return}case"Uint8Array":Ze(r,iV,e.length),r.push(e);return;case"Array":if(!e.length){r.push([dT]);return}n=lf.createCheck(n,e),Ze(r,dT,e.length);for(let s of e)hT(r,s,t,n);return;case"Object":case"Map":{let s=Vo.Object(e,o,t,n);cf(r,s,Dl,t)}return;default:{let s=Vo[o];if(!s)throw new Error(`${qo} unsupported type: ${o}`);let a=s(e,o,t,n);cf(r,a,Dl,t)}}}function o1(r,e,t,n){let o=n instanceof Uint8Array,i=o?new Ym(n):n1,s=Va(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(o||(i=new rf(l)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():Ha(i.chunks[0])}}return i.reset(),cf(i,s,e,t),i.toBytes(!0)}function Ko(r,e){return e=Object.assign({},tV,e),hV(e)?(n1.reset(),hT(n1,r,e,void 0),n1.toBytes(!0)):o1(r,Dl,e)}var pV={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},i1=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=mo[e];if(t===void 0){let n=z[e];if(!n)throw new Error(`${W} 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}},xs=Symbol.for("DONE"),Ll=Symbol.for("BREAK");function mV(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=Es(e,t);if(i===Ll){if(r.value===1/0)break;throw new Error(`${W} got unexpected break to lengthed array`)}if(i===xs)throw new Error(`${W} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function gV(r,e,t){let n=t.useMaps===!0,o=t.rejectDuplicateMapKeys===!0,i=n?void 0:{},s=n?new Map:void 0;for(let a=0;a<r.value;a++){let c=Es(e,t);if(c===Ll){if(r.value===1/0)break;throw new Error(`${W} got unexpected break to lengthed map`)}if(c===xs)throw new Error(`${W} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${W} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${W} found repeat map key "${c}"`);let l=Es(e,t);if(l===xs)throw new Error(`${W} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,l):i[c]=l}return n?s:i}function*yV(r,e,t){for(let n=0;n<r.value;n++){let o=Es(e,t);if(o===Ll){if(r.value===1/0)break;throw new Error(`${W} got unexpected break to lengthed map`)}if(o===xs)throw new Error(`${W} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=Es(e,t);if(i===xs)throw new Error(`${W} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function wV(r,e){let t=!1,n=function(){if(t)throw new Error(`${W} tag decode() may only be called once`);t=!0;let o=Es(r,e);if(o===xs)throw new Error(`${W} tag content missing`);if(o===Ll)throw new Error(`${W} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${W} tag decode() may only be called once`);t=!0;let o=r.next();if(!w.equals(o.type,w.map))throw new Error(`${W} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of yV(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function Es(r,e){if(r.done())return xs;let t=r.next();if(w.equals(t.type,w.break))return Ll;if(t.type.terminal)return t.value;if(w.equals(t.type,w.array))return mV(t,r,e);if(w.equals(t.type,w.map))return gV(t,r,e);if(w.equals(t.type,w.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=wV(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${W} tag decoder must call decode() or entries()`);return o}throw new Error(`${W} tag not supported (${t.value})`)}throw new Error("unsupported")}function R5(r,e){if(!(r instanceof Uint8Array))throw new Error(`${W} data to decode must be a Uint8Array`);e=Object.assign({},pV,e);let t=Ha(r),n=e.tokenizer||new i1(t,e),o=Es(n,e);if(o===xs)throw new Error(`${W} did not find any content to decode`);if(o===Ll)throw new Error(`${W} got unexpected break`);return[o,r.subarray(n.pos())]}function Pr(r,e){let[t,n]=R5(r,e);if(n.length>0)throw new Error(`${W} too many terminals, data makes no sense`);return t}var s1=class r{constructor(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=t}static decoder(e){return t=>new r(e,t())}static preserve(...e){let t={};for(let n of e)t[n]=r.decoder(n);return t}};Object.defineProperty(s1.prototype,Symbol.toStringTag,{value:"Tagged"});var c1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Nl=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},l1=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},uf=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function u1(r){return r[Symbol.asyncIterator]!=null}function pT(r,e){if(r.byteLength>e)throw new Nl("Message length too long")}var f1=r=>{let e=ye(r),t=nt(e);return ur(r,t),f1.bytes=e,t};f1.bytes=0;function Si(r,e){e=e??{};let t=e.lengthEncoder??f1,n=e?.maxDataLength??4194304;function*o(i){pT(i,n);let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return u1(r)?(async function*(){for await(let i of r)yield*o(i)})():(function*(){for(let i of r)yield*o(i)})()}Si.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??f1,n=e?.maxDataLength??4194304;return pT(r,n),new G(t(r.byteLength),r)};var Ka;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ka||(Ka={}));var P5=r=>{let e=No(r);return P5.bytes=ye(e),e};P5.bytes=0;function za(r,e){let t=new G,n=Ka.LENGTH,o=-1,i=e?.lengthDecoder??P5,s=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Ka.LENGTH)try{if(o=i(t),o<0)throw new c1("Invalid message length");if(o>a)throw new Nl("Message length too long");let l=i.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=Ka.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>s)throw new l1("Message length length too long");break}throw l}if(n===Ka.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=Ka.LENGTH}}}return u1(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new uf("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new uf("Unexpected end of input")})()}za.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:i,value:s}=await r.next(t);if(i===!0)return;s!=null&&(yield s)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}})();return za(n,{...e??{},onLength:i=>{t=i}})};function h1(r,e){if(typeof r=="string")return xV(r);if(typeof r=="number")return SV(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function xV(r){if(typeof r!="string"||r.length===0||r.length>100)throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let 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),i=n.toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw new Error(`Unknown unit "${i}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function EV(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 vV(r){let e=Math.abs(r);return e>=315576e5?Ga(r,e,315576e5,"year"):e>=26298e5?Ga(r,e,26298e5,"month"):e>=6048e5?Ga(r,e,6048e5,"week"):e>=864e5?Ga(r,e,864e5,"day"):e>=36e5?Ga(r,e,36e5,"hour"):e>=6e4?Ga(r,e,6e4,"minute"):e>=1e3?Ga(r,e,1e3,"second"):`${r} ms`}function SV(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return e?.long?vV(r):EV(r)}function Ga(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function D5(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=s,t.humanize=h1,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let f=0;f<u.length;f++)d=(d<<5)-d+u.charCodeAt(f),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u,d){let f,h=null,p,y;function g(...m){if(!g.enabled)return;let b=g,_=Number(new Date),R=_-(f||_);b.diff=R,b.prev=f,b.curr=_,f=_,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let D=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(U,C)=>{if(U==="%%")return"%";D++;let L=t.formatters[C];if(typeof L=="function"){let H=m[D];U=L.call(b,H),m.splice(D,1),D--}return U}),t.formatArgs.call(b,m),d?.onLog!=null&&d.onLog(...m),(b.log||t.log).apply(b,m)}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:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,y=t.enabled(u)),y),set:m=>{h=m}}),typeof t.init=="function"&&t.init(g),g}function n(u,d){let f=t(this.namespace+(typeof d>"u"?":":d)+u);return f.log=this.log,f}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,f=(typeof u=="string"?u:"").split(/[\s,]+/),h=f.length;for(d=0;d<h;d++)f[d]&&(u=f[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function i(){let u=[...t.names.map(a),...t.skips.map(a).map(d=>"-"+d)].join(",");return t.enable(""),u}function s(u){if(u[u.length-1]==="*")return!0;let d,f;for(d=0,f=t.skips.length;d<f;d++)if(t.skips[d].test(u))return!1;for(d=0,f=t.names.length;d<f;d++)if(t.names[d].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var p1=RV(),AV=["#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 TV(){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 _V(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+h1(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 CV=console.debug??console.log??(()=>{});function IV(r){try{r?p1?.setItem("debug",r):p1?.removeItem("debug")}catch{}}function kV(){let r;try{r=p1?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function RV(){try{return localStorage}catch{}}function PV(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var gT=D5({formatArgs:_V,save:IV,load:kV,useColors:TV,setupFormatters:PV,colors:AV,storage:p1,log:CV});var $r=gT;$r.formatters.b=r=>r==null?"undefined":Ce.baseEncode(r);$r.formatters.t=r=>r==null?"undefined":$t.baseEncode(r);$r.formatters.m=r=>r==null?"undefined":Tt.baseEncode(r);$r.formatters.p=r=>r==null?"undefined":r.toString();$r.formatters.c=r=>r==null?"undefined":r.toString();$r.formatters.k=r=>r==null?"undefined":r.toString();$r.formatters.a=r=>r==null?"undefined":r.toString();function yT(r,e=""){let t=wT(r.message),n=wT(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
2
+ "use strict";var HeliaVerifiedFetch=(()=>{var gF=Object.create;var Sp=Object.defineProperty;var yF=Object.getOwnPropertyDescriptor;var wF=Object.getOwnPropertyNames;var bF=Object.getPrototypeOf,xF=Object.prototype.hasOwnProperty;var $=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),xt=(r,e)=>{for(var t in e)Sp(r,t,{get:e[t],enumerable:!0})},qx=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wF(e))!xF.call(r,o)&&o!==t&&Sp(r,o,{get:()=>e[o],enumerable:!(n=yF(e,o))||n.enumerable});return r};var Yt=(r,e,t)=>(t=r!=null?gF(bF(r)):{},qx(e||!r||!r.__esModule?Sp(t,"default",{value:r,enumerable:!0}):t,r)),EF=r=>qx(Sp({},"__esModule",{value:!0}),r);var k8=$(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});pl.Netmask4Impl=void 0;pl.ip2long=hl;pl.long2ip=Fo;function Fo(r){let e=(r&-16777216)>>>24,t=(r&255<<16)>>>16,n=(r&65280)>>>8,o=r&255;return[e,t,n,o].join(".")}var mH=48,gH=97,yH=65;function wH(r){let e=0,t=10,n="9",o=0;r.length>1&&r[o]==="0"&&(r[o+1]==="x"||r[o+1]==="X"?(o+=2,t=16):"0"<=r[o+1]&&r[o+1]<="9"&&(o++,t=8,n="7"));let i=o;for(;o<r.length;){if("0"<=r[o]&&r[o]<=n)e=e*t+(r.charCodeAt(o)-mH)>>>0;else if(t===16)if("a"<=r[o]&&r[o]<="f")e=e*t+(10+r.charCodeAt(o)-gH)>>>0;else if("A"<=r[o]&&r[o]<="F")e=e*t+(10+r.charCodeAt(o)-yH)>>>0;else break;else break;if(e>4294967295)throw new Error("too large");o++}if(o===i)throw new Error("empty octet");return[e,o]}function hl(r){let e=[];for(let t=0;t<=3&&r.length!==0;t++){if(t>0){if(r[0]!==".")throw new Error("Invalid IP");r=r.substring(1)}let[n,o]=wH(r);r=r.substring(o),e.push(n)}if(r.length!==0)throw new Error("Invalid IP");switch(e.length){case 1:if(e[0]>4294967295)throw new Error("Invalid IP");return e[0]>>>0;case 2:if(e[0]>255||e[1]>16777215)throw new Error("Invalid IP");return(e[0]<<24|e[1])>>>0;case 3:if(e[0]>255||e[1]>255||e[2]>65535)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2])>>>0;case 4:if(e[0]>255||e[1]>255||e[2]>255||e[3]>255)throw new Error("Invalid IP");return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0;default:throw new Error("Invalid IP")}}var I8=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(!n){let o=e.split("/",2);e=o[0],n=o[1]}if(n||(n=32),typeof n=="string"&&n.indexOf(".")>-1){try{this.maskLong=hl(n)}catch{throw new Error("Invalid mask: "+n)}this.bitmask=NaN;for(let o=32;o>=0;o--)if(this.maskLong===4294967295<<32-o>>>0){this.bitmask=o;break}}else if(n||n===0)this.bitmask=parseInt(n,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(hl(e)&this.maskLong)>>>0}catch{throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+n);this.size=Math.pow(2,32-this.bitmask),this.base=Fo(this.netLong),this.mask=Fo(this.maskLong),this.hostmask=Fo(~this.maskLong),this.first=this.bitmask<=30?Fo(this.netLong+1):this.base,this.last=this.bitmask<=30?Fo(this.netLong+this.size-2):Fo(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?Fo(this.netLong+this.size-1):void 0}contains(e){return typeof e=="string"&&(e.indexOf("/")>0||e.split(".").length!==4)&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):(hl(e)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0}next(e=1){return new r(Fo(this.netLong+this.size*e),this.mask)}forEach(e){let t=hl(this.first),n=hl(this.last),o=0;for(;t<=n;)e(Fo(t),t,o),o++,t++}toString(){return this.base+"/"+this.bitmask}};pl.Netmask4Impl=I8});var CS=$(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});ml.Netmask6Impl=void 0;ml.ip6bigint=P8;ml.bigint2ip6=Na;var bH=k8(),R8=(1n<<128n)-1n;function P8(r){let e=r.indexOf("%");e!==-1&&(r=r.substring(0,e));let t=r.lastIndexOf(":");if(t!==-1&&r.indexOf(".",t)!==-1){let n=r.substring(t+1),o=(0,bH.ip2long)(n),i=r.substring(0,t+1)+"0:0";return _S(i)&~0xffffffffn|BigInt(o)}return _S(r)}function _S(r){let e=r.indexOf("::"),t;if(e!==-1){let o=r.substring(0,e),i=r.substring(e+2),s=o===""?[]:o.split(":"),a=i===""?[]:i.split(":"),c=8-s.length-a.length;if(c<0)throw new Error("Invalid IPv6: too many groups");t=[...s,...Array(c).fill("0"),...a]}else t=r.split(":");if(t.length!==8)throw new Error("Invalid IPv6: expected 8 groups, got "+t.length);let n=0n;for(let o=0;o<8;o++){let i=t[o];if(i.length===0||i.length>4)throw new Error('Invalid IPv6: bad group "'+i+'"');let s=parseInt(i,16);if(isNaN(s)||s<0||s>65535)throw new Error('Invalid IPv6: bad group "'+i+'"');n=n<<16n|BigInt(s)}return n}function Na(r){if(r<0n||r>R8)throw new Error("Invalid IPv6 address value");let e=[];for(let s=0;s<8;s++)e.unshift(Number(r&0xffffn)),r>>=16n;let t=-1,n=0,o=-1,i=0;for(let s=0;s<8;s++)e[s]===0?o===-1?(o=s,i=1):i++:(i>n&&i>=2&&(t=o,n=i),o=-1,i=0);if(i>n&&i>=2&&(t=o,n=i),t!==-1&&t+n===8&&t>0)return e.slice(0,t).map(a=>a.toString(16)).join(":")+"::";if(t===0)return"::"+e.slice(n).map(a=>a.toString(16)).join(":");if(t>0){let s=e.slice(0,t).map(c=>c.toString(16)),a=e.slice(t+n).map(c=>c.toString(16));return s.join(":")+"::"+a.join(":")}else return e.map(s=>s.toString(16)).join(":")}var D8=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");let n=t;if(n==null){let o=e.indexOf("/");o!==-1?(n=parseInt(e.substring(o+1),10),e=e.substring(0,o)):n=128}if(isNaN(n)||n<0||n>128)throw new Error("Invalid mask for IPv6: "+n);this.bitmask=n,this.bitmask===0?this.maskBigint=0n:this.maskBigint=R8>>BigInt(128-this.bitmask)<<BigInt(128-this.bitmask);try{this.netBigint=P8(e)&this.maskBigint}catch{throw new Error("Invalid IPv6 net address: "+e)}this.size=Number(1n<<BigInt(128-this.bitmask)),this.base=Na(this.netBigint),this.mask=Na(this.maskBigint),this.hostmask=Na(~this.maskBigint&R8),this.first=this.base,this.last=Na(this.netBigint+(1n<<BigInt(128-this.bitmask))-1n),this.broadcast=void 0}contains(e){return typeof e=="string"&&e.indexOf("/")>0&&(e=new r(e)),e instanceof r?this.contains(e.base)&&this.contains(e.last):(P8(e)&this.maskBigint)===this.netBigint}next(e=1){let t=1n<<BigInt(128-this.bitmask);return new r(Na(this.netBigint+t*BigInt(e)),this.bitmask)}forEach(e){let t=this.netBigint,n=1n<<BigInt(128-this.bitmask),o=this.netBigint+n-1n,i=0;for(;t<=o;)e(Na(t),Number(t),i),i++,t++}toString(){return this.base+"/"+this.bitmask}};ml.Netmask6Impl=D8});var IS=$(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.long2ip=us.ip2long=us.Netmask=void 0;var bm=k8();Object.defineProperty(us,"ip2long",{enumerable:!0,get:function(){return bm.ip2long}});Object.defineProperty(us,"long2ip",{enumerable:!0,get:function(){return bm.long2ip}});var xH=CS(),L8=class r{constructor(e,t){if(typeof e!="string")throw new Error("Missing `net' parameter");(e.indexOf("/")!==-1?e.substring(0,e.indexOf("/")):e).indexOf(":")!==-1?this._impl=new xH.Netmask6Impl(e,t):this._impl=new bm.Netmask4Impl(e,t),this.base=this._impl.base,this.mask=this._impl.mask,this.hostmask=this._impl.hostmask,this.bitmask=this._impl.bitmask,this.size=this._impl.size,this.first=this._impl.first,this.last=this._impl.last,this.broadcast=this._impl.broadcast,this._impl instanceof bm.Netmask4Impl?(this.maskLong=this._impl.maskLong,this.netLong=this._impl.netLong):(this.maskLong=0,this.netLong=0)}contains(e){return typeof e=="string"&&(e.indexOf("/")>0?e=new r(e):e.indexOf(":")===-1&&e.split(".").length!==4&&(e=new r(e))),e instanceof r?this.contains(e.base)&&this.contains(e.broadcast||e.last):this._impl.contains(e)}next(e=1){let t=this._impl.next(e);return new r(t.base,t.bitmask)}forEach(e){this._impl.forEach(e)}toString(){return this._impl.toString()}};us.Netmask=L8});var BT=$((Yme,G5)=>{"use strict";var hK=Object.prototype.hasOwnProperty,Nr="~";function bf(){}Object.create&&(bf.prototype=Object.create(null),new bf().__proto__||(Nr=!1));function pK(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function OT(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new pK(t,n||r,o),s=Nr?Nr+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],i]:r._events[s].push(i):(r._events[s]=i,r._eventsCount++),r}function T1(r,e){--r._eventsCount===0?r._events=new bf:delete r._events[e]}function gr(){this._events=new bf,this._eventsCount=0}gr.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)hK.call(t,n)&&e.push(Nr?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};gr.prototype.listeners=function(e){var t=Nr?Nr+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,s=new Array(i);o<i;o++)s[o]=n[o].fn;return s};gr.prototype.listenerCount=function(e){var t=Nr?Nr+e:e,n=this._events[t];return n?n.fn?1:n.length:0};gr.prototype.emit=function(e,t,n,o,i,s){var a=Nr?Nr+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,d;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,i),!0;case 6:return c.fn.call(c.context,t,n,o,i,s),!0}for(d=1,u=new Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,h;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].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[d].fn.apply(c[d].context,u)}}return!0};gr.prototype.on=function(e,t,n){return OT(this,e,t,n,!1)};gr.prototype.once=function(e,t,n){return OT(this,e,t,n,!0)};gr.prototype.removeListener=function(e,t,n,o){var i=Nr?Nr+e:e;if(!this._events[i])return this;if(!t)return T1(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&T1(this,i);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==t||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:T1(this,i)}return this};gr.prototype.removeAllListeners=function(e){var t;return e?(t=Nr?Nr+e:e,this._events[t]&&T1(this,t)):(this._events=new bf,this._eventsCount=0),this};gr.prototype.off=gr.prototype.removeListener;gr.prototype.addListener=gr.prototype.on;gr.prefixed=Nr;gr.EventEmitter=gr;typeof G5<"u"&&(G5.exports=gr)});var UT=$((y1e,FT)=>{FT.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(i,s){t[i]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=t[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){t[i]!==void 0?t[i]=s:o(i,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var v0=$((uye,Dw)=>{var lye=(function(){typeof Dw<"u"&&(Dw.exports=y);var r=86400,e=3200,t=146097*e/400,n=r*t,o=1e3*n,i=864e13,s=4294967296,a=1e6,c="000000000",l=Math.trunc||function(C){var L=C-C%1;return L==0&&(C<0||C===0&&1/C!=1/0)?-0:L},u=y.prototype,d=(y.fromDate=function(C){return new y(+C)},y.fromInt64BE=R(0,1,2,3,0,4),y.fromInt64LE=R(3,2,1,0,4,0),y.fromString=function(M){var L,H=new y,M=(M+="").replace(/^\s*[+\-]?\d+/,function(A){var A=+A,_=1970+(A-1970)%400;return H.year=A-_,_}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function(x,A,_){return A<0&&(_*=-1),L=6e4*(60*+A+ +_),""}).replace(/\.\d+$/,function(x){return H.nano=+(x+c).substr(1,9),""}).split(/\D+/);if(1<M.length?M[1]--:M[1]=0,H.time=L=Date.UTC.apply(Date,M)-(L||0),isNaN(L))throw new TypeError("Invalid Date");return g(H)},y.fromTimeT=function(C){return b(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=g(this);return(C.time%1e3*a+ +C.nano+1e9)%1e9},u.getTimeT=function(){var L=g(this),C=Math.floor(L.time/1e3),L=L.year;return L&&(C+=L*t*r/e),C},u.getYear=function(){return this.toDate().getUTCFullYear()+this.year},u.toDate=function(){return m(g(this).time)},u.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},u.toString=function(C){var L=this,H=L.toDate(),M={H:function(){return O(H.getUTCHours())},L:function(){return U(H.getUTCMilliseconds(),3)},M:function(){return O(H.getUTCMinutes())},N:function(){return U(L.getNano(),9)},S:function(){return O(H.getUTCSeconds())},Y:function(){var x=L.getYear();return 999999<x?"+"+x:9999<x?"+"+U(x,6):0<=x?U(x,4):-999999<=x?"-"+U(-x,6):x},a:function(){return h[H.getUTCDay()]},b:function(){return f[H.getUTCMonth()]},d:function(){return O(H.getUTCDate())},e:function(){return(function(x){return(9<x?"":" ")+(0|x)})(H.getUTCDate())},m:function(){return O(H.getUTCMonth()+1)}};return(function x(A){return A.replace(/%./g,function(_){var S=_[1],v=p[S],S=M[S];return v?x(v):S?S():_})})(C||d)},u.writeInt64BE=T(0,1,2,3,0,4),u.writeInt64LE=T(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),f=["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 y;function y(C,L,H){var M=this;if(!(M instanceof y))return new y(C,L,H);M.time=+C||0,M.nano=+L||0,M.year=+H||0,g(M)}function g(C){var L,H,M,x=C.year,A=C.time,_=C.nano,v=((_<0||a<=_)&&(_-=(H=Math.floor(_/a))*a,A+=H,H=1),x%e);return(A<-i||i<A||v)&&((L=l(A/o))&&(x+=L*e,A-=L*o),(M=m(A)).setUTCFullYear(v+M.getUTCFullYear()),M=(A=+M)+(L=l((x-=v)/e))*o,L&&-i<=M&&M<=i&&(x-=L*e,A=M),H=1),H&&(C.year=x,C.time=A,C.nano=_),C}function m(C){var L=new Date(0);return L.setTime(C),L}function b(x,M){x=+x||0;var H=l((M=(M|0)*s)/n)+l(x/n),M=M%n+x%n,x=l(M/n);return x&&(H+=x,M-=x*n),new y(1e3*M,0,H*e)}function T(C,L,H,M,x,A){return function(v,S){var B=g(this);v=v||new Array(8),D(v,S|=0);var I=Math.floor(B.time/1e3),B=B.year*(t*r/e),P=l(B/s)+l(I/s),B=B%s+I%s,I=Math.floor(B/s);return I&&(P+=I,B-=I*s),_(v,S+x,P),_(v,S+A,B),v};function _(v,S,P){v[S+C]=P>>24&255,v[S+L]=P>>16&255,v[S+H]=P>>8&255,v[S+M]=255&P}}function R(C,L,H,M,x,A){return function(v,S){D(v,S|=0);var P=_(v,S+x);return b(_(v,S+A),P)};function _(v,S){return 16777216*v[S+C]+(v[S+L]<<16|v[S+H]<<8|v[S+M])}}function D(C,L){if(C=C&&C.length,C==null)throw new TypeError("Invalid Buffer");if(C<L+8)throw new RangeError("Out of range")}function O(C){return(9<C?"":"0")+(0|C)}function U(C,L){return(c+(0|C)).substr(-L)}})()});var HC=$((U9e,$C)=>{"use strict";function zG(r){return r>=55296&&r<=56319}function GG(r){return r>=56320&&r<=57343}$C.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var o=t.length,i=0,s,a,c=0;c<o;c+=1){if(s=t.charCodeAt(c),a=t[c],zG(s)&&GG(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),i+=e(a),i===n)return t.slice(0,c+1);if(i>n)return t.slice(0,c-a.length+1)}return t}});var VC=$(($9e,qC)=>{"use strict";function WG(r){return r>=55296&&r<=56319}function jG(r){return r>=56320&&r<=57343}qC.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,o=null,i=null,s=0;s<t;s++)o=e.charCodeAt(s),jG(o)?i!=null&&WG(i)?n+=1:n+=3:o<=127?n+=1:o>=128&&o<=2047?n+=2:o>=2048&&o<=65535&&(n+=3),i=o;return n}});var zC=$((H9e,KC)=>{"use strict";var YG=HC(),XG=VC();KC.exports=YG.bind(null,XG)});var jC=$((q9e,WC)=>{"use strict";var QG=zC(),ZG=/[\/\?<>\\:\*\|"]/g,JG=/[\x00-\x1f\x80-\x9f]/g,eW=/^\.+$/,tW=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;function rW(r,e){for(var t=r.length;t>0&&(r[t-1]==="."||r[t-1]===" ");)t--;return t<r.length?r.slice(0,t)+e:r}function GC(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(ZG,e).replace(JG,e).replace(eW,e).replace(tW,e);return t=rW(t,e),QG(t,255)}WC.exports=function(r,e){var t=e&&e.replacement||"",n=GC(r,t);return t===""?n:GC(n,"")}});var ZC=$(su=>{"use strict";var iW="[object ArrayBuffer]",Oi=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===iW}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 i=0;i<n.length;i++)if(n[i]!==o[i])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 s of t)n+=s.byteLength;let o=new Uint8Array(n),i=0;for(let s of t){let a=this.toUint8Array(s);o.set(a,i),i+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},u7="string",sW=/^[0-9a-f\s]+$/i,aW=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,cW=/^[a-zA-Z0-9-_]+$/,R2=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=Oi.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return decodeURIComponent(escape(n))}},Vn=class{static toString(e,t=!1){let n=Oi.toArrayBuffer(e),o=new DataView(n),i="";for(let s=0;s<n.byteLength;s+=2){let a=o.getUint16(s,t);i+=String.fromCharCode(a)}return i}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let i=0;i<e.length;i++)o.setUint16(i*2,e.charCodeAt(i),t);return n}},P2=class r{static isHex(e){return typeof e===u7&&sW.test(e)}static isBase64(e){return typeof e===u7&&aW.test(e)}static isBase64Url(e){return typeof e===u7&&cW.test(e)}static ToString(e,t="utf8"){let n=Oi.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 Vn.toString(n,!0);case"utf16":case"utf16be":return Vn.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 Vn.fromString(e,!0);case"utf16":case"utf16be":return Vn.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Oi.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 R2.fromString(e);case"utf16":case"utf16be":return Vn.fromString(e);case"utf16le":case"usc2":return Vn.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 R2.toString(e);case"utf16":case"utf16be":return Vn.toString(e);case"utf16le":case"usc2":return Vn.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=Oi.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Oi.toUint8Array(e),n="",o=t.length;for(let i=0;i<o;i++){let s=t[i];s<16&&(n+="0"),n+=s.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 i=t.slice(o,o+2);n[o/2]=parseInt(i,16)}return n.buffer}static ToUtf16String(e,t=!1){return Vn.toString(e,t)}static FromUtf16String(e,t=!1){return Vn.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,"")||""}};P2.DEFAULT_UTF8_ENCODING="utf8";function lW(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let i in o)t[i]=o[i]}return t}function uW(...r){let e=r.map(o=>o.byteLength).reduce((o,i)=>o+i),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let i of o)t[n++]=i}),t.buffer}function dW(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}su.BufferSourceConverter=Oi;su.Convert=P2;su.assign=lW;su.combine=uW;su.isEqual=dW});var IR=$(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.parseCookie=_R;ni.parse=_R;ni.stringifyCookie=Yj;ni.stringifySetCookie=c3;ni.serialize=c3;ni.parseSetCookie=Xj;ni.stringifySetCookie=c3;ni.serialize=c3;var AR=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,TR=/^[\u0021-\u003A\u003C-\u007E]*$/,Kj=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,zj=/^[\u0020-\u003A\u003D-\u007E]*$/,Gj=/^-?\d+$/,Wj=Object.prototype.toString,jj=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function _R(r,e){let t=new jj,n=r.length;if(n<2)return t;let o=e?.decode||CR,i=0;do{let s=mb(r,i,n);if(s===-1)break;let a=pb(r,i,n);if(s>a){i=r.lastIndexOf(";",s-1)+1;continue}let c=Bs(r,i,s);t[c]===void 0&&(t[c]=o(Bs(r,s+1,a))),i=a+1}while(i<n);return t}function Yj(r,e){let t=e?.encode||encodeURIComponent,n=[];for(let o of Object.keys(r)){let i=r[o];if(i===void 0)continue;if(!AR.test(o))throw new TypeError(`cookie name is invalid: ${o}`);let s=t(i);if(!TR.test(s))throw new TypeError(`cookie val is invalid: ${i}`);n.push(`${o}=${s}`)}return n.join("; ")}function c3(r,e,t){let n=typeof r=="object"?r:{...t,name:r,value:String(e)},i=(typeof e=="object"?e:t)?.encode||encodeURIComponent;if(!AR.test(n.name))throw new TypeError(`argument name is invalid: ${n.name}`);let s=n.value?i(n.value):"";if(!TR.test(s))throw new TypeError(`argument val is invalid: ${n.value}`);let a=n.name+"="+s;if(n.maxAge!==void 0){if(!Number.isInteger(n.maxAge))throw new TypeError(`option maxAge is invalid: ${n.maxAge}`);a+="; Max-Age="+n.maxAge}if(n.domain){if(!Kj.test(n.domain))throw new TypeError(`option domain is invalid: ${n.domain}`);a+="; Domain="+n.domain}if(n.path){if(!zj.test(n.path))throw new TypeError(`option path is invalid: ${n.path}`);a+="; Path="+n.path}if(n.expires){if(!Qj(n.expires)||!Number.isFinite(n.expires.valueOf()))throw new TypeError(`option expires is invalid: ${n.expires}`);a+="; Expires="+n.expires.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.partitioned&&(a+="; Partitioned"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${n.priority}`)}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${n.sameSite}`)}return a}function Xj(r,e){let t=e?.decode||CR,n=r.length,o=pb(r,0,n),i=mb(r,0,o),s=i===-1?{name:"",value:t(Bs(r,0,o))}:{name:Bs(r,0,i),value:t(Bs(r,i+1,o))},a=o+1;for(;a<n;){let c=pb(r,a,n),l=mb(r,a,c),u=l===-1?Bs(r,a,c):Bs(r,a,l),d=l===-1?void 0:Bs(r,l+1,c);switch(u.toLowerCase()){case"httponly":s.httpOnly=!0;break;case"secure":s.secure=!0;break;case"partitioned":s.partitioned=!0;break;case"domain":s.domain=d;break;case"path":s.path=d;break;case"max-age":d&&Gj.test(d)&&(s.maxAge=Number(d));break;case"expires":if(!d)break;let f=new Date(d);Number.isFinite(f.valueOf())&&(s.expires=f);break;case"priority":if(!d)break;let h=d.toLowerCase();(h==="low"||h==="medium"||h==="high")&&(s.priority=h);break;case"samesite":if(!d)break;let p=d.toLowerCase();(p==="lax"||p==="strict"||p==="none")&&(s.sameSite=p);break}a=c+1}return s}function pb(r,e,t){let n=r.indexOf(";",e);return n===-1?t:n}function mb(r,e,t){let n=r.indexOf("=",e);return n<t?n:-1}function Bs(r,e,t){let n=e,o=t;do{let i=r.charCodeAt(n);if(i!==32&&i!==9)break}while(++n<o);for(;o>n;){let i=r.charCodeAt(o-1);if(i!==32&&i!==9)break;o--}return r.slice(n,o)}function CR(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function Qj(r){return Wj.call(r)==="[object Date]"}});var UD=$((kUe,FD)=>{FD.exports=p9;var MD=128,fX=127,hX=~fX,pX=Math.pow(2,31);function p9(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw p9.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=pX;)e[t++]=r&255|MD,r/=128;for(;r&hX;)e[t++]=r&255|MD,r>>>=7;return e[t]=r|0,p9.bytes=t-n+1,e}});var qD=$((RUe,HD)=>{HD.exports=m9;var mX=128,$D=127;function m9(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a||o>49)throw m9.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&$D)<<o:(s&$D)*Math.pow(2,o),o+=7}while(s>=mX);return m9.bytes=i-n,t}});var KD=$((PUe,VD)=>{var gX=Math.pow(2,7),yX=Math.pow(2,14),wX=Math.pow(2,21),bX=Math.pow(2,28),xX=Math.pow(2,35),EX=Math.pow(2,42),vX=Math.pow(2,49),SX=Math.pow(2,56),AX=Math.pow(2,63);VD.exports=function(r){return r<gX?1:r<yX?2:r<wX?3:r<bX?4:r<xX?5:r<EX?6:r<vX?7:r<SX?8:r<AX?9:10}});var Dy=$((DUe,zD)=>{zD.exports={encode:UD(),decode:qD(),encodingLength:KD()}});var uL=$((kHe,lL)=>{"use strict";lL.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let n=this._internalPositionFor(e,!1);if(t===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let o=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):o=!0,this._setInternalPos(n,e,t,o),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let t=this._internalPositionFor(e,!0);if(t!==-1)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let t=0;for(;t<this.length;)e(this.get(t),t,this),t++}map(e){let t=0,n=new Array(this.length);for(;t<this.length;)n[t]=e(this.get(t),t,this),t++;return n}reduce(e,t){let n=0,o=t;for(;n<this.length;){let i=this.get(n);o=e(o,i,n),n++}return o}find(e){let t=0,n,o;for(;t<this.length&&!n;)o=this.get(t),n=e(o),t++;return n?o:void 0}_internalPositionFor(e,t){let n=this._bytePosFor(e,t);if(n>=this._bitArrays.length)return-1;let o=this._bitArrays[n],i=e-n*7;if(!((o&1<<i)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(KX,0),c=~(4294967295<<i+1),l=cL(o&c);return a+l-1}_bytePosFor(e,t){let n=Math.floor(e/7),o=n+1;for(;!t&&this._bitArrays.length<o;)this._bitArrays.push(0);return n}_setBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]|=1<<e-t*7}_unsetBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]&=~(1<<e-t*7)}_setInternalPos(e,t,n,o){let i=this._data,s=[t,n];if(o)this._sortData(),i[e]=s;else{if(i.length)if(i[i.length-1][0]>=t)i.push(s);else if(i[0][0]<=t)i.unshift(s);else{let a=Math.round(i.length/2);this._data=i.slice(0,a).concat(s).concat(i.slice(a))}else this._data.push(s);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(zX),this._changedData=!1}bitField(){let e=[],t=8,n=0,o=0,i,s=this._bitArrays.slice();for(;s.length||n;){n===0&&(i=s.shift(),n=7);let c=Math.min(n,t),l=~(255<<c),u=i&l;o|=u<<8-t,i=i>>>c,n-=c,t-=c,(!t||!n&&!s.length)&&(e.push(o),o=0,t=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(GX)}};function KX(r,e){return r+cL(e)}function cL(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function zX(r,e){return r[0]-e[0]}function GX(r){return r[1]}});var QL=$((cze,XL)=>{"use strict";XL.exports={RTLD_LAZY:1,RTLD_NOW:2,RTLD_GLOBAL:256,RTLD_LOCAL:0,RTLD_DEEPBIND:8,E2BIG:7,EACCES:13,EADDRINUSE:98,EADDRNOTAVAIL:99,EAFNOSUPPORT:97,EAGAIN:11,EALREADY:114,EBADF:9,EBADMSG:74,EBUSY:16,ECANCELED:125,ECHILD:10,ECONNABORTED:103,ECONNREFUSED:111,ECONNRESET:104,EDEADLK:35,EDESTADDRREQ:89,EDOM:33,EDQUOT:122,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:113,EIDRM:43,EILSEQ:84,EINPROGRESS:115,EINTR:4,EINVAL:22,EIO:5,EISCONN:106,EISDIR:21,ELOOP:40,EMFILE:24,EMLINK:31,EMSGSIZE:90,EMULTIHOP:72,ENAMETOOLONG:36,ENETDOWN:100,ENETRESET:102,ENETUNREACH:101,ENFILE:23,ENOBUFS:105,ENODATA:61,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:37,ENOLINK:67,ENOMEM:12,ENOMSG:42,ENOPROTOOPT:92,ENOSPC:28,ENOSR:63,ENOSTR:60,ENOSYS:38,ENOTCONN:107,ENOTDIR:20,ENOTEMPTY:39,ENOTSOCK:88,ENOTSUP:95,ENOTTY:25,ENXIO:6,EOPNOTSUPP:95,EOVERFLOW:75,EPERM:1,EPIPE:32,EPROTO:71,EPROTONOSUPPORT:93,EPROTOTYPE:91,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:116,ETIME:62,ETIMEDOUT:110,ETXTBSY:26,EWOULDBLOCK:11,EXDEV:18,PRIORITY_LOW:19,PRIORITY_BELOW_NORMAL:10,PRIORITY_NORMAL:0,PRIORITY_ABOVE_NORMAL:-7,PRIORITY_HIGH:-14,PRIORITY_HIGHEST:-20,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:17,SIGSTKFLT:16,SIGCONT:18,SIGSTOP:19,SIGTSTP:20,SIGTTIN:21,SIGTTOU:22,SIGURG:23,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:29,SIGPOLL:29,SIGPWR:30,SIGSYS:31,UV_FS_SYMLINK_DIR:1,UV_FS_SYMLINK_JUNCTION:2,O_RDONLY:0,O_WRONLY:1,O_RDWR:2,UV_DIRENT_UNKNOWN:0,UV_DIRENT_FILE:1,UV_DIRENT_DIR:2,UV_DIRENT_LINK:3,UV_DIRENT_FIFO:4,UV_DIRENT_SOCKET:5,UV_DIRENT_CHAR:6,UV_DIRENT_BLOCK:7,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:64,O_EXCL:128,UV_FS_O_FILEMAP:0,O_NOCTTY:256,O_TRUNC:512,O_APPEND:1024,O_DIRECTORY:65536,O_NOATIME:262144,O_NOFOLLOW:131072,O_SYNC:1052672,O_DSYNC:4096,O_DIRECT:16384,O_NONBLOCK:2048,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,F_OK:0,R_OK:4,W_OK:2,X_OK:1,UV_FS_COPYFILE_EXCL:1,COPYFILE_EXCL:1,UV_FS_COPYFILE_FICLONE:2,COPYFILE_FICLONE:2,UV_FS_COPYFILE_FICLONE_FORCE:4,COPYFILE_FICLONE_FORCE:4,OPENSSL_VERSION_NUMBER:810549344,SSL_OP_ALL:2147485776,SSL_OP_ALLOW_NO_DHE_KEX:1024,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_ENCRYPT_THEN_MAC:524288,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_RENEGOTIATION:1073741824,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:0,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_NO_TLSv1_3:536870912,SSL_OP_PRIORITIZE_CHACHA:2097152,SSL_OP_TLS_ROLLBACK_BUG:8388608,ENGINE_METHOD_RSA:1,ENGINE_METHOD_DSA:2,ENGINE_METHOD_DH:4,ENGINE_METHOD_RAND:8,ENGINE_METHOD_EC:2048,ENGINE_METHOD_CIPHERS:64,ENGINE_METHOD_DIGESTS:128,ENGINE_METHOD_PKEY_METHS:512,ENGINE_METHOD_PKEY_ASN1_METHS:1024,ENGINE_METHOD_ALL:65535,ENGINE_METHOD_NONE:0,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,RSA_PKCS1_PADDING:1,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,RSA_PSS_SALTLEN_DIGEST:-1,RSA_PSS_SALTLEN_MAX_SIGN:-2,RSA_PSS_SALTLEN_AUTO:-2,defaultCoreCipherList:"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA",TLS1_VERSION:769,TLS1_1_VERSION:770,TLS1_2_VERSION:771,TLS1_3_VERSION:772,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}});var z9=$((Xze,iN)=>{"use strict";var oN=Object.prototype.toString;iN.exports=function(e){var t=oN.call(e),n=t==="[object Arguments]";return n||(n=t!=="[object Array]"&&e!==null&&typeof e=="object"&&typeof e.length=="number"&&e.length>=0&&oN.call(e.callee)==="[object Function]"),n}});var pN=$((Qze,hN)=>{"use strict";var fN;Object.keys||(up=Object.prototype.hasOwnProperty,G9=Object.prototype.toString,sN=z9(),W9=Object.prototype.propertyIsEnumerable,aN=!W9.call({toString:null},"toString"),cN=W9.call(function(){},"prototype"),dp=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],i4=function(r){var e=r.constructor;return e&&e.prototype===r},lN={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},uN=(function(){if(typeof window>"u")return!1;for(var r in window)try{if(!lN["$"+r]&&up.call(window,r)&&window[r]!==null&&typeof window[r]=="object")try{i4(window[r])}catch{return!0}}catch{return!0}return!1})(),dN=function(r){if(typeof window>"u"||!uN)return i4(r);try{return i4(r)}catch{return!1}},fN=function(e){var t=e!==null&&typeof e=="object",n=G9.call(e)==="[object Function]",o=sN(e),i=t&&G9.call(e)==="[object String]",s=[];if(!t&&!n&&!o)throw new TypeError("Object.keys called on a non-object");var a=cN&&n;if(i&&e.length>0&&!up.call(e,0))for(var c=0;c<e.length;++c)s.push(String(c));if(o&&e.length>0)for(var l=0;l<e.length;++l)s.push(String(l));else for(var u in e)!(a&&u==="prototype")&&up.call(e,u)&&s.push(String(u));if(aN)for(var d=dN(e),f=0;f<dp.length;++f)!(d&&dp[f]==="constructor")&&up.call(e,dp[f])&&s.push(dp[f]);return s});var up,G9,sN,W9,aN,cN,dp,i4,lN,uN,dN;hN.exports=fN});var wN=$((Zze,yN)=>{"use strict";var eZ=Array.prototype.slice,tZ=z9(),mN=Object.keys,s4=mN?function(e){return mN(e)}:pN(),gN=Object.keys;s4.shim=function(){if(Object.keys){var e=(function(){var t=Object.keys(arguments);return t&&t.length===arguments.length})(1,2);e||(Object.keys=function(n){return tZ(n)?gN(eZ.call(n)):gN(n)})}else Object.keys=s4;return Object.keys||s4};yN.exports=s4});var fp=$((Jze,bN)=>{"use strict";var a4=Object.defineProperty||!1;if(a4)try{a4({},"a",{value:1})}catch{a4=!1}bN.exports=a4});var j9=$((eGe,xN)=>{"use strict";xN.exports=SyntaxError});var Sr=$((tGe,EN)=>{"use strict";EN.exports=TypeError});var SN=$((rGe,vN)=>{"use strict";vN.exports=Object.getOwnPropertyDescriptor});var Bu=$((nGe,AN)=>{"use strict";var c4=SN();if(c4)try{c4([],"length")}catch{c4=null}AN.exports=c4});var Y9=$((oGe,CN)=>{"use strict";var TN=fp(),rZ=j9(),Mu=Sr(),_N=Bu();CN.exports=function(e,t,n){if(!e||typeof e!="object"&&typeof e!="function")throw new Mu("`obj` must be an object or a function`");if(typeof t!="string"&&typeof t!="symbol")throw new Mu("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Mu("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Mu("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Mu("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Mu("`loose`, if provided, must be a boolean");var o=arguments.length>3?arguments[3]:null,i=arguments.length>4?arguments[4]:null,s=arguments.length>5?arguments[5]:null,a=arguments.length>6?arguments[6]:!1,c=!!_N&&_N(e,t);if(TN)TN(e,t,{configurable:s===null&&c?c.configurable:!s,enumerable:o===null&&c?c.enumerable:!o,value:n,writable:i===null&&c?c.writable:!i});else if(a||!o&&!i&&!s)e[t]=n;else throw new rZ("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}});var Q9=$((iGe,kN)=>{"use strict";var X9=fp(),IN=function(){return!!X9};IN.hasArrayLengthDefineBug=function(){if(!X9)return null;try{return X9([],"length",{value:1}).length!==1}catch{return!0}};kN.exports=IN});var Z9=$((sGe,LN)=>{"use strict";var nZ=wN(),oZ=typeof Symbol=="function"&&typeof Symbol("foo")=="symbol",iZ=Object.prototype.toString,sZ=Array.prototype.concat,RN=Y9(),aZ=function(r){return typeof r=="function"&&iZ.call(r)==="[object Function]"},PN=Q9()(),cZ=function(r,e,t,n){if(e in r){if(n===!0){if(r[e]===t)return}else if(!aZ(n)||!n())return}PN?RN(r,e,t,!0):RN(r,e,t)},DN=function(r,e){var t=arguments.length>2?arguments[2]:{},n=nZ(e);oZ&&(n=sZ.call(n,Object.getOwnPropertySymbols(e)));for(var o=0;o<n.length;o+=1)cZ(r,n[o],e[n[o]],t[n[o]])};DN.supportsDescriptors=!!PN;LN.exports=DN});var J9=$((aGe,NN)=>{"use strict";NN.exports=Object});var BN=$((cGe,ON)=>{"use strict";ON.exports=Error});var FN=$((lGe,MN)=>{"use strict";MN.exports=EvalError});var $N=$((uGe,UN)=>{"use strict";UN.exports=RangeError});var qN=$((dGe,HN)=>{"use strict";HN.exports=ReferenceError});var KN=$((fGe,VN)=>{"use strict";VN.exports=URIError});var ex=$((hGe,zN)=>{"use strict";zN.exports=Math.abs});var hp=$((pGe,GN)=>{"use strict";GN.exports=Math.floor});var jN=$((mGe,WN)=>{"use strict";WN.exports=Math.max});var XN=$((gGe,YN)=>{"use strict";YN.exports=Math.min});var ZN=$((yGe,QN)=>{"use strict";QN.exports=Math.pow});var eO=$((wGe,JN)=>{"use strict";JN.exports=Math.round});var l4=$((bGe,tO)=>{"use strict";tO.exports=Number.isNaN||function(e){return e!==e}});var nO=$((xGe,rO)=>{"use strict";var lZ=l4();rO.exports=function(e){return lZ(e)||e===0?e:e<0?-1:1}});var tx=$((EGe,oO)=>{"use strict";oO.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},t=Symbol("test"),n=Object(t);if(typeof t=="string"||Object.prototype.toString.call(t)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var o=42;e[t]=o;for(var i in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var s=Object.getOwnPropertySymbols(e);if(s.length!==1||s[0]!==t||!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var a=Object.getOwnPropertyDescriptor(e,t);if(a.value!==o||a.enumerable!==!0)return!1}return!0}});var aO=$((vGe,sO)=>{"use strict";var iO=typeof Symbol<"u"&&Symbol,uZ=tx();sO.exports=function(){return typeof iO!="function"||typeof Symbol!="function"||typeof iO("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:uZ()}});var rx=$((SGe,cO)=>{"use strict";cO.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var nx=$((AGe,lO)=>{"use strict";var dZ=J9();lO.exports=dZ.getPrototypeOf||null});var fO=$((TGe,dO)=>{"use strict";var fZ="Function.prototype.bind called on incompatible ",hZ=Object.prototype.toString,pZ=Math.max,mZ="[object Function]",uO=function(e,t){for(var n=[],o=0;o<e.length;o+=1)n[o]=e[o];for(var i=0;i<t.length;i+=1)n[i+e.length]=t[i];return n},gZ=function(e,t){for(var n=[],o=t||0,i=0;o<e.length;o+=1,i+=1)n[i]=e[o];return n},yZ=function(r,e){for(var t="",n=0;n<r.length;n+=1)t+=r[n],n+1<r.length&&(t+=e);return t};dO.exports=function(e){var t=this;if(typeof t!="function"||hZ.apply(t)!==mZ)throw new TypeError(fZ+t);for(var n=gZ(arguments,1),o,i=function(){if(this instanceof o){var u=t.apply(this,uO(n,arguments));return Object(u)===u?u:this}return t.apply(e,uO(n,arguments))},s=pZ(0,t.length-n.length),a=[],c=0;c<s;c++)a[c]="$"+c;if(o=Function("binder","return function ("+yZ(a,",")+"){ return binder.apply(this,arguments); }")(i),t.prototype){var l=function(){};l.prototype=t.prototype,o.prototype=new l,l.prototype=null}return o}});var Fu=$((_Ge,hO)=>{"use strict";var wZ=fO();hO.exports=Function.prototype.bind||wZ});var u4=$((CGe,pO)=>{"use strict";pO.exports=Function.prototype.call});var d4=$((IGe,mO)=>{"use strict";mO.exports=Function.prototype.apply});var yO=$((kGe,gO)=>{"use strict";gO.exports=typeof Reflect<"u"&&Reflect&&Reflect.apply});var ox=$((RGe,wO)=>{"use strict";var bZ=Fu(),xZ=d4(),EZ=u4(),vZ=yO();wO.exports=vZ||bZ.call(EZ,xZ)});var f4=$((PGe,bO)=>{"use strict";var SZ=Fu(),AZ=Sr(),TZ=u4(),_Z=ox();bO.exports=function(e){if(e.length<1||typeof e[0]!="function")throw new AZ("a function is required");return _Z(SZ,TZ,e)}});var TO=$((DGe,AO)=>{"use strict";var CZ=f4(),xO=Bu(),vO;try{vO=[].__proto__===Array.prototype}catch(r){if(!r||typeof r!="object"||!("code"in r)||r.code!=="ERR_PROTO_ACCESS")throw r}var ix=!!vO&&xO&&xO(Object.prototype,"__proto__"),SO=Object,EO=SO.getPrototypeOf;AO.exports=ix&&typeof ix.get=="function"?CZ([ix.get]):typeof EO=="function"?function(e){return EO(e==null?e:SO(e))}:!1});var RO=$((LGe,kO)=>{"use strict";var _O=rx(),CO=nx(),IO=TO();kO.exports=_O?function(e){return _O(e)}:CO?function(e){if(!e||typeof e!="object"&&typeof e!="function")throw new TypeError("getProto: not an object");return CO(e)}:IO?function(e){return IO(e)}:null});var sx=$((NGe,PO)=>{"use strict";var IZ=Function.prototype.call,kZ=Object.prototype.hasOwnProperty,RZ=Fu();PO.exports=RZ.call(IZ,kZ)});var Vu=$((OGe,MO)=>{"use strict";var ge,PZ=J9(),DZ=BN(),LZ=FN(),NZ=$N(),OZ=qN(),qu=j9(),Hu=Sr(),BZ=KN(),MZ=ex(),FZ=hp(),UZ=jN(),$Z=XN(),HZ=ZN(),qZ=eO(),VZ=nO(),OO=Function,ax=function(r){try{return OO('"use strict"; return ('+r+").constructor;")()}catch{}},pp=Bu(),KZ=fp(),cx=function(){throw new Hu},zZ=pp?(function(){try{return arguments.callee,cx}catch{try{return pp(arguments,"callee").get}catch{return cx}}})():cx,Uu=aO()(),jt=RO(),GZ=nx(),WZ=rx(),BO=d4(),mp=u4(),$u={},jZ=typeof Uint8Array>"u"||!jt?ge:jt(Uint8Array),Dc={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?ge:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?ge:ArrayBuffer,"%ArrayIteratorPrototype%":Uu&&jt?jt([][Symbol.iterator]()):ge,"%AsyncFromSyncIteratorPrototype%":ge,"%AsyncFunction%":$u,"%AsyncGenerator%":$u,"%AsyncGeneratorFunction%":$u,"%AsyncIteratorPrototype%":$u,"%Atomics%":typeof Atomics>"u"?ge:Atomics,"%BigInt%":typeof BigInt>"u"?ge:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?ge:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?ge:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?ge:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":DZ,"%eval%":eval,"%EvalError%":LZ,"%Float16Array%":typeof Float16Array>"u"?ge:Float16Array,"%Float32Array%":typeof Float32Array>"u"?ge:Float32Array,"%Float64Array%":typeof Float64Array>"u"?ge:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?ge:FinalizationRegistry,"%Function%":OO,"%GeneratorFunction%":$u,"%Int8Array%":typeof Int8Array>"u"?ge:Int8Array,"%Int16Array%":typeof Int16Array>"u"?ge:Int16Array,"%Int32Array%":typeof Int32Array>"u"?ge:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Uu&&jt?jt(jt([][Symbol.iterator]())):ge,"%JSON%":typeof JSON=="object"?JSON:ge,"%Map%":typeof Map>"u"?ge:Map,"%MapIteratorPrototype%":typeof Map>"u"||!Uu||!jt?ge:jt(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":PZ,"%Object.getOwnPropertyDescriptor%":pp,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?ge:Promise,"%Proxy%":typeof Proxy>"u"?ge:Proxy,"%RangeError%":NZ,"%ReferenceError%":OZ,"%Reflect%":typeof Reflect>"u"?ge:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?ge:Set,"%SetIteratorPrototype%":typeof Set>"u"||!Uu||!jt?ge:jt(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?ge:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Uu&&jt?jt(""[Symbol.iterator]()):ge,"%Symbol%":Uu?Symbol:ge,"%SyntaxError%":qu,"%ThrowTypeError%":zZ,"%TypedArray%":jZ,"%TypeError%":Hu,"%Uint8Array%":typeof Uint8Array>"u"?ge:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?ge:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?ge:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?ge:Uint32Array,"%URIError%":BZ,"%WeakMap%":typeof WeakMap>"u"?ge:WeakMap,"%WeakRef%":typeof WeakRef>"u"?ge:WeakRef,"%WeakSet%":typeof WeakSet>"u"?ge:WeakSet,"%Function.prototype.call%":mp,"%Function.prototype.apply%":BO,"%Object.defineProperty%":KZ,"%Object.getPrototypeOf%":GZ,"%Math.abs%":MZ,"%Math.floor%":FZ,"%Math.max%":UZ,"%Math.min%":$Z,"%Math.pow%":HZ,"%Math.round%":qZ,"%Math.sign%":VZ,"%Reflect.getPrototypeOf%":WZ};if(jt)try{null.error}catch(r){DO=jt(jt(r)),Dc["%Error.prototype%"]=DO}var DO,YZ=function r(e){var t;if(e==="%AsyncFunction%")t=ax("async function () {}");else if(e==="%GeneratorFunction%")t=ax("function* () {}");else if(e==="%AsyncGeneratorFunction%")t=ax("async function* () {}");else if(e==="%AsyncGenerator%"){var n=r("%AsyncGeneratorFunction%");n&&(t=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var o=r("%AsyncGenerator%");o&&jt&&(t=jt(o.prototype))}return Dc[e]=t,t},LO={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},gp=Fu(),h4=sx(),XZ=gp.call(mp,Array.prototype.concat),QZ=gp.call(BO,Array.prototype.splice),NO=gp.call(mp,String.prototype.replace),p4=gp.call(mp,String.prototype.slice),ZZ=gp.call(mp,RegExp.prototype.exec),JZ=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,eJ=/\\(\\)?/g,tJ=function(e){var t=p4(e,0,1),n=p4(e,-1);if(t==="%"&&n!=="%")throw new qu("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&t!=="%")throw new qu("invalid intrinsic syntax, expected opening `%`");var o=[];return NO(e,JZ,function(i,s,a,c){o[o.length]=a?NO(c,eJ,"$1"):s||i}),o},rJ=function(e,t){var n=e,o;if(h4(LO,n)&&(o=LO[n],n="%"+o[0]+"%"),h4(Dc,n)){var i=Dc[n];if(i===$u&&(i=YZ(n)),typeof i>"u"&&!t)throw new Hu("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:o,name:n,value:i}}throw new qu("intrinsic "+e+" does not exist!")};MO.exports=function(e,t){if(typeof e!="string"||e.length===0)throw new Hu("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof t!="boolean")throw new Hu('"allowMissing" argument must be a boolean');if(ZZ(/^%?[^%]*%?$/,e)===null)throw new qu("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=tJ(e),o=n.length>0?n[0]:"",i=rJ("%"+o+"%",t),s=i.name,a=i.value,c=!1,l=i.alias;l&&(o=l[0],QZ(n,XZ([0,1],l)));for(var u=1,d=!0;u<n.length;u+=1){var f=n[u],h=p4(f,0,1),p=p4(f,-1);if((h==='"'||h==="'"||h==="`"||p==='"'||p==="'"||p==="`")&&h!==p)throw new qu("property names with quotes must have matching quotes");if((f==="constructor"||!d)&&(c=!0),o+="."+f,s="%"+o+"%",h4(Dc,s))a=Dc[s];else if(a!=null){if(!(f in a)){if(!t)throw new Hu("base intrinsic for "+e+" exists, but the property is not available.");return}if(pp&&u+1>=n.length){var y=pp(a,f);d=!!y,d&&"get"in y&&!("originalValue"in y.get)?a=y.get:a=a[f]}else d=h4(a,f),a=a[f];d&&!c&&(Dc[s]=a)}}return a}});var qO=$((BGe,HO)=>{"use strict";var nJ=Vu(),FO=Y9(),oJ=Q9()(),UO=Bu(),$O=Sr(),iJ=nJ("%Math.floor%");HO.exports=function(e,t){if(typeof e!="function")throw new $O("`fn` is not a function");if(typeof t!="number"||t<0||t>4294967295||iJ(t)!==t)throw new $O("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],o=!0,i=!0;if("length"in e&&UO){var s=UO(e,"length");s&&!s.configurable&&(o=!1),s&&!s.writable&&(i=!1)}return(o||i||!n)&&(oJ?FO(e,"length",t,!0,!0):FO(e,"length",t)),e}});var KO=$((MGe,VO)=>{"use strict";var sJ=Fu(),aJ=d4(),cJ=ox();VO.exports=function(){return cJ(sJ,aJ,arguments)}});var lx=$((FGe,m4)=>{"use strict";var lJ=qO(),zO=fp(),uJ=f4(),GO=KO();m4.exports=function(e){var t=uJ(arguments),n=1+e.length-(arguments.length-1);return lJ(t,n>0?n:0,!0)};zO?zO(m4.exports,"apply",{value:GO}):m4.exports.apply=GO});var ra=$((UGe,YO)=>{"use strict";var WO=Vu(),jO=f4(),dJ=jO([WO("%String.prototype.indexOf%")]);YO.exports=function(e,t){var n=WO(e,!!t);return typeof n=="function"&&dJ(e,".prototype.")>-1?jO([n]):n}});var QO=$(($Ge,XO)=>{"use strict";var fJ=l4();XO.exports=function(e){return(typeof e=="number"||typeof e=="bigint")&&!fJ(e)&&e!==1/0&&e!==-1/0}});var g4=$((HGe,ZO)=>{"use strict";var hJ=ex(),pJ=hp(),mJ=l4(),gJ=QO();ZO.exports=function(e){if(typeof e!="number"||mJ(e)||!gJ(e))return!1;var t=hJ(e);return pJ(t)===t}});var ux=$((qGe,eB)=>{"use strict";var JO=Sr(),yJ=ra(),wJ=g4(),bJ=yJ("Number.prototype.toString");eB.exports=function(e,t){if(typeof e!="number")throw new JO("Assertion failed: `x` must be a Number");if(!wJ(t)||t<2||t>36)throw new JO("Assertion failed: `radix` must be an integer >= 2 and <= 36");return bJ(e,t)}});var rB=$((VGe,tB)=>{"use strict";var xJ=ra(),dx=Sr(),EJ=g4(),vJ=xJ("String.prototype.slice");tB.exports=function(e,t,n){if(typeof e!="string")throw new dx("Assertion failed: `string` must be a String");if(typeof t!="string")throw new dx("Assertion failed: `searchValue` must be a String");if(!EJ(n)||n<0)throw new dx("Assertion failed: `fromIndex` must be a non-negative integer");var o=e.length;if(t===""&&n<=o)return n;for(var i=t.length,s=n;s<=o-i;s+=1){var a=vJ(e,s,s+i);if(a===t)return s}return-1}});var fx=$((KGe,nB)=>{"use strict";var y4=Sr(),SJ=ra(),AJ=g4(),TJ=SJ("String.prototype.slice");nB.exports=function(e,t,n,o){if(typeof e!="string")throw new y4("Assertion failed: `S` must be a String");if(!AJ(t)||t<0)throw new y4("Assertion failed: `maxLength` must be a non-negative integer");if(typeof n!="string")throw new y4("Assertion failed: `fillString` must be a String");if(o!=="start"&&o!=="end"&&o!=="START"&&o!=="END")throw new y4("Assertion failed: `placement` must be ~START~ or ~END~");var i=e.length;if(t<=i||n==="")return e;for(var s=t-i,a="";a.length<s;)a+=n;return a=TJ(a,0,s),o==="start"||o==="START"?a+e:e+a}});var sB=$((zGe,iB)=>{"use strict";var oB=Sr(),hx=ra(),_J=hx("String.prototype.charCodeAt"),CJ=hx("Number.prototype.toString"),IJ=hx("String.prototype.toLowerCase"),kJ=fx();iB.exports=function(e){if(typeof e!="string"||e.length!==1)throw new oB("Assertion failed: `C` must be a single code unit");var t=_J(e,0);if(t>65535)throw new oB("`Assertion failed: numeric value of `C` must be <= 0xFFFF");return"\\u"+kJ(IJ(CJ(t,16)),4,"0","start")}});var cB=$((GGe,aB)=>{"use strict";var RJ=hp();aB.exports=function(e){return typeof e=="bigint"?e:RJ(e)}});var uB=$((WGe,lB)=>{"use strict";var PJ=hp();lB.exports=function(e,t){var n=e%t;return PJ(n>=0?n:n+t)}});var fB=$((jGe,dB)=>{"use strict";dB.exports=uB()});var pB=$((YGe,hB)=>{"use strict";var DJ=fB();hB.exports=function(e,t){return DJ(e,t)}});var px=$((XGe,mB)=>{"use strict";mB.exports=function(e){return typeof e=="number"&&e>=0&&e<=1114111&&(e|0)===e}});var yB=$((QGe,gB)=>{"use strict";var LJ=Vu(),NJ=Sr(),mx=LJ("%String.fromCharCode%"),OJ=cB(),BJ=pB(),MJ=px();gB.exports=function(e){if(!MJ(e))throw new NJ("Assertion failed: `cp` must be >= 0 and <= 0x10FFFF");if(e<=65535)return mx(e);var t=mx(OJ((e-65536)/1024)+55296),n=mx(BJ(e-65536,1024)+56320);return t+n}});var w4=$((ZGe,wB)=>{"use strict";wB.exports=function(e){return typeof e=="number"&&e>=55296&&e<=56319}});var b4=$((JGe,bB)=>{"use strict";bB.exports=function(e){return typeof e=="number"&&e>=56320&&e<=57343}});var SB=$((eWe,vB)=>{"use strict";var EB=Function.prototype.toString,Ku=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,yx,x4;if(typeof Ku=="function"&&typeof Object.defineProperty=="function")try{yx=Object.defineProperty({},"length",{get:function(){throw x4}}),x4={},Ku(function(){throw 42},null,yx)}catch(r){r!==x4&&(Ku=null)}else Ku=null;var FJ=/^\s*class\b/,wx=function(e){try{var t=EB.call(e);return FJ.test(t)}catch{return!1}},gx=function(e){try{return wx(e)?!1:(EB.call(e),!0)}catch{return!1}},E4=Object.prototype.toString,UJ="[object Object]",$J="[object Function]",HJ="[object GeneratorFunction]",qJ="[object HTMLAllCollection]",VJ="[object HTML document.all class]",KJ="[object HTMLCollection]",zJ=typeof Symbol=="function"&&!!Symbol.toStringTag,GJ=!(0 in[,]),bx=function(){return!1};typeof document=="object"&&(xB=document.all,E4.call(xB)===E4.call(document.all)&&(bx=function(e){if((GJ||!e)&&(typeof e>"u"||typeof e=="object"))try{var t=E4.call(e);return(t===qJ||t===VJ||t===KJ||t===UJ)&&e("")==null}catch{}return!1}));var xB;vB.exports=Ku?function(e){if(bx(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;try{Ku(e,null,yx)}catch(t){if(t!==x4)return!1}return!wx(e)&&gx(e)}:function(e){if(bx(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;if(zJ)return gx(e);if(wx(e))return!1;var t=E4.call(e);return t!==$J&&t!==HJ&&!/^\[object HTML/.test(t)?!1:gx(e)}});var xx=$((tWe,TB)=>{"use strict";var WJ=SB(),jJ=Object.prototype.toString,AB=Object.prototype.hasOwnProperty,YJ=function(e,t,n){for(var o=0,i=e.length;o<i;o++)AB.call(e,o)&&(n==null?t(e[o],o,e):t.call(n,e[o],o,e))},XJ=function(e,t,n){for(var o=0,i=e.length;o<i;o++)n==null?t(e.charAt(o),o,e):t.call(n,e.charAt(o),o,e)},QJ=function(e,t,n){for(var o in e)AB.call(e,o)&&(n==null?t(e[o],o,e):t.call(n,e[o],o,e))};function ZJ(r){return jJ.call(r)==="[object Array]"}TB.exports=function(e,t,n){if(!WJ(t))throw new TypeError("iterator must be a function");var o;arguments.length>=3&&(o=n),ZJ(e)?YJ(e,t,o):typeof e=="string"?XJ(e,t,o):QJ(e,t,o)}});var CB=$((rWe,_B)=>{"use strict";var JJ=tx();_B.exports=function(){return JJ()&&!!Symbol.toStringTag}});var LB=$((nWe,DB)=>{"use strict";var IB=ra(),eee=CB()(),tee=sx(),ree=Bu(),Sx;eee?(kB=IB("RegExp.prototype.exec"),Ex={},v4=function(){throw Ex},vx={toString:v4,valueOf:v4},typeof Symbol.toPrimitive=="symbol"&&(vx[Symbol.toPrimitive]=v4),Sx=function(e){if(!e||typeof e!="object")return!1;var t=ree(e,"lastIndex"),n=t&&tee(t,"value");if(!n)return!1;try{kB(e,vx)}catch(o){return o===Ex}}):(RB=IB("Object.prototype.toString"),PB="[object RegExp]",Sx=function(e){return!e||typeof e!="object"&&typeof e!="function"?!1:RB(e)===PB});var kB,Ex,v4,vx,RB,PB;DB.exports=Sx});var Ax=$((oWe,NB)=>{"use strict";var nee=ra(),oee=LB(),iee=nee("RegExp.prototype.exec"),see=Sr();NB.exports=function(e){if(!oee(e))throw new see("`regex` must be a RegExp");return function(n){return iee(e,n)!==null}}});var UB=$((iWe,FB)=>{"use strict";var aee=ux(),OB=rB(),cee=fx(),lee=sB(),uee=yB(),dee=w4(),fee=b4(),hee=Sr(),pee=px(),mee=xx(),MB=Ax(),gee=MB(/^\s$/),yee=MB(/^[\n\r\u2028\u2029]$/),wee="^$\\.*+?()[]{}|",bee=",-=<>#&!%:;@~'`\"",BB={" ":"t","\n":"n","\v":"v","\f":"f","\r":"r",__proto__:null};FB.exports=function(e){if(!pee(e))throw new hee("Assertion failed: `c` must be a valid Unicode code point");var t=uee(e);if(OB(wee,t,0)>-1||t==="/")return"\\"+t;if(t in BB)return"\\"+BB[t];if(OB(bee,t,0)>-1||gee(t)||yee(t)||dee(e)||fee(e)){if(e<255){var n=aee(e,16);return"\\x"+cee(n,2,"0","START")}var o="",i=t;return mee(i,function(s){o+=lee(s)}),o}return t}});var qB=$((sWe,HB)=>{"use strict";var xee=Vu(),Eee=Sr(),$B=xee("%String.fromCharCode%"),vee=w4(),See=b4();HB.exports=function(e,t){if(!vee(e)||!See(t))throw new Eee("Assertion failed: `lead` must be a leading surrogate char code, and `trail` must be a trailing surrogate char code");return $B(e)+$B(t)}});var jB=$((aWe,WB)=>{"use strict";var VB=Sr(),GB=ra(),Aee=w4(),KB=b4(),Tee=qB(),_ee=GB("String.prototype.charAt"),zB=GB("String.prototype.charCodeAt");WB.exports=function(e,t){if(typeof e!="string")throw new VB("Assertion failed: `string` must be a String");var n=e.length;if(t<0||t>=n)throw new VB("Assertion failed: `position` must be >= 0, and < the length of `string`");var o=zB(e,t),i=_ee(e,t),s=Aee(o),a=KB(o);if(!s&&!a)return{"[[CodePoint]]":i,"[[CodeUnitCount]]":1,"[[IsUnpairedSurrogate]]":!1};if(a||t+1===n)return{"[[CodePoint]]":i,"[[CodeUnitCount]]":1,"[[IsUnpairedSurrogate]]":!0};var c=zB(e,t+1);return KB(c)?{"[[CodePoint]]":Tee(o,c),"[[CodeUnitCount]]":2,"[[IsUnpairedSurrogate]]":!1}:{"[[CodePoint]]":i,"[[CodeUnitCount]]":1,"[[IsUnpairedSurrogate]]":!0}}});var XB=$((cWe,YB)=>{"use strict";var Cee=Sr(),Iee=jB();YB.exports=function(e){if(typeof e!="string")throw new Cee("Assertion failed: `string` must be a String");for(var t=[],n=e.length,o=0;o<n;){var i=Iee(e,o);t[t.length]=i["[[CodePoint]]"],o+=i["[[CodeUnitCount]]"]}return t}});var eM=$((lWe,JB)=>{"use strict";var QB=Vu(),ZB=lx(),kee=ZB(QB("String.prototype.indexOf"));JB.exports=function(e,t){var n=QB(e,!!t);return typeof n=="function"&&kee(e,".prototype.")>-1?ZB(n):n}});var Tx=$((uWe,nM)=>{"use strict";var Ree=UB(),Pee=ux(),Dee=XB(),Lee=Ax(),Nee=xx(),Oee=Sr(),Bee=Lee(/^[\da-zA-Z]$/),Mee=eM(),tM=Mee("String.prototype.charCodeAt"),rM=function(e){var t=tM(e,0);if(t<55296||t>56319||e.length===1)return t;var n=tM(e,1);return n<56320||n>57343?t:(t-55296)*1024+(n-56320)+65536};nM.exports=function(e){if(typeof e!="string")throw new Oee("`S` must be a String");var t="",n=Dee(e);return Nee(n,function(o){if(t===""&&Bee(o)){var i=Pee(rM(o),16);t+="\\x"+i}else t+=Ree(rM(o))}),t}});var _x=$((dWe,oM)=>{"use strict";var Fee=Tx();oM.exports=function(){return RegExp.escape||Fee}});var sM=$((fWe,iM)=>{"use strict";var Uee=Z9(),$ee=_x()();iM.exports=function(){return Uee(RegExp,{escape:$ee}),RegExp.escape}});var lM=$((hWe,cM)=>{"use strict";var Hee=Z9(),qee=lx(),Cx=Tx(),Vee=_x(),Kee=sM(),aM=qee(Cx,null);Hee(aM,{getPolyfill:Vee,implementation:Cx,method:Cx,shim:Kee});cM.exports=aM});var mM=$(Ix=>{Ix.read=function(r,e,t,n,o){var i,s,a=o*8-n-1,c=(1<<a)-1,l=c>>1,u=-7,d=t?o-1:0,f=t?-1:1,h=r[e+d];for(d+=f,i=h&(1<<-u)-1,h>>=-u,u+=a;u>0;i=i*256+r[e+d],d+=f,u-=8);for(s=i&(1<<-u)-1,i>>=-u,u+=n;u>0;s=s*256+r[e+d],d+=f,u-=8);if(i===0)i=1-l;else{if(i===c)return s?NaN:(h?-1:1)*(1/0);s=s+Math.pow(2,n),i=i-l}return(h?-1:1)*s*Math.pow(2,i-n)};Ix.write=function(r,e,t,n,o,i){var s,a,c,l=i*8-o-1,u=(1<<l)-1,d=u>>1,f=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:i-1,p=n?1:-1,y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=u):(s=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-s))<1&&(s--,c*=2),s+d>=1?e+=f/c:e+=f*Math.pow(2,1-d),e*c>=2&&(s++,c/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(e*c-1)*Math.pow(2,o),s=s+d):(a=e*Math.pow(2,d-1)*Math.pow(2,o),s=0));o>=8;r[t+h]=a&255,h+=p,a/=256,o-=8);for(s=s<<o|a,l+=o;l>0;r[t+h]=s&255,h+=p,s/=256,l-=8);r[t+h-p]|=y*128}});var _M=$((Sje,TM)=>{var ju=1e3,Yu=ju*60,Xu=Yu*60,Bc=Xu*24,lte=Bc*7,ute=Bc*365.25;TM.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return dte(r);if(t==="number"&&isFinite(r))return e.long?hte(r):fte(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function dte(r){if(r=String(r),!(r.length>100)){var 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){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*ute;case"weeks":case"week":case"w":return t*lte;case"days":case"day":case"d":return t*Bc;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Xu;case"minutes":case"minute":case"mins":case"min":case"m":return t*Yu;case"seconds":case"second":case"secs":case"sec":case"s":return t*ju;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function fte(r){var e=Math.abs(r);return e>=Bc?Math.round(r/Bc)+"d":e>=Xu?Math.round(r/Xu)+"h":e>=Yu?Math.round(r/Yu)+"m":e>=ju?Math.round(r/ju)+"s":r+"ms"}function hte(r){var e=Math.abs(r);return e>=Bc?R4(r,e,Bc,"day"):e>=Xu?R4(r,e,Xu,"hour"):e>=Yu?R4(r,e,Yu,"minute"):e>=ju?R4(r,e,ju,"second"):r+" ms"}function R4(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var IM=$((Aje,CM)=>{function pte(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=a,t.humanize=_M(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let f=0;f<u.length;f++)d=(d<<5)-d+u.charCodeAt(f),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u){let d,f=null,h,p;function y(...g){if(!y.enabled)return;let m=y,b=Number(new Date),T=b-(d||b);m.diff=T,m.prev=d,m.curr=b,d=b,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let R=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(O,U)=>{if(O==="%%")return"%";R++;let C=t.formatters[U];if(typeof C=="function"){let L=g[R];O=C.call(m,L),g.splice(R,1),R--}return O}),t.formatArgs.call(m,g),(m.log||t.log).apply(m,g)}return y.namespace=u,y.useColors=t.useColors(),y.color=t.selectColor(u),y.extend=n,y.destroy=t.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(h!==t.namespaces&&(h=t.namespaces,p=t.enabled(u)),p),set:g=>{f=g}}),typeof t.init=="function"&&t.init(y),y}function n(u,d){let f=t(this.namespace+(typeof d>"u"?":":d)+u);return f.log=this.log,f}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let f of d)f[0]==="-"?t.skips.push(f.slice(1)):t.names.push(f)}function i(u,d){let f=0,h=0,p=-1,y=0;for(;f<u.length;)if(h<d.length&&(d[h]===u[f]||d[h]==="*"))d[h]==="*"?(p=h,y=f,h++):(f++,h++);else if(p!==-1)h=p+1,y++,f=y;else return!1;for(;h<d.length&&d[h]==="*";)h++;return h===d.length}function s(){let u=[...t.names,...t.skips.map(d=>"-"+d)].join(",");return t.enable(""),u}function a(u){for(let d of t.skips)if(i(u,d))return!1;for(let d of t.names)if(i(u,d))return!0;return!1}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.enable(t.load()),t}CM.exports=pte});var kM=$((Qr,P4)=>{Qr.formatArgs=gte;Qr.save=yte;Qr.load=wte;Qr.useColors=mte;Qr.storage=bte();Qr.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Qr.colors=["#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 mte(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function gte(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+P4.exports.humanize(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)}Qr.log=console.debug||console.log||(()=>{});function yte(r){try{r?Qr.storage.setItem("debug",r):Qr.storage.removeItem("debug")}catch{}}function wte(){let r;try{r=Qr.storage.getItem("debug")||Qr.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function bte(){try{return localStorage}catch{}}P4.exports=IM()(Qr);var{formatters:xte}=P4.exports;xte.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var bre={};xt(bre,{BasePlugin:()=>vr,DuplicatePlaceholderError:()=>cp,InvalidRangeError:()=>Fr,InvalidRedirectStatusCodeError:()=>ap,InvalidRedirectsFileError:()=>sp,MEDIA_TYPE_CAR:()=>Cc,MEDIA_TYPE_CBOR:()=>vn,MEDIA_TYPE_DAG_CBOR:()=>En,MEDIA_TYPE_DAG_JSON:()=>Sn,MEDIA_TYPE_DAG_PB:()=>np,MEDIA_TYPE_IPNS_RECORD:()=>_c,MEDIA_TYPE_JSON:()=>An,MEDIA_TYPE_OCTET_STREAM:()=>Ft,MEDIA_TYPE_RAW:()=>sr,MEDIA_TYPE_TAR:()=>Nu,NoContentError:()=>L9,RedirectsFileTooLargeError:()=>ip,SubdomainNotSupportedError:()=>N9,createVerifiedFetch:()=>Ux,createVerifiedFetchWithHelia:()=>mF,isAbortWithServerTimingError:()=>yQ,verifiedFetch:()=>M4});var Vx=Symbol.for("@libp2p/connection");var si=Symbol.for("@libp2p/content-routing");var Tr=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},Ap=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Tp=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},E=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},ai=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Ju=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},ed=class extends Error{static name="UnsupportedOperationError";constructor(e="Unsupported operation"){super(e),this.name="UnsupportedOperationError"}};var oa=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},$c=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Xn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},Hc=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var Io=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},td=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},qe=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},qc=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},ko=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},_p=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Wi=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Vc=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},he=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},ia=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Ro=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Qn=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var ji=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},sa=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},rd=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},Cp=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Kc=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},Zn=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var Ip=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},Yi=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},kp=class extends Yi{constructor(e,t){super(!0,e,t)}},Rp=class extends Yi{constructor(e,t){super(!1,e,t)}};function Pp(r){return r==null?!1:(r.type==="RSA"||r.type==="Ed25519"||r.type==="secp256k1"||r.type==="ECDSA")&&r.raw instanceof Uint8Array&&typeof r.equals=="function"&&typeof r.toMultihash=="function"&&typeof r.toCID=="function"&&typeof r.verify=="function"}var aa=Symbol.for("@libp2p/peer-discovery");var Dp=Symbol.for("@libp2p/peer-id");function pt(r){return!!r?.[Dp]}var ci=Symbol.for("@libp2p/peer-routing");var ca="keep-alive";function Lp(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Rt(...r){let e=[];for(let t of r)Lp(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 Ut(...r){let e=[];for(let t of r)Lp(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 Xi=Symbol.for("@libp2p/transport");var nd;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(nd||(nd={}));function vF(r){return typeof r?.handleEvent=="function"}function SF(r){return(r!==!0&&r!==!1&&r?.once)??!1}var se=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){let o=SF(n);super.addEventListener(e,s=>{if(o){let a=this.#e.get(s.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(s.type,a))}vF(t)?t.handleEvent(s):t(s)},n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:o})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:i})=>i!==t),this.#e.set(e,o))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var be=Symbol.for("@libp2p/service-capabilities"),Zr=Symbol.for("@libp2p/service-dependencies");function ae(r){let e=new globalThis.AbortController;function t(){let i=r.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(i);for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var k=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function AF(r){return r.buffer instanceof ArrayBuffer}function Pt(r){return AF(r)?r:r.slice()}var od=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},id=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Np=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var At={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new Np("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 V4={};xt(V4,{base58btc:()=>Ce,base58flickr:()=>PF});var une=new Uint8Array(0);function Kx(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 Jn(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 zx(r){return new TextEncoder().encode(r)}function Gx(r){return new TextDecoder().decode(r)}function TF(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 i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,g=0,m=0,b=p.length;m!==b&&p[m]===0;)m++,y++;for(var T=(b-m)*u+1>>>0,R=new Uint8Array(T);m!==b;){for(var D=p[m],O=0,U=T-1;(D!==0||O<g)&&U!==-1;U--,O++)D+=256*R[U]>>>0,R[U]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");g=O,m++}for(var C=T-g;C!==T&&R[C]===0;)C++;for(var L=c.repeat(y);C<T;++C)L+=r.charAt(R[C]);return L}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var g=0,m=0;p[y]===c;)g++,y++;for(var b=(p.length-y)*l+1>>>0,T=new Uint8Array(b);p[y];){var R=t[p.charCodeAt(y)];if(R===255)return;for(var D=0,O=b-1;(R!==0||D<m)&&O!==-1;O--,D++)R+=a*T[O]>>>0,T[O]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");m=D,y++}if(p[y]!==" "){for(var U=b-m;U!==b&&T[U]===0;)U++;for(var C=new Uint8Array(g+(b-U)),L=g;U!==b;)C[L++]=T[U++];return C}}}function h(p){var y=f(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:f,decode:h}}var _F=TF,CF=_F,Wx=CF;var U4=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")}},$4=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 jx(this,e)}},H4=class{decoders;constructor(e){this.decoders=e}or(e){return jx(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 jx(r,e){return new H4({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var q4=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new U4(e,t,n),this.decoder=new $4(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function zc({name:r,prefix:e,encode:t,decode:n}){return new q4(r,e,t,n)}function Qi({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Wx(t,r);return zc({prefix:e,name:r,encode:n,decode:i=>Jn(o(i))})}function IF(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),s=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,s+=t,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function kF(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function RF(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function mt({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=RF(n);return zc({prefix:e,name:r,encode(i){return kF(i,n,t)},decode(i){return IF(i,o,t,r)}})}var Ce=Qi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),PF=Qi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var K4={};xt(K4,{base32:()=>$t,base32hex:()=>OF,base32hexpad:()=>MF,base32hexpadupper:()=>FF,base32hexupper:()=>BF,base32pad:()=>LF,base32padupper:()=>NF,base32upper:()=>DF,base32z:()=>UF});var $t=mt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),DF=mt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),LF=mt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),NF=mt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),OF=mt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),BF=mt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),MF=mt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),FF=mt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),UF=mt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var z4={};xt(z4,{base36:()=>_r,base36upper:()=>$F});var _r=Qi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),$F=Qi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ve={};xt(Ve,{Digest:()=>la,create:()=>Cr,decode:()=>xe,equals:()=>W4,hasCode:()=>iU});var HF=Qx,Yx=128,qF=127,VF=~qF,KF=Math.pow(2,31);function Qx(r,e,t){e=e||[],t=t||0;for(var n=t;r>=KF;)e[t++]=r&255|Yx,r/=128;for(;r&VF;)e[t++]=r&255|Yx,r>>>=7;return e[t]=r|0,Qx.bytes=t-n+1,e}var zF=G4,GF=128,Xx=127;function G4(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw G4.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&Xx)<<o:(s&Xx)*Math.pow(2,o),o+=7}while(s>=GF);return G4.bytes=i-n,t}var WF=Math.pow(2,7),jF=Math.pow(2,14),YF=Math.pow(2,21),XF=Math.pow(2,28),QF=Math.pow(2,35),ZF=Math.pow(2,42),JF=Math.pow(2,49),eU=Math.pow(2,56),tU=Math.pow(2,63),rU=function(r){return r<WF?1:r<jF?2:r<YF?3:r<XF?4:r<QF?5:r<ZF?6:r<JF?7:r<eU?8:r<tU?9:10},nU={encode:HF,decode:zF,encodingLength:rU},oU=nU,sd=oU;function ad(r,e=0){return[sd.decode(r,e),sd.decode.bytes]}function Gc(r,e,t=0){return sd.encode(r,e,t),e}function Wc(r){return sd.encodingLength(r)}function Cr(r,e){let t=e.byteLength,n=Wc(r),o=n+Wc(t),i=new Uint8Array(o+t);return Gc(r,i,0),Gc(t,i,n),i.set(e,o),new la(r,t,e,i)}function xe(r){let e=Jn(r),[t,n]=ad(e),[o,i]=ad(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new la(t,o,s,e)}function W4(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Kx(r.bytes,t.bytes)}}var la=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function iU(r,e){return r.code===e}function Zx(r,e){let{bytes:t,version:n}=r;return n===0?aU(t,j4(r),e??Ce.encoder):cU(t,j4(r),e??$t.encoder)}var Jx=new WeakMap;function j4(r){let e=Jx.get(r);if(e==null){let t=new Map;return Jx.set(r,t),t}return e}var F=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!==cd)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==lU)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=Cr(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&&W4(e.multihash,n.multihash)}toString(e){return Zx(this,e)}toJSON(){return{"/":Zx(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:i,bytes:s}=t;return new r(n,o,i,s??eE(n,o,i.bytes))}else if(t[uU]===!0){let{version:n,multihash:o,code:i}=t,s=xe(o);return r.create(n,i,s)}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!==cd)throw new Error(`Version 0 CID must use dag-pb (code: ${cd}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=eE(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,cd,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=Jn(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new la(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,f]=ad(e.subarray(t));return t+=f,d},o=n(),i=cd;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,u=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=sU(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return j4(i).set(n,e),i}};function sU(r,e){switch(r[0]){case"Q":{let t=e??Ce;return[Ce.prefix,t.decode(`${Ce.prefix}${r}`)]}case Ce.prefix:{let t=e??Ce;return[Ce.prefix,t.decode(r)]}case $t.prefix:{let t=e??$t;return[$t.prefix,t.decode(r)]}case _r.prefix:{let t=e??_r;return[_r.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 aU(r,e,t){let{prefix:n}=t;if(n!==Ce.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function cU(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var cd=112,lU=18;function eE(r,e,t){let n=Wc(r),o=n+Wc(e),i=new Uint8Array(o+t.byteLength);return Gc(r,i,0),Gc(e,i,n),i.set(t,o),i}var uU=Symbol.for("@ipld/js-cid/CID");var Y4={};xt(Y4,{identity:()=>Ke});var tE=0,dU="identity",rE=Jn;function fU(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 Cr(tE,rE(r))}var Ke={code:tE,name:dU,encode:rE,digest:fU};function Dn(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 nE="1.2.840.10045.3.1.7",oE="1.3.132.0.34",iE="1.3.132.0.35";async function sE(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 aE(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,Pt(e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function cE(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 i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Pt(e),Pt(t.subarray()));return n?.signal?.throwIfAborted(),i}function rt(r=0){return new Uint8Array(r)}function nt(r=0){return new Uint8Array(r)}function Ln(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=nt(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function gt(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 uE=Symbol.for("@achingbrain/uint8arraylist");function lE(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 Nn(r){return!!r?.[uE]}var G=class r{bufs;length;[uE]=!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(Nn(n)){t+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Nn(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=lE(this.bufs,e);return t.buf[t.index]}set(e,t){let n=lE(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(Nn(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 Ln(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ln(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),i=new r;return i.length=o,i.bufs=n,i}_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 i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.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(s);break}let d=e-a;n.push(s.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(u){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Nn(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 i=256,s=new Int32Array(i);for(let d=0;d<i;d++)s[d]=-1;for(let d=0;d<o;d++)s[n[d]]=d;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let f=l;f>=0;f--){let h=this.get(d+f);if(n[f]!==h){u=Math.max(1,f-a[h]);break}}if(u===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=nt(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=rt(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=rt(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=rt(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=nt(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=rt(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=rt(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=rt(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=rt(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=rt(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(!gt(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,i)=>o+i.byteLength,0)),n.length=t,n}};var X4={};xt(X4,{base10:()=>pU});var pU=Qi({prefix:"9",name:"base10",alphabet:"0123456789"});var Q4={};xt(Q4,{base16:()=>mU,base16upper:()=>gU});var mU=mt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),gU=mt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Z4={};xt(Z4,{base2:()=>yU});var yU=mt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var J4={};xt(J4,{base256emoji:()=>vU});var dE=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}"),wU=dE.reduce((r,e,t)=>(r[t]=e,r),[]),bU=dE.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function xU(r){return r.reduce((e,t)=>(e+=wU[t],e),"")}function EU(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=bU[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var vU=zc({prefix:"\u{1F680}",name:"base256emoji",encode:xU,decode:EU});var e6={};xt(e6,{base64:()=>Tt,base64pad:()=>ld,base64url:()=>ud,base64urlpad:()=>SU});var Tt=mt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ld=mt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ud=mt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),SU=mt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var t6={};xt(t6,{base8:()=>AU});var AU=mt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var r6={};xt(r6,{identity:()=>TU});var TU=zc({prefix:"\0",name:"identity",encode:r=>Gx(r),decode:r=>zx(r)});var Po={};xt(Po,{code:()=>ar,decode:()=>ua,encode:()=>kU,name:()=>IU});var _U=new TextEncoder,CU=new TextDecoder,IU="json",ar=512;function kU(r){return _U.encode(JSON.stringify(r))}function ua(r){return JSON.parse(CU.decode(r))}var Jr={};xt(Jr,{code:()=>Ie,decode:()=>DU,encode:()=>PU,name:()=>RU});var RU="raw",Ie=85;function PU(r){return Jn(r)}function DU(r){return Jn(r)}var o6={};xt(o6,{sha256:()=>ct,sha512:()=>Bp});var LU=20;function li({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new n6(r,e,t,n,o)}var n6=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,i){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??LU,this.maxDigestLength=i}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?fE(n,this.code,t?.truncate):n.then(o=>fE(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function fE(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 Cr(e,r)}function pE(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ct=li({name:"sha2-256",code:18,encode:pE("SHA-256")}),Bp=li({name:"sha2-512",code:19,encode:pE("SHA-512")});var oe={...r6,...Z4,...t6,...X4,...Q4,...K4,...z4,...V4,...e6,...J4},soe={...o6,...Y4};function Mp(r=0){return new Uint8Array(r)}function gE(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var mE=gE("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),i6=gE("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=Mp(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),NU={utf8:mE,"utf-8":mE,hex:oe.base16,latin1:i6,ascii:i6,binary:i6,...oe},Fp=NU;function lt(r,e="utf8"){let t=Fp[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function ze(r,e="utf8"){let t=Fp[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var OU=parseInt("11111",2),s6=parseInt("10000000",2),BU=parseInt("01111111",2),yE={0:dd,1:dd,2:MU,3:$U,4:HU,5:UU,6:FU,16:dd,22:dd,48:dd};function On(r,e={offset:0}){let t=r[e.offset]&OU;if(e.offset++,yE[t]!=null)return yE[t](r,e);throw new Error("No decoder for tag "+t)}function fd(r,e){let t=0;if((r[e.offset]&s6)===s6){let n=r[e.offset]&BU,o="0x";e.offset++;for(let i=0;i<n;i++,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 dd(r,e){fd(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=On(r,e);if(n===null)break;t.push(n)}return t}function MU(r,e){let t=fd(r,e),n=e.offset,o=e.offset+t,i=[];for(let s=n;s<o;s++)s===n&&r[s]===0||i.push(r[s]);return e.offset+=t,Uint8Array.from(i)}function FU(r,e){let t=fd(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,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 d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function UU(r,e){return e.offset++,null}function $U(r,e){let t=fd(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 HU(r,e){let t=fd(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function qU(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new G;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Up(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=qU(r.byteLength);return new G(Uint8Array.from([e.byteLength|s6]),e)}function Ir(r){let e=new G,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new G(Uint8Array.from([2]),Up(e),e)}function hd(r){let e=Uint8Array.from([0]),t=new G(e,r);return new G(Uint8Array.from([3]),Up(t),t)}function wE(r){return new G(Uint8Array.from([4]),Up(r),r)}function eo(r,e=48){let t=new G;for(let n of r)t.append(n);return new G(Uint8Array.from([e]),Up(t),t)}var VU=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),KU=Uint8Array.from([6,5,43,129,4,0,34]),zU=Uint8Array.from([6,5,43,129,4,0,35]),bE={ext:!0,kty:"EC",crv:"P-256"},xE={ext:!0,kty:"EC",crv:"P-384"},EE={ext:!0,kty:"EC",crv:"P-521"},jc=32,Yc=48,Xc=66;function vE(r){let e=On(r);return a6(e)}function a6(r){let e=r[1],t=ze(e,"base64url"),n=r[2][1][0],o=1,i,s;if(e.byteLength===jc)return i=ze(n.subarray(o,o+jc),"base64url"),s=ze(n.subarray(o+jc),"base64url"),new fa({...bE,key_ops:["sign"],d:t,x:i,y:s});if(e.byteLength===Yc)return i=ze(n.subarray(o,o+Yc),"base64url"),s=ze(n.subarray(o+Yc),"base64url"),new fa({...xE,key_ops:["sign"],d:t,x:i,y:s});if(e.byteLength===Xc)return i=ze(n.subarray(o,o+Xc),"base64url"),s=ze(n.subarray(o+Xc),"base64url"),new fa({...EE,key_ops:["sign"],d:t,x:i,y:s});throw new E(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function c6(r){let e=On(r);return SE(e)}function SE(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===jc*2+1)return n=ze(e.subarray(t,t+jc),"base64url"),o=ze(e.subarray(t+jc),"base64url"),new da({...bE,key_ops:["verify"],x:n,y:o});if(e.byteLength===Yc*2+1)return n=ze(e.subarray(t,t+Yc),"base64url"),o=ze(e.subarray(t+Yc),"base64url"),new da({...xE,key_ops:["verify"],x:n,y:o});if(e.byteLength===Xc*2+1)return n=ze(e.subarray(t,t+Xc),"base64url"),o=ze(e.subarray(t+Xc),"base64url"),new da({...EE,key_ops:["verify"],x:n,y:o});throw new E(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function AE(r){return eo([Ir(Uint8Array.from([1])),wE(lt(r.d??"","base64url")),eo([_E(r.crv)],160),eo([hd(new G(Uint8Array.from([4]),lt(r.x??"","base64url"),lt(r.y??"","base64url")))],161)]).subarray()}function TE(r){return eo([Ir(Uint8Array.from([1])),eo([_E(r.crv)],160),eo([hd(new G(Uint8Array.from([4]),lt(r.x??"","base64url"),lt(r.y??"","base64url")))],161)]).subarray()}function _E(r){if(r==="P-256")return VU;if(r==="P-384")return KU;if(r==="P-521")return zU;throw new E(`Invalid curve ${r}`)}async function CE(r="P-256"){let e=await sE(r);return new fa(e.privateKey)}var da=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=TE(this.jwk)),this._raw}toMultihash(){return Ke.digest(Ht(this))}toCID(){return F.createV1(114,this.toMultihash())}toString(){return Ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}async verify(e,t,n){return cE(this.jwk,t,e,n)}},fa=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new da({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=AE(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}async sign(e,t){return aE(this.jwk,e,t)}};function l6(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Ur(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${r}`)}}function Xt(r,e,t=""){let n=l6(r),o=r?.length,i=e!==void 0;if(!n||i&&o!==e){let s=t&&`"${t}" `,a=i?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function di(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(Ur(r.outputLen),Ur(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Qc(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 $p(r,e){Xt(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function cr(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ha(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function to(r,e){return r<<32-e|r>>>e}function Hp(r,e){return r<<e|r>>>32-e>>>0}var kE=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",GU=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function qp(r){if(Xt(r),kE)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=GU[r[t]];return e}var ui={_0:48,_9:57,A:65,F:70,a:97,f:102};function IE(r){if(r>=ui._0&&r<=ui._9)return r-ui._0;if(r>=ui.A&&r<=ui.F)return r-(ui.A-10);if(r>=ui.a&&r<=ui.f)return r-(ui.a-10)}function pd(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(kE)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=r.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,i=0;o<t;o++,i+=2){let s=IE(r.charCodeAt(i)),a=IE(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}var WU=async()=>{};async function RE(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let i=Date.now()-n;i>=0&&i<e||(await WU(),n+=i)}}function jU(r){if(typeof r!="string")throw new TypeError("string expected");return new Uint8Array(new TextEncoder().encode(r))}function u6(r,e=""){return typeof r=="string"?jU(r):Xt(r,void 0,e)}function d6(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Xt(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}function PE(r,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new TypeError("options must be object or undefined");return Object.assign(r,e)}function md(r,e={}){let t=(o,i)=>r(i).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function Vp(r=32){Ur(r,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return e.getRandomValues(new Uint8Array(r))}var f6=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Kp(r,e,t){return r&e^~r&t}function zp(r,e,t){return r&e^r&t^e&t}var pa=class{blockLen;outputLen;canXOF=!1;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=ha(this.buffer)}update(e){Qc(this),Xt(e);let{view:t,buffer:n,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=ha(e);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Qc(this),$p(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;t[s++]=128,cr(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let d=s;d<o;d++)t[d]=0;n.setBigUint64(o-8,BigInt(this.length*8),i),this.process(n,0);let a=ha(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 d=0;d<l;d++)a.setUint32(4*d,u[d],i)}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:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},fi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Qt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Gp=BigInt(4294967295),DE=BigInt(32);function YU(r,e=!1){return e?{h:Number(r&Gp),l:Number(r>>DE&Gp)}:{h:Number(r>>DE&Gp)|0,l:Number(r&Gp)|0}}function LE(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let i=0;i<t;i++){let{h:s,l:a}=YU(r[i],e);[n[i],o[i]]=[s,a]}return[n,o]}var h6=(r,e,t)=>r>>>t,p6=(r,e,t)=>r<<32-t|e>>>t,ma=(r,e,t)=>r>>>t|e<<32-t,ga=(r,e,t)=>r<<32-t|e>>>t,gd=(r,e,t)=>r<<64-t|e>>>t-32,yd=(r,e,t)=>r>>>t-32|e<<64-t;function Do(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var NE=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),OE=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,BE=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),ME=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,FE=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),UE=(r,e,t,n,o,i)=>e+t+n+o+i+(r/2**32|0)|0;var QU=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]),Zi=new Uint32Array(64),m6=class extends pa{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[e,t,n,o,i,s,a,c]}set(e,t,n,o,i,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)Zi[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let f=Zi[d-15],h=Zi[d-2],p=to(f,7)^to(f,18)^f>>>3,y=to(h,17)^to(h,19)^h>>>10;Zi[d]=y+Zi[d-7]+p+Zi[d-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=to(a,6)^to(a,11)^to(a,25),h=u+f+Kp(a,c,l)+QU[d]+Zi[d]|0,y=(to(n,2)^to(n,13)^to(n,22))+zp(n,o,i)|0;u=l,l=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+y|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,i,s,a,c,l,u)}roundClean(){cr(Zi)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),cr(this.buffer)}},g6=class extends m6{A=fi[0]|0;B=fi[1]|0;C=fi[2]|0;D=fi[3]|0;E=fi[4]|0;F=fi[5]|0;G=fi[6]|0;H=fi[7]|0;constructor(){super(32)}};var $E=LE(["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))),ZU=$E[0],JU=$E[1],Ji=new Uint32Array(80),es=new Uint32Array(80),y6=class extends pa{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:f,Gh:h,Gl:p,Hh:y,Hl:g}=this;return[e,t,n,o,i,s,a,c,l,u,d,f,h,p,y,g]}set(e,t,n,o,i,s,a,c,l,u,d,f,h,p,y,g){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=f|0,this.Gh=h|0,this.Gl=p|0,this.Hh=y|0,this.Hl=g|0}process(e,t){for(let T=0;T<16;T++,t+=4)Ji[T]=e.getUint32(t),es[T]=e.getUint32(t+=4);for(let T=16;T<80;T++){let R=Ji[T-15]|0,D=es[T-15]|0,O=ma(R,D,1)^ma(R,D,8)^h6(R,D,7),U=ga(R,D,1)^ga(R,D,8)^p6(R,D,7),C=Ji[T-2]|0,L=es[T-2]|0,H=ma(C,L,19)^gd(C,L,61)^h6(C,L,6),M=ga(C,L,19)^yd(C,L,61)^p6(C,L,6),x=BE(U,M,es[T-7],es[T-16]),A=ME(x,O,H,Ji[T-7],Ji[T-16]);Ji[T]=A|0,es[T]=x|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:f,Fh:h,Fl:p,Gh:y,Gl:g,Hh:m,Hl:b}=this;for(let T=0;T<80;T++){let R=ma(d,f,14)^ma(d,f,18)^gd(d,f,41),D=ga(d,f,14)^ga(d,f,18)^yd(d,f,41),O=d&h^~d&y,U=f&p^~f&g,C=FE(b,D,U,JU[T],es[T]),L=UE(C,m,R,O,ZU[T],Ji[T]),H=C|0,M=ma(n,o,28)^gd(n,o,34)^gd(n,o,39),x=ga(n,o,28)^yd(n,o,34)^yd(n,o,39),A=n&i^n&a^i&a,_=o&s^o&c^s&c;m=y|0,b=g|0,y=h|0,g=p|0,h=d|0,p=f|0,{h:d,l:f}=Do(l|0,u|0,L|0,H|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let v=NE(H,x,_);n=OE(v,L,M,A),o=v|0}({h:n,l:o}=Do(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Do(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Do(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Do(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:f}=Do(this.Eh|0,this.El|0,d|0,f|0),{h,l:p}=Do(this.Fh|0,this.Fl|0,h|0,p|0),{h:y,l:g}=Do(this.Gh|0,this.Gl|0,y|0,g|0),{h:m,l:b}=Do(this.Hh|0,this.Hl|0,m|0,b|0),this.set(n,o,i,s,a,c,l,u,d,f,h,p,y,g,m,b)}roundClean(){cr(Ji,es)}destroy(){this.destroyed=!0,cr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},w6=class extends y6{Ah=Qt[0]|0;Al=Qt[1]|0;Bh=Qt[2]|0;Bl=Qt[3]|0;Ch=Qt[4]|0;Cl=Qt[5]|0;Dh=Qt[6]|0;Dl=Qt[7]|0;Eh=Qt[8]|0;El=Qt[9]|0;Fh=Qt[10]|0;Fl=Qt[11]|0;Gh=Qt[12]|0;Gl=Qt[13]|0;Hh=Qt[14]|0;Hl=Qt[15]|0;constructor(){super(64)}};var Bn=md(()=>new g6,f6(1));var Lo=md(()=>new w6,f6(3));var pe=(r,e,t)=>Xt(r,e,t),x6=Ur,Zc=qp,Dt=(...r)=>d6(...r),Jc=r=>pd(r),ya=l6,wa=r=>Vp(r),jp=BigInt(0),b6=BigInt(1);function ro(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof r)}return r}function Yp(r){if(typeof r=="bigint"){if(!Wp(r))throw new RangeError("positive bigint expected, got "+r)}else x6(r);return r}function no(r,e=""){if(typeof r!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+r)}}function wd(r){let e=Yp(r).toString(16);return e.length&1?"0"+e:e}function HE(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?jp:BigInt("0x"+r)}function ba(r){return HE(qp(r))}function en(r){return HE(qp(ts(Xt(r)).reverse()))}function Xp(r,e){if(Ur(e),e===0)throw new RangeError("zero length");r=Yp(r);let t=r.toString(16);if(t.length>e*2)throw new RangeError("number too large");return pd(t.padStart(e*2,"0"))}function bd(r,e){return Xp(r,e).reverse()}function qE(r,e){if(r=pe(r),e=pe(e),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 ts(r){return Uint8Array.from(pe(r))}function Qp(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var Wp=r=>typeof r=="bigint"&&jp<=r;function e$(r,e,t){return Wp(r)&&Wp(e)&&Wp(t)&&e<=r&&r<t}function hi(r,e,t,n){if(!e$(e,t,n))throw new RangeError("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function el(r){if(r<jp)throw new Error("expected non-negative bigint, got "+r);let e;for(e=0;r>jp;r>>=b6,e+=1);return e}var xd=r=>(b6<<BigInt(r))-b6;function VE(r,e,t){if(Ur(r,"hashLen"),Ur(e,"qByteLen"),typeof t!="function")throw new TypeError("hmacFn must be a function");let n=g=>new Uint8Array(g),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},f=(...g)=>t(l,Dt(c,...g)),h=(g=o)=>{l=f(i,g),c=f(),g.length!==0&&(l=f(s,g),c=f())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let g=0,m=[];for(;g<e;){c=f();let b=c.slice();m.push(b),g+=c.length}return Dt(...m)};return(g,m)=>{d(),h(g);let b;for(;(b=m(p()))===void 0;)h();return d(),b}}function tn(r,e={},t={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(r,i))throw new TypeError(`param "${i}" is invalid: expected own property`);let c=r[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new TypeError(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.entries(i).forEach(([a,c])=>n(a,c,s));o(e,!1),o(t,!0)}var E6=()=>{throw new Error("not implemented")};var Zt=BigInt(0),yt=BigInt(1),xa=BigInt(2),WE=BigInt(3),jE=BigInt(4),YE=BigInt(5),t$=BigInt(7),XE=BigInt(8),r$=BigInt(9),QE=BigInt(16);function ot(r,e){if(e<=Zt)throw new Error("mod: expected positive modulus, got "+e);let t=r%e;return t>=Zt?t:e+t}function Qe(r,e,t){if(e<Zt)throw new Error("pow2: expected non-negative exponent, got "+e);let n=r;for(;e-- >Zt;)n*=n,n%=t;return n}function KE(r,e){if(r===Zt)throw new Error("invert: expected non-zero number");if(e<=Zt)throw new Error("invert: expected positive modulus, got "+e);let t=ot(r,e),n=e,o=Zt,i=yt,s=yt,a=Zt;for(;t!==Zt;){let l=n/t,u=n-t*l,d=o-s*l,f=i-a*l;n=t,t=u,o=s,i=a,s=d,a=f}if(n!==yt)throw new Error("invert: does not exist");return ot(o,e)}function v6(r,e,t){let n=r;if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function ZE(r,e){let t=r,n=(t.ORDER+yt)/jE,o=t.pow(e,n);return v6(t,o,e),o}function n$(r,e){let t=r,n=(t.ORDER-YE)/XE,o=t.mul(e,xa),i=t.pow(o,n),s=t.mul(e,i),a=t.mul(t.mul(s,xa),i),c=t.mul(s,t.sub(a,t.ONE));return v6(t,c,e),c}function o$(r){let e=tl(r),t=JE(r),n=t(e,e.neg(e.ONE)),o=t(e,n),i=t(e,e.neg(n)),s=(r+t$)/QE;return((a,c)=>{let l=a,u=l.pow(c,s),d=l.mul(u,n),f=l.mul(u,o),h=l.mul(u,i),p=l.eql(l.sqr(d),c),y=l.eql(l.sqr(f),c);u=l.cmov(u,d,p),d=l.cmov(h,f,y);let g=l.eql(l.sqr(d),c),m=l.cmov(u,d,g);return v6(l,m,c),m})}function JE(r){if(r<WE)throw new Error("sqrt is not defined for small field");let e=r-yt,t=0;for(;e%xa===Zt;)e/=xa,t++;let n=xa,o=tl(r);for(;zE(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ZE;let i=o.pow(n,e),s=(e+yt)/xa;return function(c,l){let u=c;if(u.is0(l))return l;if(zE(u,l)!==1)throw new Error("Cannot find square root");let d=t,f=u.mul(u.ONE,i),h=u.pow(l,e),p=u.pow(l,s);for(;!u.eql(h,u.ONE);){if(u.is0(h))return u.ZERO;let y=1,g=u.sqr(h);for(;!u.eql(g,u.ONE);)if(y++,g=u.sqr(g),y===d)throw new Error("Cannot find square root");let m=yt<<BigInt(d-y-1),b=u.pow(f,m);d=y,f=u.sqr(b),h=u.mul(h,f),p=u.mul(p,b)}return p}}function i$(r){return r%jE===WE?ZE:r%XE===YE?n$:r%QE===r$?o$(r):JE(r)}var pi=(r,e)=>(ot(r,e)&yt)===yt,s$=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function S6(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=s$.reduce((n,o)=>(n[o]="function",n),e);if(tn(r,t),no(r.BYTES,"BYTES"),no(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=yt)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function a$(r,e,t){let n=r;if(t<Zt)throw new Error("invalid exponent, negatives unsupported");if(t===Zt)return n.ONE;if(t===yt)return e;let o=n.ONE,i=e;for(;t>Zt;)t&yt&&(o=n.mul(o,i)),i=n.sqr(i),t>>=yt;return o}function Ed(r,e,t=!1){let n=r,o=new Array(e.length).fill(t?n.ZERO:void 0),i=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),s=n.inv(i);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),s),o}function zE(r,e){let t=r,n=(t.ORDER-yt)/xa,o=t.pow(e,n),i=t.eql(o,t.ONE),s=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function c$(r,e){if(e!==void 0&&x6(e),r<=Zt)throw new Error("invalid n length: expected positive n, got "+r);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=el(r);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let n=e!==void 0?e:t,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var GE=new WeakMap,Zp=class{ORDER;BITS;BYTES;isLE;ZERO=Zt;ONE=yt;_lengths;_mod;constructor(e,t={}){if(e<=yt)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:i}=c$(e,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,Object.freeze(this)}create(e){return ot(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Zt<=e&&e<this.ORDER}is0(e){return e===Zt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&yt)===yt}neg(e){return ot(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ot(e*e,this.ORDER)}add(e,t){return ot(e+t,this.ORDER)}sub(e,t){return ot(e-t,this.ORDER)}mul(e,t){return ot(e*t,this.ORDER)}pow(e,t){return a$(this,e,t)}div(e,t){return ot(e*KE(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 KE(e,this.ORDER)}sqrt(e){let t=GE.get(this);return t||GE.set(this,t=i$(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?bd(e,this.BYTES):Xp(e,this.BYTES)}fromBytes(e,t=!1){pe(e);let{_lengths:n,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(n){if(e.length<1||!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,i?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?en(e):ba(e);if(a&&(c=ot(c,s)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Ed(this,e)}cmov(e,t,n){return ro(n,"condition"),n?t:e}};Object.freeze(Zp.prototype);function tl(r,e={}){return new Zp(r,e)}function ev(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=yt)throw new Error("field order must be greater than 1");let e=el(r-yt);return Math.ceil(e/8)}function A6(r){let e=ev(r);return e+Math.ceil(e/2)}function T6(r,e,t=!1){pe(r);let n=r.length,o=ev(e),i=Math.max(A6(e),16);if(n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=t?en(r):ba(r),a=ot(s,e-yt)+yt;return t?bd(a,o):Xp(a,o)}var rl=BigInt(0),Ea=BigInt(1);function vd(r,e){let t=e.negate();return r?t:e}function va(r,e){let t=Ed(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function ov(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function _6(r,e){ov(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,i=xd(r),s=BigInt(r);return{windows:t,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function tv(r,e,t){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=t,a=Number(r&o),c=r>>s;a>n&&(a-=i,c+=Ea);let l=e*n,u=l+Math.abs(a)-1,d=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:l}}var C6=new WeakMap,iv=new WeakMap;function I6(r){return iv.get(r)||1}function rv(r){if(r!==rl)throw new Error("invalid wNAF")}var nl=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>rl;)t&Ea&&(n=n.add(o)),o=o.double(),t>>=Ea;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=_6(t,this.bits),i=[],s=e,a=s;for(let c=0;c<n;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=_6(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:f,offsetF:h}=tv(n,a,s);n=c,u?i=i.add(vd(f,t[h])):o=o.add(vd(d,t[l]))}return rv(n),{p:o,f:i}}wNAFUnsafe(e,t,n,o=this.ZERO){let i=_6(e,this.bits);for(let s=0;s<i.windows&&n!==rl;s++){let{nextN:a,offset:c,isZero:l,isNeg:u}=tv(n,s,i);if(n=a,!l){let d=t[c];o=o.add(u?d.negate():d)}}return rv(n),o}getPrecomputes(e,t,n){let o=C6.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),C6.set(t,o))),o}cached(e,t,n){let o=I6(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let i=I6(e);return i===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,o)}createCache(e,t){ov(t,this.bits),iv.set(e,t),C6.delete(e)}hasCache(e){return I6(e)!==1}};function sv(r,e,t,n){let o=e,i=r.ZERO,s=r.ZERO;for(;t>rl||n>rl;)t&Ea&&(i=i.add(o)),n&Ea&&(s=s.add(o)),o=o.double(),t>>=Ea,n>>=Ea;return{p1:i,p2:s}}function nv(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return S6(e),e}else return tl(r,{isLE:t})}function Jp(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>rl))throw new Error(`CURVE.${c} must be positive bigint`)}let o=nv(e.p,t.Fp,n),i=nv(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:i}}function ol(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var rs=BigInt(0),qt=BigInt(1),k6=BigInt(2),l$=BigInt(8);function u$(r,e,t,n){let o=r.sqr(t),i=r.sqr(n),s=r.add(r.mul(e.a,o),i),a=r.add(r.ONE,r.mul(e.d,r.mul(o,i)));return r.eql(s,a)}function av(r,e={}){let t=e,n=Jp("edwards",r,t,t.FpFnLE),{Fp:o,Fn:i}=n,s=n.CURVE,{h:a}=s;tn(t,{},{uvRatio:"function"});let c=k6<<BigInt(i.BYTES*8)-qt,l=y=>o.create(y),u=t.uvRatio===void 0?(y,g)=>{try{return{isValid:!0,value:o.sqrt(o.div(y,g))}}catch{return{isValid:!1,value:rs}}}:t.uvRatio;if(!u$(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(y,g,m=!1){let b=m?qt:rs;return hi("coordinate "+y,g,b,c),g}function f(y){if(!(y instanceof h))throw new Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,qt,l(s.Gx*s.Gy));static ZERO=new h(rs,qt,qt,rs);static Fp=o;static Fn=i;X;Y;Z;T;constructor(g,m,b,T){this.X=d("x",g),this.Y=d("y",m),this.Z=d("z",b,!0),this.T=d("t",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof h)throw new Error("extended point not allowed");let{x:m,y:b}=g||{};return d("x",m),d("y",b),new h(m,b,qt,l(m*b))}static fromBytes(g,m=!1){let b=o.BYTES,{a:T,d:R}=s;g=ts(pe(g,b,"point")),ro(m,"zip215");let D=ts(g),O=g[b-1];D[b-1]=O&-129;let U=en(D),C=m?c:o.ORDER;hi("point.y",U,rs,C);let L=l(U*U),H=l(L-qt),M=l(R*L-T),{isValid:x,value:A}=u(H,M);if(!x)throw new Error("bad point: invalid y coordinate");let _=(A&qt)===qt,v=(O&128)!==0;if(!m&&A===rs&&v)throw new Error("bad point: x=0 and x_0=1");return v!==_&&(A=l(-A)),h.fromAffine({x:A,y:U})}static fromHex(g,m=!1){return h.fromBytes(Jc(g),m)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,m=!0){return p.createCache(this,g),m||this.multiply(k6),this}assertValidity(){let g=this,{a:m,d:b}=s;if(g.is0())throw new Error("bad point: ZERO");let{X:T,Y:R,Z:D,T:O}=g,U=l(T*T),C=l(R*R),L=l(D*D),H=l(L*L),M=l(U*m),x=l(L*l(M+C)),A=l(H+l(b*l(U*C)));if(x!==A)throw new Error("bad point: equation left != right (1)");let _=l(T*R),v=l(D*O);if(_!==v)throw new Error("bad point: equation left != right (2)")}equals(g){f(g);let{X:m,Y:b,Z:T}=this,{X:R,Y:D,Z:O}=g,U=l(m*O),C=l(R*T),L=l(b*O),H=l(D*T);return U===C&&L===H}is0(){return this.equals(h.ZERO)}negate(){return new h(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:g}=s,{X:m,Y:b,Z:T}=this,R=l(m*m),D=l(b*b),O=l(k6*l(T*T)),U=l(g*R),C=m+b,L=l(l(C*C)-R-D),H=U+D,M=H-O,x=U-D,A=l(L*M),_=l(H*x),v=l(L*x),S=l(M*H);return new h(A,_,S,v)}add(g){f(g);let{a:m,d:b}=s,{X:T,Y:R,Z:D,T:O}=this,{X:U,Y:C,Z:L,T:H}=g,M=l(T*U),x=l(R*C),A=l(O*b*H),_=l(D*L),v=l((T+R)*(U+C)-M-x),S=_-A,P=_+A,B=l(x-m*M),I=l(v*S),q=l(P*B),V=l(v*B),Z=l(S*P);return new h(I,q,Z,V)}subtract(g){return f(g),this.add(g.negate())}multiply(g){if(!i.isValidNot0(g))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:m,f:b}=p.cached(this,g,T=>va(h,T));return va(h,[m,b])[0]}multiplyUnsafe(g){if(!i.isValid(g))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return g===rs?h.ZERO:this.is0()||g===qt?this:p.unsafe(this,g,m=>va(h,m))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return p.unsafe(this,s.n).is0()}toAffine(g){let m=this,b=g,{X:T,Y:R,Z:D}=m,O=m.is0();b==null&&(b=O?l$:o.inv(D));let U=l(T*b),C=l(R*b),L=o.mul(D,b);if(O)return{x:rs,y:qt};if(L!==qt)throw new Error("invZ was invalid");return{x:U,y:C}}clearCofactor(){return a===qt?this:this.multiplyUnsafe(a)}toBytes(){let{x:g,y:m}=this.toAffine(),b=o.toBytes(m);return b[b.length-1]|=g&qt?128:0,b}toHex(){return Zc(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let p=new nl(h,i.BITS);return i.BITS>=8&&h.BASE.precompute(8),Object.freeze(h.prototype),Object.freeze(h),h}var em=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){E6()}static fromHex(e){E6()}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 Zc(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.ep.precompute(e,t),this}};function cv(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=t;tn(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=r,l=n.outputLen,u=2*a.BYTES;if(l!==void 0&&(no(l,"hash.outputLen"),l!==u))throw new Error(`hash.outputLen must be ${u}, got ${l}`);let d=o.randomBytes===void 0?wa:o.randomBytes,f=o.adjustScalarBytes===void 0?x=>x:o.adjustScalarBytes,h=o.domain===void 0?(x,A,_)=>{if(ro(_,"phflag"),A.length||_)throw new Error("Contexts/pre-hash are not supported");return x}:o.domain;function p(x){return c.create(en(x))}function y(x){let A=U.secretKey;pe(x,U.secretKey,"secretKey");let _=pe(n(x),2*A,"hashedSecretKey"),v=f(_.slice(0,A)),S=_.slice(A,2*A),P=p(v);return{head:v,prefix:S,scalar:P}}function g(x){let{head:A,prefix:_,scalar:v}=y(x),S=s.multiply(v),P=S.toBytes();return{head:A,prefix:_,scalar:v,point:S,pointBytes:P}}function m(x){return g(x).pointBytes}function b(x=Uint8Array.of(),...A){let _=Dt(...A);return p(n(h(_,pe(x,void 0,"context"),!!i)))}function T(x,A,_={}){x=pe(x,void 0,"message"),i&&(x=i(x));let{prefix:v,scalar:S,pointBytes:P}=g(A),B=b(_.context,v,x),I=s.multiply(B).toBytes(),q=b(_.context,I,P,x),V=c.create(B+q*S);if(!c.isValid(V))throw new Error("sign failed: invalid s");let Z=Dt(I,c.toBytes(V));return pe(Z,U.signature,"result")}let R={zip215:o.zip215};function D(x,A,_,v=R){let{context:S}=v,P=v.zip215===void 0?!!R.zip215:v.zip215,B=U.signature;x=pe(x,B,"signature"),A=pe(A,void 0,"message"),_=pe(_,U.publicKey,"publicKey"),P!==void 0&&ro(P,"zip215"),i&&(A=i(A));let I=B/2,q=x.subarray(0,I),V=en(x.subarray(I,B)),Z,fe,ce;try{Z=r.fromBytes(_,P),fe=r.fromBytes(q,P),ce=s.multiplyUnsafe(V)}catch{return!1}if(!P&&Z.isSmallOrder())return!1;let Fe=b(S,q,_,A);return fe.add(Z.multiplyUnsafe(Fe)).subtract(ce).clearCofactor().is0()}let O=a.BYTES,U={secretKey:O,publicKey:O,signature:2*O,seed:O};function C(x){return x=x===void 0?d(U.seed):x,pe(x,U.seed,"seed")}function L(x){return ya(x)&&x.length===U.secretKey}function H(x,A){try{return!!r.fromBytes(x,A===void 0?R.zip215:A)}catch{return!1}}let M={getExtendedPublicKey:g,randomSecretKey:C,isValidSecretKey:L,isValidPublicKey:H,toMontgomery(x){let{y:A}=r.fromBytes(x),_=U.publicKey,v=_===32;if(!v&&_!==57)throw new Error("only defined for 25519 and 448");let S=v?a.div(qt+A,qt-A):a.div(A-qt,A+qt);return a.toBytes(S)},toMontgomerySecret(x){let A=U.secretKey;pe(x,A);let _=n(x.subarray(0,A));return f(_).subarray(0,A)}};return Object.freeze(U),Object.freeze(M),Object.freeze({keygen:ol(C,m),getPublicKey:m,sign:T,verify:D,utils:M,Point:r,lengths:U})}function Sd(r,e){if(no(r),no(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(r<0||r>2**(8*e)-1)throw new Error("invalid I2OSP input: "+r);let t=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return new Uint8Array(t)}function d$(r,e){let t=new Uint8Array(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return t}function f$(r){if(!ya(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof r=="string"?Qp(r):r;if(e.length===0)throw new Error("DST must be non-empty");return e}function R6(r,e,t,n){pe(r),no(t),e=f$(e),e.length>255&&(e=n(Dt(Qp("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:i}=n,s=Math.ceil(t/o);if(t>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=Dt(e,Sd(e.length,1)),c=new Uint8Array(i),l=Sd(t,2),u=new Array(s),d=n(Dt(c,r,l,Sd(0,1),a));u[0]=n(Dt(d,Sd(1,1),a));for(let h=1;h<s;h++){let p=[d$(d,u[h-1]),Sd(h+1,1),a];u[h]=n(Dt(...p))}return Dt(...u).slice(0,t)}var lv="HashToScalar-";var Ad=BigInt(0),il=BigInt(1),tm=BigInt(2);function h$(r){return tn(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...r})}function uv(r){let e=h$(r),{P:t,type:n,adjustScalarBytes:o,powPminus2:i,randomBytes:s}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=s===void 0?wa:s,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),f=BigInt(a?121665:39081),h=a?tm**BigInt(254):tm**BigInt(447),p=a?BigInt(8)*tm**BigInt(251)-il:BigInt(4)*tm**BigInt(445)-il,y=h+p+il,g=_=>ot(_,t),m=b(d);function b(_){return bd(g(_),u)}function T(_){let v=ts(pe(_,u,"uCoordinate"));return a&&(v[31]&=127),g(en(v))}function R(_){return en(o(ts(pe(_,u,"scalar"))))}function D(_,v){let S=H(T(v),R(_));if(S===Ad)throw new Error("invalid private or public key received");return b(S)}function O(_){return D(_,m)}let U=O,C=D;function L(_,v,S){let P=g(_*(v-S));return v=g(v-P),S=g(S+P),{x_2:v,x_3:S}}function H(_,v){hi("u",_,Ad,t),hi("scalar",v,h,y);let S=v,P=_,B=il,I=Ad,q=_,V=il,Z=Ad;for(let ce=BigInt(l-1);ce>=Ad;ce--){let Fe=S>>ce&il;Z^=Fe,{x_2:B,x_3:q}=L(Z,B,q),{x_2:I,x_3:V}=L(Z,I,V),Z=Fe;let Ue=B+I,$e=g(Ue*Ue),_e=B-I,tt=g(_e*_e),ii=$e-tt,na=q+V,Uc=q-V,Qu=g(Uc*Ue),Zu=g(na*_e),$x=Qu+Zu,Hx=Qu-Zu;q=g($x*$x),V=g(P*g(Hx*Hx)),B=g($e*tt),I=g(ii*($e+g(f*ii)))}({x_2:B,x_3:q}=L(Z,B,q)),{x_2:I,x_3:V}=L(Z,I,V);let fe=i(I);return g(B*fe)}let M={secretKey:u,publicKey:u,seed:u},x=_=>(_=_===void 0?c(u):_,pe(_,M.seed,"seed"),_),A={randomSecretKey:x};return Object.freeze(M),Object.freeze(A),Object.freeze({keygen:ol(x,U),getSharedSecret:C,getPublicKey:U,scalarMult:D,scalarMultBase:O,utils:A,GuBytes:m.slice(),lengths:M})}var p$=BigInt(0),mi=BigInt(1),dv=BigInt(2),m$=BigInt(3),g$=BigInt(5),y$=BigInt(8),Sa=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),N6={p:Sa,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:y$,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function pv(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),i=Sa,a=r*r%i*r%i,c=Qe(a,dv,i)*a%i,l=Qe(c,mi,i)*r%i,u=Qe(l,g$,i)*l%i,d=Qe(u,e,i)*u%i,f=Qe(d,t,i)*d%i,h=Qe(f,n,i)*f%i,p=Qe(h,o,i)*h%i,y=Qe(p,o,i)*h%i,g=Qe(y,e,i)*u%i;return{pow_p_5_8:Qe(g,dv,i)*r%i,b2:a}}function mv(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var P6=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function O6(r,e){let t=Sa,n=ot(e*e*e,t),o=ot(n*n*e,t),i=pv(r*o).pow_p_5_8,s=ot(r*n*i,t),a=ot(e*s*s,t),c=s,l=ot(s*P6,t),u=a===r,d=a===ot(-r,t),f=a===ot(-r*P6,t);return u&&(s=c),(d||f)&&(s=l),pi(s,t)&&(s=ot(-s,t)),{isValid:u||d,value:s}}var os=av(N6,{uvRatio:O6}),ns=os.Fp,gv=os.Fn;function w$(r){return cv(os,Lo,Object.assign({adjustScalarBytes:mv,zip215:!0},r))}var Td=w$({});var _d=(()=>{let r=Sa;return uv({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=pv(e);return ot(Qe(t,m$,r)*n,r)},adjustScalarBytes:mv})})();var D6=P6,b$=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),x$=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),E$=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),v$=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),fv=r=>O6(mi,r),S$=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),L6=r=>ns.create(en(r)&S$);function hv(r){let{d:e}=N6,t=Sa,n=m=>ns.create(m),o=n(D6*r*r),i=n((o+mi)*E$),s=BigInt(-1),a=n((s-e*o)*n(o+e)),{isValid:c,value:l}=O6(i,a),u=n(l*r);pi(u,t)||(u=n(-u)),c||(l=u),c||(s=o);let d=n(s*(o-mi)*v$-a),f=l*l,h=n((l+l)*a),p=n(d*b$),y=n(mi-f),g=n(mi+f);return new os(n(h*g),n(y*p),n(p*g),n(h*y))}var is=class r extends em{static BASE=new r(os.BASE);static ZERO=new r(os.ZERO);static Fp=ns;static Fn=gv;constructor(e){super(e)}static fromAffine(e){return new r(os.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static fromBytes(e){Xt(e,32);let{a:t,d:n}=N6,o=Sa,i=R=>ns.create(R),s=L6(e);if(!qE(ns.toBytes(s),e)||pi(s,o))throw new Error("invalid ristretto255 encoding 1");let a=i(s*s),c=i(mi+t*a),l=i(mi-t*a),u=i(c*c),d=i(l*l),f=i(t*n*u-d),{isValid:h,value:p}=fv(i(f*d)),y=i(p*l),g=i(p*y*f),m=i((s+s)*y);pi(m,o)&&(m=i(-m));let b=i(c*g),T=i(m*b);if(!h||pi(T,o)||b===p$)throw new Error("invalid ristretto255 encoding 2");return new r(new os(m,b,mi,T))}static fromHex(e){return r.fromBytes(pd(e))}toBytes(){let{X:e,Y:t,Z:n,T:o}=this.ep,i=Sa,s=g=>ns.create(g),a=s(s(n+t)*s(n-t)),c=s(e*t),l=s(c*c),{value:u}=fv(s(a*l)),d=s(u*a),f=s(u*c),h=s(d*f*o),p;if(pi(o*h,i)){let g=s(t*D6),m=s(e*D6);e=g,t=m,p=s(d*x$)}else p=f;pi(e*h,i)&&(t=s(-t));let y=s((n-t)*p);return pi(y,i)&&(y=s(-y)),ns.toBytes(y)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:o,Y:i}=e.ep,s=l=>ns.create(l),a=s(t*i)===s(n*o),c=s(n*i)===s(t*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(is.BASE);Object.freeze(is.ZERO);Object.freeze(is.prototype);Object.freeze(is);var A$=Object.freeze({Point:is,hashToCurve(r,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=R6(r,t,64,Lo);return A$.deriveToCurve(n)},hashToScalar(r,e={DST:lv}){let t=R6(r,e.DST,64,Lo);return gv.create(en(t))},deriveToCurve(r){Xt(r,64);let e=L6(r.subarray(0,32)),t=hv(e),n=L6(r.subarray(32,64)),o=hv(n);return new is(t.add(o))}});var Aa=32,rn=64,B6=32;var sl,yv=(async()=>{try{return await At.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function wv(){let r=Td.utils.randomSecretKey(),e=Td.getPublicKey(r);return{privateKey:k$(r,e),publicKey:e}}async function T$(r,e){let t;r.length===rn?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:ze(r.subarray(32),"base64url"),d:ze(t,"base64url"),ext:!0,key_ops:["sign"]},o=await At.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),i=await At.get().subtle.sign({name:"Ed25519"},o,Pt(e instanceof Uint8Array?e:e.subarray()));return new Uint8Array(i,0,i.byteLength)}function _$(r,e){let t=r.subarray(0,B6);return Td.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function bv(r,e){return sl==null&&(sl=await yv),sl?T$(r,e):_$(r,e)}async function C$(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await At.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await At.get().subtle.verify({name:"Ed25519"},n,Pt(e),Pt(t instanceof Uint8Array?t:t.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function I$(r,e,t){return Td.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function xv(r,e,t){return sl==null&&(sl=await yv),sl?C$(r,e,t):I$(r,e,t)}function k$(r,e){let t=new Uint8Array(rn);for(let n=0;n<B6;n++)t[n]=r[n],t[B6+n]=e[n];return t}function R$(r){return r?.buffer instanceof ArrayBuffer}function vv(r){if(R$(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function M6(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=Mp(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return vv(t)}function al(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Cd=class{type="Ed25519";raw;constructor(e){this.raw=ll(e,Aa)}toMultihash(){return Ke.digest(Ht(this))}toCID(){return F.createV1(114,this.toMultihash())}toString(){return Ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=xv(this.raw,t,e);return al(o)?o.then(i=>(n?.signal?.throwIfAborted(),i)):o}},cl=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=ll(e,rn),this.publicKey=new Cd(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=bv(this.raw,e);return al(n)?n.then(o=>(t?.signal?.throwIfAborted(),o)):(t?.signal?.throwIfAborted(),n)}};function F6(r){if(r.length>rn){r=ll(r,rn+Aa);let n=r.subarray(0,rn),o=r.subarray(rn,r.length);return new cl(n,o)}r=ll(r,rn);let e=r.subarray(0,rn),t=r.subarray(Aa);return new cl(e,t)}function U6(r){return r=ll(r,Aa),new Cd(r)}async function Sv(){let{privateKey:r,publicKey:e}=wv();return new cl(r,e)}function ll(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new E(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var P$=Math.pow(2,7),D$=Math.pow(2,14),L$=Math.pow(2,21),$6=Math.pow(2,28),H6=Math.pow(2,35),q6=Math.pow(2,42),V6=Math.pow(2,49),Ne=128,lr=127;function ye(r){if(r<P$)return 1;if(r<D$)return 2;if(r<L$)return 3;if(r<$6)return 4;if(r<H6)return 5;if(r<q6)return 6;if(r<V6)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Id(r,e,t=0){switch(ye(r)){case 8:e[t++]=r&255|Ne,r/=128;case 7:e[t++]=r&255|Ne,r/=128;case 6:e[t++]=r&255|Ne,r/=128;case 5:e[t++]=r&255|Ne,r/=128;case 4:e[t++]=r&255|Ne,r>>>=7;case 3:e[t++]=r&255|Ne,r>>>=7;case 2:e[t++]=r&255|Ne,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function N$(r,e,t=0){switch(ye(r)){case 8:e.set(t++,r&255|Ne),r/=128;case 7:e.set(t++,r&255|Ne),r/=128;case 6:e.set(t++,r&255|Ne),r/=128;case 5:e.set(t++,r&255|Ne),r/=128;case 4:e.set(t++,r&255|Ne),r>>>=7;case 3:e.set(t++,r&255|Ne),r>>>=7;case 2:e.set(t++,r&255|Ne),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function kd(r,e){let t=r[e],n=0;if(n+=t&lr,t<Ne||(t=r[e+1],n+=(t&lr)<<7,t<Ne)||(t=r[e+2],n+=(t&lr)<<14,t<Ne)||(t=r[e+3],n+=(t&lr)<<21,t<Ne)||(t=r[e+4],n+=(t&lr)*$6,t<Ne)||(t=r[e+5],n+=(t&lr)*H6,t<Ne)||(t=r[e+6],n+=(t&lr)*q6,t<Ne)||(t=r[e+7],n+=(t&lr)*V6,t<Ne))return n;throw new RangeError("Could not decode varint")}function O$(r,e){let t=r.get(e),n=0;if(n+=t&lr,t<Ne||(t=r.get(e+1),n+=(t&lr)<<7,t<Ne)||(t=r.get(e+2),n+=(t&lr)<<14,t<Ne)||(t=r.get(e+3),n+=(t&lr)<<21,t<Ne)||(t=r.get(e+4),n+=(t&lr)*$6,t<Ne)||(t=r.get(e+5),n+=(t&lr)*H6,t<Ne)||(t=r.get(e+6),n+=(t&lr)*q6,t<Ne)||(t=r.get(e+7),n+=(t&lr)*V6,t<Ne))return n;throw new RangeError("Could not decode varint")}function ur(r,e,t=0){return e==null&&(e=nt(ye(r))),e instanceof Uint8Array?Id(r,e,t):N$(r,e,t)}function No(r,e=0){return r instanceof Uint8Array?kd(r,e):O$(r,e)}var K6=new Float32Array([-0]),as=new Uint8Array(K6.buffer);function Av(r,e,t){K6[0]=r,e[t]=as[0],e[t+1]=as[1],e[t+2]=as[2],e[t+3]=as[3]}function Tv(r,e){return as[0]=r[e],as[1]=r[e+1],as[2]=r[e+2],as[3]=r[e+3],K6[0]}var z6=new Float64Array([-0]),dr=new Uint8Array(z6.buffer);function _v(r,e,t){z6[0]=r,e[t]=dr[0],e[t+1]=dr[1],e[t+2]=dr[2],e[t+3]=dr[3],e[t+4]=dr[4],e[t+5]=dr[5],e[t+6]=dr[6],e[t+7]=dr[7]}function Cv(r,e){return dr[0]=r[e],dr[1]=r[e+1],dr[2]=r[e+2],dr[3]=r[e+3],dr[4]=r[e+4],dr[5]=r[e+5],dr[6]=r[e+6],dr[7]=r[e+7],z6[0]}var B$=BigInt(Number.MAX_SAFE_INTEGER),M$=BigInt(Number.MIN_SAFE_INTEGER),nn=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 Ta;if(e<B$&&e>M$)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>Iv&&(o=0n,++n>Iv&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Ta;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):Ta}},Ta=new nn(0,0);Ta.toBigInt=function(){return 0n};Ta.zzEncode=Ta.zzDecode=function(){return this};Ta.length=function(){return 1};var Iv=4294967296n;function kv(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 Rv(r,e,t){if(t-e<1)return"";let o,i=[],s=0,a;for(;e<t;)a=r[e++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(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,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function G6(r,e,t){let n=t,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,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 oo(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function rm(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var W6=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,oo(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 oo(this,4);return rm(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw oo(this,4);return rm(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw oo(this,4);let e=Tv(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw oo(this,4);let e=Cv(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 oo(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Rv(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw oo(this,e);this.pos+=e}else do if(this.pos>=this.len)throw oo(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 nn(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 oo(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 oo(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 oo(this,8);let e=rm(this.buf,this.pos+=4),t=rm(this.buf,this.pos+=4);return new nn(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=kd(this.buf,this.pos);return this.pos+=ye(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 Rd(r){return new W6(r instanceof Uint8Array?r:r.subarray())}function J(r,e,t){let n=Rd(r);return e.decode(n,void 0,t)}function Lv(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Dv=Lv("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),j6=Lv("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=nt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),F$={utf8:Dv,"utf-8":Dv,hex:oe.base16,latin1:j6,ascii:j6,binary:j6,...oe},nm=F$;function K(r,e="utf8"){let t=nm[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Y6(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return nt(s);o+s>e&&(n=nt(e),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var _a=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function X6(){}var Z6=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},U$=Y6();function $$(r){return globalThis.Buffer!=null?nt(r):U$(r)}var Dd=class{len;head;tail;states;constructor(){this.len=0,this.head=new _a(X6,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new _a(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new J6((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(om,10,nn.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=nn.fromBigInt(e);return this._push(om,t.length(),t)}uint64Number(e){return this._push(Id,ye(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=nn.fromBigInt(e).zzEncode();return this._push(om,t.length(),t)}sint64Number(e){let t=nn.fromNumber(e).zzEncode();return this._push(om,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Q6,1,e?1:0)}fixed32(e){return this._push(Pd,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=nn.fromBigInt(e);return this._push(Pd,4,t.lo)._push(Pd,4,t.hi)}fixed64Number(e){let t=nn.fromNumber(e);return this._push(Pd,4,t.lo)._push(Pd,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(Av,4,e)}double(e){return this._push(_v,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Q6,1,0):this.uint32(t)._push(q$,t,e)}string(e){let t=kv(e);return t!==0?this.uint32(t)._push(G6,t,e):this._push(Q6,1,0)}fork(){return this.states=new Z6(this),this.head=this.tail=new _a(X6,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 _a(X6,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=$$(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Q6(r,e,t){e[t]=r&255}function H$(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var J6=class extends _a{next;constructor(e,t){super(H$,e,t),this.next=void 0}};function om(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 Pd(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 q$(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Dd.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(V$,e,r),this},Dd.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(K$,e,r),this});function V$(r,e,t){e.set(r,t)}function K$(r,e,t){r.length<40?G6(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(K(r),t)}function e8(){return new Dd}function ee(r,e){let t=e8();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}function*te(r,e,t){let n=Rd(r);yield*e.stream(n,void 0,"$",t)}var im={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function sm(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}function Ye(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(s,a){let c=e(s);a.int32(c)},n=function(s){let a=s.int32();return e(a)},o=function*(s){let a=s.int32();yield e(a)};return sm("enum",im.VARINT,t,n,o)}function re(r,e,t){return sm("message",im.LENGTH_DELIMITED,r,e,t)}var le=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},Ld=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var Ge;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Ge||(Ge={}));var t8;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(t8||(t8={}));(function(r){r.codec=()=>Ye(t8)})(Ge||(Ge={}));var Oo;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Type!=null&&(s.uint32(8),Ge.codec().encode(i.Type,s)),i.Data!=null&&(s.uint32(18),s.bytes(i.Data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.Type=Ge.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Ge.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Oo||(Oo={}));var Nd;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Type!=null&&(s.uint32(8),Ge.codec().encode(i.Type,s)),i.Data!=null&&(s.uint32(18),s.bytes(i.Data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.Type=Ge.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:Ge.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Nd||(Nd={}));function kr(r){if(isNaN(r)||r<=0)throw new E("random bytes length must be a Number bigger than 0");return Vp(r)}var Bd={};xt(Bd,{MAX_RSA_KEY_SIZE:()=>r8,generateRSAKeyPair:()=>d8,jwkToJWKKeyPair:()=>Mv,jwkToPkcs1:()=>j$,jwkToPkix:()=>s8,jwkToRSAPrivateKey:()=>u8,pkcs1MessageToJwk:()=>o8,pkcs1MessageToRSAPrivateKey:()=>am,pkcs1ToJwk:()=>W$,pkcs1ToRSAPrivateKey:()=>a8,pkixMessageToJwk:()=>i8,pkixMessageToRSAPublicKey:()=>l8,pkixToJwk:()=>Y$,pkixToRSAPublicKey:()=>c8});var ul=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Bd.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return F.createV1(114,this._multihash)}toString(){return Ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}verify(e,t,n){return Bv(this.jwk,t,e,n)}},Od=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Bd.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}sign(e,t){return Ov(this.jwk,e,t)}};var r8=8192,n8=18,z$=1062,G$=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function W$(r){let e=On(r);return o8(e)}function o8(r){return{n:ze(r[1],"base64url"),e:ze(r[2],"base64url"),d:ze(r[3],"base64url"),p:ze(r[4],"base64url"),q:ze(r[5],"base64url"),dp:ze(r[6],"base64url"),dq:ze(r[7],"base64url"),qi:ze(r[8],"base64url"),kty:"RSA"}}function j$(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 E("JWK was missing components");return eo([Ir(Uint8Array.from([0])),Ir(lt(r.n,"base64url")),Ir(lt(r.e,"base64url")),Ir(lt(r.d,"base64url")),Ir(lt(r.p,"base64url")),Ir(lt(r.q,"base64url")),Ir(lt(r.dp,"base64url")),Ir(lt(r.dq,"base64url")),Ir(lt(r.qi,"base64url"))]).subarray()}function Y$(r){let e=On(r,{offset:0});return i8(e)}function i8(r){let e=On(r[1],{offset:0});return{kty:"RSA",n:ze(e[0],"base64url"),e:ze(e[1],"base64url")}}function s8(r){if(r.n==null||r.e==null)throw new E("JWK was missing components");return eo([G$,hd(eo([Ir(lt(r.n,"base64url")),Ir(lt(r.e,"base64url"))]))]).subarray()}function a8(r){let e=On(r);return am(e)}function am(r){let e=o8(r);return u8(e)}function c8(r,e){if(r.byteLength>=z$)throw new ai("Key size is too large");let t=On(r,{offset:0});return l8(t,r,e)}function l8(r,e,t){let n=i8(r);if(t==null){let o=Bn(Oo.encode({Type:Ge.RSA,Data:e}));t=Cr(n8,o)}return new ul(n,t)}function u8(r){if(Uv(r)>r8)throw new E("Key size is too large");let e=Mv(r),t=Bn(Oo.encode({Type:Ge.RSA,Data:s8(e.publicKey)})),n=Cr(n8,t);return new Od(e.privateKey,new ul(e.publicKey,n))}async function d8(r){if(r>r8)throw new E("Key size is too large");let e=await Fv(r),t=Bn(Oo.encode({Type:Ge.RSA,Data:s8(e.publicKey)})),n=Cr(n8,t);return new Od(e.privateKey,new ul(e.publicKey,n))}function Mv(r){if(r==null)throw new E("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Fv(r,e){let t=await At.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 X$(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Ov(r,e,t){let n=await At.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await At.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Pt(e instanceof Uint8Array?e:e.subarray()));return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Bv(r,e,t,n){let o=await At.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let i=await At.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Pt(e),Pt(t instanceof Uint8Array?t:t.subarray()));return n?.signal?.throwIfAborted(),i}async function X$(r,e){if(r.privateKey==null||r.publicKey==null)throw new E("Private and public key are required");let t=await Promise.all([At.get().subtle.exportKey("jwk",r.privateKey),At.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Uv(r){if(r.kty!=="RSA")throw new E("invalid key type");if(r.n==null)throw new E("invalid key modulus");return lt(r.n,"base64url").length*8}var cm=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(di(e),Xt(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 i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),cr(o)}update(e){return Qc(this),this.iHash.update(e),this}digestInto(e){Qc(this),$p(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),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:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ca=(()=>{let r=((e,t,n)=>new cm(e,t).update(n).digest());return r.create=(e,t)=>new cm(e,t),r})();var $v=(r,e)=>(r+(r>=0?e:-e)/Hv)/e;function Q$(r,e,t){hi("scalar",r,Bo,t);let[[n,o],[i,s]]=e,a=$v(s*r,t),c=$v(-o*r,t),l=r-a*n-c*i,u=-a*o-c*s,d=l<Bo,f=u<Bo;d&&(l=-l),f&&(u=-u);let h=xd(Math.ceil(el(t)/2))+cs;if(l<Bo||l>=h||u<Bo||u>=h)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:d,k1:l,k2neg:f,k2:u}}function h8(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function f8(r,e){tn(r);let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return ro(t.lowS,"lowS"),ro(t.prehash,"prehash"),t.format!==void 0&&h8(t.format),t}var p8=class extends Error{constructor(e=""){super(e)}},io={Err:p8,_tlv:{encode:(r,e)=>{let{Err:t}=io;if(no(r,"tag"),r<0||r>255)throw new t("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=wd(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?wd(o.length/2|128):"";return wd(r)+i+o+e},decode(r,e){let{Err:t}=io;e=pe(e,void 0,"DER data");let n=0;if(r<0||r>255)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let o=e[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(r){let{Err:e}=io;if(Yp(r),r<Bo)throw new e("integer: negative integers are not allowed");let t=wd(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}=io;if(r.length<1)throw new e("invalid signature integer: empty");if(r[0]&128)throw new e("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return ba(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=io,o=pe(r,void 0,"signature"),{v:i,l:s}=n.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=io,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),i=n+o;return e.encode(48,i)}};Object.freeze(io._tlv);Object.freeze(io._int);Object.freeze(io);var Bo=BigInt(0),cs=BigInt(1),Hv=BigInt(2),lm=BigInt(3),Z$=BigInt(4);function qv(r,e={}){let t=Jp("weierstrass",r,e),n=t.Fp,o=t.Fn,i=t.CURVE,{h:s,n:a}=i;tn(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Kv(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(M,x,A){if(l&&x.is0())return Uint8Array.of(0);let{x:_,y:v}=x.toAffine(),S=n.toBytes(_);if(ro(A,"isCompressed"),A){d();let P=!n.isOdd(v);return Dt(Vv(P),S)}else return Dt(Uint8Array.of(4),S,n.toBytes(v))}function h(M){pe(M,void 0,"Point");let{publicKey:x,publicKeyUncompressed:A}=u,_=M.length,v=M[0],S=M.subarray(1);if(l&&_===1&&v===0)return{x:n.ZERO,y:n.ZERO};if(_===x&&(v===2||v===3)){let P=n.fromBytes(S);if(!n.isValid(P))throw new Error("bad point: is not on curve, wrong x");let B=g(P),I;try{I=n.sqrt(B)}catch(Z){let fe=Z instanceof Error?": "+Z.message:"";throw new Error("bad point: is not on curve, sqrt error"+fe)}d();let q=n.isOdd(I);return(v&1)===1!==q&&(I=n.neg(I)),{x:P,y:I}}else if(_===A&&v===4){let P=n.BYTES,B=n.fromBytes(S.subarray(0,P)),I=n.fromBytes(S.subarray(P,P*2));if(!m(B,I))throw new Error("bad point: is not on curve");return{x:B,y:I}}else throw new Error(`bad point: got length ${_}, expected compressed=${x} or uncompressed=${A}`)}let p=e.toBytes===void 0?f:e.toBytes,y=e.fromBytes===void 0?h:e.fromBytes;function g(M){let x=n.sqr(M),A=n.mul(x,M);return n.add(n.add(A,n.mul(M,i.a)),i.b)}function m(M,x){let A=n.sqr(x),_=g(M);return n.eql(A,_)}if(!m(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let b=n.mul(n.pow(i.a,lm),Z$),T=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(b,T)))throw new Error("bad curve params: a or b");function R(M,x,A=!1){if(!n.isValid(x)||A&&n.is0(x))throw new Error(`bad point coordinate ${M}`);return x}function D(M){if(!(M instanceof C))throw new Error("Weierstrass Point expected")}function O(M){if(!c||!c.basises)throw new Error("no endo");return Q$(M,c.basises,o.ORDER)}function U(M,x,A,_,v){return A=new C(n.mul(A.X,M),A.Y,A.Z),x=vd(_,x),A=vd(v,A),x.add(A)}class C{static BASE=new C(i.Gx,i.Gy,n.ONE);static ZERO=new C(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(x,A,_){this.X=R("x",x),this.Y=R("y",A,!0),this.Z=R("z",_),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){let{x:A,y:_}=x||{};if(!x||!n.isValid(A)||!n.isValid(_))throw new Error("invalid affine point");if(x instanceof C)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(_)?C.ZERO:new C(A,_,n.ONE)}static fromBytes(x){let A=C.fromAffine(y(pe(x,void 0,"point")));return A.assertValidity(),A}static fromHex(x){return C.fromBytes(Jc(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,A=!0){return H.createCache(this,x),A||this.multiply(lm),this}assertValidity(){let x=this;if(x.is0()){if(e.allowInfinityPoint&&n.is0(x.X)&&n.eql(x.Y,n.ONE)&&n.is0(x.Z))return;throw new Error("bad point: ZERO")}let{x:A,y:_}=x.toAffine();if(!n.isValid(A)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!m(A,_))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){D(x);let{X:A,Y:_,Z:v}=this,{X:S,Y:P,Z:B}=x,I=n.eql(n.mul(A,B),n.mul(S,v)),q=n.eql(n.mul(_,B),n.mul(P,v));return I&&q}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:A}=i,_=n.mul(A,lm),{X:v,Y:S,Z:P}=this,B=n.ZERO,I=n.ZERO,q=n.ZERO,V=n.mul(v,v),Z=n.mul(S,S),fe=n.mul(P,P),ce=n.mul(v,S);return ce=n.add(ce,ce),q=n.mul(v,P),q=n.add(q,q),B=n.mul(x,q),I=n.mul(_,fe),I=n.add(B,I),B=n.sub(Z,I),I=n.add(Z,I),I=n.mul(B,I),B=n.mul(ce,B),q=n.mul(_,q),fe=n.mul(x,fe),ce=n.sub(V,fe),ce=n.mul(x,ce),ce=n.add(ce,q),q=n.add(V,V),V=n.add(q,V),V=n.add(V,fe),V=n.mul(V,ce),I=n.add(I,V),fe=n.mul(S,P),fe=n.add(fe,fe),V=n.mul(fe,ce),B=n.sub(B,V),q=n.mul(fe,Z),q=n.add(q,q),q=n.add(q,q),new C(B,I,q)}add(x){D(x);let{X:A,Y:_,Z:v}=this,{X:S,Y:P,Z:B}=x,I=n.ZERO,q=n.ZERO,V=n.ZERO,Z=i.a,fe=n.mul(i.b,lm),ce=n.mul(A,S),Fe=n.mul(_,P),Ue=n.mul(v,B),$e=n.add(A,_),_e=n.add(S,P);$e=n.mul($e,_e),_e=n.add(ce,Fe),$e=n.sub($e,_e),_e=n.add(A,v);let tt=n.add(S,B);return _e=n.mul(_e,tt),tt=n.add(ce,Ue),_e=n.sub(_e,tt),tt=n.add(_,v),I=n.add(P,B),tt=n.mul(tt,I),I=n.add(Fe,Ue),tt=n.sub(tt,I),V=n.mul(Z,_e),I=n.mul(fe,Ue),V=n.add(I,V),I=n.sub(Fe,V),V=n.add(Fe,V),q=n.mul(I,V),Fe=n.add(ce,ce),Fe=n.add(Fe,ce),Ue=n.mul(Z,Ue),_e=n.mul(fe,_e),Fe=n.add(Fe,Ue),Ue=n.sub(ce,Ue),Ue=n.mul(Z,Ue),_e=n.add(_e,Ue),ce=n.mul(Fe,_e),q=n.add(q,ce),ce=n.mul(tt,_e),I=n.mul($e,I),I=n.sub(I,ce),ce=n.mul($e,Fe),V=n.mul(tt,V),V=n.add(V,ce),new C(I,q,V)}subtract(x){return D(x),this.add(x.negate())}is0(){return this.equals(C.ZERO)}multiply(x){let{endo:A}=e;if(!o.isValidNot0(x))throw new RangeError("invalid scalar: out of range");let _,v,S=P=>H.cached(this,P,B=>va(C,B));if(A){let{k1neg:P,k1:B,k2neg:I,k2:q}=O(x),{p:V,f:Z}=S(B),{p:fe,f:ce}=S(q);v=Z.add(ce),_=U(A.beta,V,fe,P,I)}else{let{p:P,f:B}=S(x);_=P,v=B}return va(C,[_,v])[0]}multiplyUnsafe(x){let{endo:A}=e,_=this,v=x;if(!o.isValid(v))throw new RangeError("invalid scalar: out of range");if(v===Bo||_.is0())return C.ZERO;if(v===cs)return _;if(H.hasCache(this))return this.multiply(v);if(A){let{k1neg:S,k1:P,k2neg:B,k2:I}=O(v),{p1:q,p2:V}=sv(C,_,P,I);return U(A.beta,q,V,S,B)}else return H.unsafe(_,v)}toAffine(x){let A=this,_=x,{X:v,Y:S,Z:P}=A;if(n.eql(P,n.ONE))return{x:v,y:S};let B=A.is0();_==null&&(_=B?n.ONE:n.inv(P));let I=n.mul(v,_),q=n.mul(S,_),V=n.mul(P,_);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(V,n.ONE))throw new Error("invZ was invalid");return{x:I,y:q}}isTorsionFree(){let{isTorsionFree:x}=e;return s===cs?!0:x?x(C,this):H.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return s===cs?this:x?x(C,this):this.multiplyUnsafe(s)}isSmallOrder(){return s===cs?this.is0():this.clearCofactor().is0()}toBytes(x=!0){return ro(x,"isCompressed"),this.assertValidity(),p(C,this,x)}toHex(x=!0){return Zc(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let L=o.BITS,H=new nl(C,e.endo?Math.ceil(L/2):L);return L>=8&&C.BASE.precompute(8),Object.freeze(C.prototype),Object.freeze(C),C}function Vv(r){return Uint8Array.of(r?2:3)}function Kv(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function J$(r,e={}){let{Fn:t}=r,n=e.randomBytes===void 0?wa:e.randomBytes,o=Object.assign(Kv(r.Fp,t),{seed:Math.max(A6(t.ORDER),16)});function i(h){try{let p=t.fromBytes(h);return t.isValidNot0(p)}catch{return!1}}function s(h,p){let{publicKey:y,publicKeyUncompressed:g}=o;try{let m=h.length;return p===!0&&m!==y||p===!1&&m!==g?!1:!!r.fromBytes(h)}catch{return!1}}function a(h){return h=h===void 0?n(o.seed):h,T6(pe(h,o.seed,"seed"),t.ORDER)}function c(h,p=!0){return r.BASE.multiply(t.fromBytes(h)).toBytes(p)}function l(h){let{secretKey:p,publicKey:y,publicKeyUncompressed:g}=o,m=t._lengths;if(!ya(h))return;let b=pe(h,void 0,"key").length,T=b===y||b===g,R=b===p||!!m?.includes(b);if(!(T&&R))return T}function u(h,p,y=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");let g=t.fromBytes(h);return r.fromBytes(p).multiply(g).toBytes(y)}let d={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},f=ol(a,c);return Object.freeze(d),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:f,Point:r,utils:d,lengths:o})}function zv(r,e,t={}){let n=e;di(n),tn(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let o=t.randomBytes===void 0?wa:t.randomBytes,i=t.hmac===void 0?(v,S)=>Ca(n,v,S):t.hmac,{Fp:s,Fn:a}=r,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=J$(r,t),y={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},g=c*Hv+cs<s.ORDER;function m(v){let S=c>>cs;return v>S}function b(v,S){if(!a.isValidNot0(S))throw new Error(`invalid signature ${v}: out of range 1..Point.Fn.ORDER`);return S}function T(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function R(v,S){h8(S);let P=p.signature,B=S==="compact"?P:S==="recovered"?P+1:void 0;return pe(v,B)}class D{r;s;recovery;constructor(S,P,B){if(this.r=b("r",S),this.s=b("s",P),B!=null){if(T(),![0,1,2,3].includes(B))throw new Error("invalid recovery id");this.recovery=B}Object.freeze(this)}static fromBytes(S,P=y.format){R(S,P);let B;if(P==="der"){let{r:Z,s:fe}=io.toSig(pe(S));return new D(Z,fe)}P==="recovered"&&(B=S[0],P="compact",S=S.subarray(1));let I=p.signature/2,q=S.subarray(0,I),V=S.subarray(I,I*2);return new D(a.fromBytes(q),a.fromBytes(V),B)}static fromHex(S,P){return this.fromBytes(Jc(S),P)}assertRecovery(){let{recovery:S}=this;if(S==null)throw new Error("invalid recovery id: must be present");return S}addRecoveryBit(S){return new D(this.r,this.s,S)}recoverPublicKey(S){let{r:P,s:B}=this,I=this.assertRecovery(),q=I===2||I===3?P+c:P;if(!s.isValid(q))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let V=s.toBytes(q),Z=r.fromBytes(Dt(Vv((I&1)===0),V)),fe=a.inv(q),ce=U(pe(S,void 0,"msgHash")),Fe=a.create(-ce*fe),Ue=a.create(B*fe),$e=r.BASE.multiplyUnsafe(Fe).add(Z.multiplyUnsafe(Ue));if($e.is0())throw new Error("invalid recovery: point at infinify");return $e.assertValidity(),$e}hasHighS(){return m(this.s)}toBytes(S=y.format){if(h8(S),S==="der")return Jc(io.hexFromSig(this));let{r:P,s:B}=this,I=a.toBytes(P),q=a.toBytes(B);return S==="recovered"?(T(),Dt(Uint8Array.of(this.assertRecovery()),I,q)):Dt(I,q)}toHex(S){return Zc(this.toBytes(S))}}Object.freeze(D.prototype),Object.freeze(D);let O=t.bits2int===void 0?function(S){if(S.length>8192)throw new Error("input is too large");let P=ba(S),B=S.length*8-l;return B>0?P>>BigInt(B):P}:t.bits2int,U=t.bits2int_modN===void 0?function(S){return a.create(O(S))}:t.bits2int_modN,C=xd(l);function L(v){return hi("num < 2^"+l,v,Bo,C),a.toBytes(v)}function H(v,S){return pe(v,void 0,"message"),S?pe(n(v),void 0,"prehashed message"):v}function M(v,S,P){let{lowS:B,prehash:I,extraEntropy:q}=f8(P,y);v=H(v,I);let V=U(v),Z=a.fromBytes(S);if(!a.isValidNot0(Z))throw new Error("invalid private key");let fe=[L(Z),L(V)];if(q!=null&&q!==!1){let $e=q===!0?o(p.secretKey):q;fe.push(pe($e,void 0,"extraEntropy"))}let ce=Dt(...fe),Fe=V;function Ue($e){let _e=O($e);if(!a.isValidNot0(_e))return;let tt=a.inv(_e),ii=r.BASE.multiply(_e).toAffine(),na=a.create(ii.x);if(na===Bo)return;let Uc=a.create(tt*a.create(Fe+na*Z));if(Uc===Bo)return;let Qu=(ii.x===na?0:2)|Number(ii.y&cs),Zu=Uc;return B&&m(Uc)&&(Zu=a.neg(Uc),Qu^=1),new D(na,Zu,g?void 0:Qu)}return{seed:ce,k2sig:Ue}}function x(v,S,P={}){let{seed:B,k2sig:I}=M(v,S,P);return VE(n.outputLen,a.BYTES,i)(B,I).toBytes(P.format)}function A(v,S,P,B={}){let{lowS:I,prehash:q,format:V}=f8(B,y);if(P=pe(P,void 0,"publicKey"),S=H(S,q),!ya(v)){let Z=v instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+Z)}R(v,V);try{let Z=D.fromBytes(v,V),fe=r.fromBytes(P);if(I&&Z.hasHighS())return!1;let{r:ce,s:Fe}=Z,Ue=U(S),$e=a.inv(Fe),_e=a.create(Ue*$e),tt=a.create(ce*$e),ii=r.BASE.multiplyUnsafe(_e).add(fe.multiplyUnsafe(tt));return ii.is0()?!1:a.create(ii.x)===ce}catch{return!1}}function _(v,S,P={}){let{prehash:B}=f8(P,y);return S=H(S,B),D.fromBytes(v,"recovered").recoverPublicKey(S).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:r,sign:x,verify:A,recoverPublicKey:_,Signature:D,hash:n})}var g8={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},eH={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Gv=BigInt(2);function tH(r){let e=g8.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=Qe(u,t,e)*u%e,f=Qe(d,t,e)*u%e,h=Qe(f,Gv,e)*l%e,p=Qe(h,o,e)*h%e,y=Qe(p,i,e)*p%e,g=Qe(y,a,e)*y%e,m=Qe(g,c,e)*g%e,b=Qe(m,a,e)*y%e,T=Qe(b,t,e)*u%e,R=Qe(T,s,e)*p%e,D=Qe(R,n,e)*l%e,O=Qe(D,Gv,e);if(!m8.eql(m8.sqr(O),r))throw new Error("Cannot find square root");return O}var m8=tl(g8.p,{sqrt:tH}),rH=qv(g8,{Fp:m8,endo:eH}),so=zv(rH,Bn);var Wv=32;function jv(r,e,t){let n=ct.digest(e instanceof Uint8Array?e:e.subarray());if(al(n))return n.then(({digest:o})=>(t?.signal?.throwIfAborted(),so.sign(o,r,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new od(String(o))});try{return so.sign(n.digest,r,{prehash:!1,format:"der"})}catch(o){throw new od(String(o))}}function Yv(r,e,t,n){let o=ct.digest(t instanceof Uint8Array?t:t.subarray());if(al(o))return o.then(({digest:i})=>(n?.signal?.throwIfAborted(),so.verify(e,i,r,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new id(String(i))});try{return n?.signal?.throwIfAborted(),so.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(i){throw new id(String(i))}}var Md=class{type="secp256k1";raw;_key;constructor(e){this._key=Zv(e),this.raw=Xv(this._key)}toMultihash(){return Ke.digest(Ht(this))}toCID(){return F.createV1(114,this.toMultihash())}toString(){return Ce.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}verify(e,t,n){return Yv(this._key,t,e,n)}},Fd=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=Qv(e),this.publicKey=new Md(t??Jv(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Dn(this.raw,e.raw)}sign(e,t){return jv(this.raw,e,t)}};function y8(r){return new Fd(r)}function w8(r){return new Md(r)}async function eS(){let r=nH();return new Fd(r)}function Xv(r){return so.Point.fromBytes(r).toBytes()}function Qv(r){try{return so.getPublicKey(r,!0),r}catch(e){throw new Ju(String(e))}}function Zv(r){try{return so.Point.fromBytes(r),r}catch(e){throw new ai(String(e))}}function Jv(r){try{return so.getPublicKey(r,!0)}catch(e){throw new Ju(String(e))}}function nH(){return so.utils.randomSecretKey()}async function um(r,e){if(r==="Ed25519")return Sv();if(r==="secp256k1")return eS();if(r==="RSA")return d8(oH(e));if(r==="ECDSA")return CE(iH(e));throw new Zn}function Et(r,e){let{Type:t,Data:n}=Oo.decode(r),o=n??new Uint8Array;switch(t){case Ge.RSA:return c8(o,e);case Ge.Ed25519:return U6(o);case Ge.secp256k1:return w8(o);case Ge.ECDSA:return c6(o);default:throw new Zn}}function dm(r){let{Type:e,Data:t}=Oo.decode(r.digest),n=t??new Uint8Array;switch(e){case Ge.Ed25519:return U6(n);case Ge.secp256k1:return w8(n);case Ge.ECDSA:return c6(n);default:throw new Zn}}function Ht(r){return Oo.encode({Type:Ge[r.type],Data:r.raw})}function tS(r){let e=Nd.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Ge.RSA:return a8(t);case Ge.Ed25519:return F6(t);case Ge.secp256k1:return y8(t);case Ge.ECDSA:return vE(t);default:throw new Zn}}function rS(r){if(r.byteLength===rn)return F6(r);if(r.byteLength===Wv)return y8(r);let e=On(r),t=e[2]?.[0];if(t===nE||t===oE||t===iE)return a6(e);if(e.length>8)return am(e);throw new E("Could not extract private key from raw bytes")}function Ia(r){return Nd.encode({Type:Ge[r.type],Data:r.raw})}function oH(r){return r==null?2048:parseInt(r,10)}function iH(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 E("Unsupported curve, should be P-256, P-384 or P-521")}var Ud=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),ls=new Uint32Array(80),b8=class extends pa{A=Ud[0]|0;B=Ud[1]|0;C=Ud[2]|0;D=Ud[3]|0;E=Ud[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:i}=this;return[e,t,n,o,i]}set(e,t,n,o,i){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0}process(e,t){for(let c=0;c<16;c++,t+=4)ls[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)ls[c]=Hp(ls[c-3]^ls[c-8]^ls[c-14]^ls[c-16],1);let{A:n,B:o,C:i,D:s,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=Kp(o,i,s),u=1518500249):c<40?(l=o^i^s,u=1859775393):c<60?(l=zp(o,i,s),u=2400959708):(l=o^i^s,u=3395469782);let d=Hp(n,5)+l+a+u+ls[c]|0;a=s,s=i,i=Hp(o,30),o=n,n=d}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,o,i,s,a)}roundClean(){cr(ls)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),cr(this.buffer)}},nS=md(()=>new b8);function oS(r,e,t,n){di(r);let o=PE({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(Ur(i,"c"),Ur(s,"dkLen"),Ur(a,"asyncTick"),i<1)throw new Error("iterations (c) must be >= 1");if(s<1)throw new Error('"dkLen" must be >= 1');if(s>(2**32-1)*r.outputLen)throw new Error("derived key too long");let c=u6(e,"password"),l=u6(t,"salt"),u=new Uint8Array(s),d=Ca.create(r,c),f=d._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:a,DK:u,PRF:d,PRFSalt:f}}function iS(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),cr(o),t}function sS(r,e,t,n){let{c:o,dkLen:i,DK:s,PRF:a,PRFSalt:c}=oS(r,e,t,n),l,u=new Uint8Array(4),d=ha(u),f=new Uint8Array(a.outputLen);for(let h=1,p=0;p<i;h++,p+=a.outputLen){let y=s.subarray(p,p+a.outputLen);d.setInt32(0,h,!1),(l=c._cloneInto(l)).update(u).digestInto(f),y.set(f.subarray(0,y.length));for(let g=1;g<o;g++){a._cloneInto(l).update(f).digestInto(f);for(let m=0;m<y.length;m++)y[m]^=f[m]}}return iS(a,c,s,l,f)}async function fm(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=oS(r,e,t,n),u,d=new Uint8Array(4),f=ha(d),h=new Uint8Array(c.outputLen);for(let p=1,y=0;y<i;p++,y+=c.outputLen){let g=a.subarray(y,y+c.outputLen);f.setInt32(0,p,!1),(u=l._cloneInto(u)).update(d).digestInto(h),g.set(h.subarray(0,g.length)),await RE(o-1,s,()=>{c._cloneInto(u).update(h).digestInto(h);for(let m=0;m<g.length;m++)g[m]^=h[m]})}return iS(c,l,a,u,h)}var aS={sha1:nS,"sha2-256":Bn,"sha2-512":Lo};function $d(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(aS).join(" / ");throw new E(`Hash '${o}' is unknown or not supported. Must be ${a}`)}let i=aS[o],s=sS(i,r,e,{c:t,dkLen:n});return Tt.encode(s).substring(1)}function cS(r=0){return new Uint8Array(r)}function lS(r=0){return new Uint8Array(r)}function dS(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var uS=dS("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),x8=dS("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=lS(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),sH={utf8:uS,"utf-8":uS,hex:oe.base16,latin1:x8,ascii:x8,binary:x8,...oe},fS=sH;function Mo(r,e="utf8"){let t=fS[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var E8={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},hS={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},pS=new globalThis.TextEncoder;function aH(r,e){let t=E8[e],n=hS[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function cH(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=E8[e],o=hS[e],i=r;for(;i.length>0;){let s=pS.encodeInto(i,t);i=i.slice(s.read);for(let a=0;a<s.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function v8(r,{size:e=32,utf8Buffer:t}={}){if(!E8[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 cH(r,e,t);r=pS.encode(r)}return aH(r,e)}var Hd={hash:r=>Number(v8(r,{size:32})),hashV:(r,e)=>lH(Hd.hash(r,e))};function lH(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),Mo(e,"base16")}function mS(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 S8=64,ao=class{fp;h;seed;constructor(e,t,n,o=2){if(o>S8)throw new TypeError("Invalid Fingerprint Size");let i=t.hashV(e,n),s=cS(o);for(let a=0;a<s.length;a++)s[a]=i[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?mS(this.fp,e.fp):!1}};function ka(r,e){return Math.floor(Math.random()*(e-r))+r}var Ra=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ao))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ao))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 ao))throw new TypeError("Invalid Fingerprint");let t=ka(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ao))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var uH=500,qd=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??Hd,this.seed=e.seed??ka(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=Mo(e));let t=new ao(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 Ra(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Ra(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let i=[n,o],s=i[ka(0,i.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Ra(this.bucketSize));for(let a=0;a<uH;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new Ra(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=Mo(e));let t=new ao(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let i=(n^t.hash())%this.filterSize;return this.buckets[i]?.has(t)??!1}remove(e){typeof e=="string"&&(e=Mo(e));let t=new ao(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let i=(n^t.hash())%this.filterSize,s=this.buckets[i]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},dH={1:.5,2:.84,4:.95,8:.98};function fH(r=.001){return r>.002?2:r>1e-5?4:8}function gS(r,e=.001){let t=fH(e),n=dH[t],o=Math.round(r/n),i=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),S8);return{filterSize:o,bucketSize:t,fingerprintSize:i}}var hm=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??Hd,this.seed=e.seed??ka(0,Math.pow(2,10)),this.filterSeries=[new qd({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=Mo(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 qd({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=Mo(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=Mo(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 Lt(r,e=.001,t){return new hm({...gS(r,e),...t??{}})}function A8(r){let e=r.getComponents(),t={},n=0;return 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?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function ie(r){let e=A8(r);if(e==null)throw new E(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var pm=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let f=Number.parseInt(d,e);if(!Number.isNaN(f))return f});if(u===void 0)break;if(i*=e,i+=u,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var yS=45,hH=15,dl=new pm;function mm(r){if(!(r.length>hH))return dl.new(r).parseWith(()=>dl.readIPv4Addr())}function gm(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>yS))return dl.new(r).parseWith(()=>dl.readIPv6Addr())}function fl(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>yS)return;let t=dl.new(r).parseWith(()=>dl.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 wS(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 bS(r,e,t,n){let o=0;for(let i of r)if(!(o<t)){if(o>n)break;if(i!==e[o])return!1;o++}return!0}function T8(r){switch(r.length){case Pa:return r.join(".");case Da:{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 xS(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 ES(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var Pa=4,Da=16,Oce=parseInt("0xFFFF",16),pH=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Vd(r,e){e.length===Da&&r.length===Pa&&wS(e,0,11)&&(e=e.slice(12)),e.length===Pa&&r.length===Da&&bS(r,pH,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 vS(r,e){if(typeof e=="string"&&(e=fl(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 _8(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=Pa,o=mm(e);if(o==null&&(n=Da,o=gm(e),o==null))throw new Error("Failed to parse given CIDR: "+r);let i=parseInt(t,10);if(Number.isNaN(i)||String(i).length!==t.length||i<0||i>n*8)throw new Error("Failed to parse given CIDR: "+r);let s=C8(i,8*n);return{network:Vd(o,s),mask:s}}function C8(r,e){if(e!==8*Pa&&e!==8*Da)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 La=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=_8(e));else{let n=fl(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n.length*8){let i=fl(t);if(i==null)throw new Error("Failed to parse mask");this.mask=i}else this.mask=C8(o,8*n.length);this.network=Vd(n,this.mask)}}contains(e){return vS({network:this.network,mask:this.mask},e)}toString(){let e=xS(this.mask),t=e!==-1?String(e):ES(this.mask);return T8(this.network)+"/"+t}};function SS(r,e){return new La(r).contains(e)}function ym(r){try{let e=ie(r);return e.type==="ip6"?SS("2000::/3",e.host):!1}catch{return!1}}function AS(r){try{let e=ie(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 TS(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function Kd(r){try{let e=ie(r);switch(e.type){case"ip4":case"ip6":return TS(e.host);default:return!1}}catch{return!1}}function Jt(r){return A8(r)!==null}function co(r){return!!mm(r)}function wm(r){return!!gm(r)}var kS=Yt(IS(),1),EH=["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"],vH=EH.map(r=>new kS.Netmask(r));function N8(r){for(let e of vH)if(e.contains(r))return!0;return!1}function SH(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function AH(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 N8(o)}function TH(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function _H(r){let e=r.split(":"),t=e[e.length-1];return N8(t)}function CH(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 gl(r){if(co(r))return N8(r);if(SH(r))return AH(r);if(TH(r))return _H(r);if(wm(r))return CH(r)}function wt(r){try{let e=ie(r);switch(e.type){case"ip4":case"ip6":return gl(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}function O8(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 Oa(r=0){return new Uint8Array(r)}var IH=Math.pow(2,7),kH=Math.pow(2,14),RH=Math.pow(2,21),B8=Math.pow(2,28),M8=Math.pow(2,35),F8=Math.pow(2,42),U8=Math.pow(2,49),ut=128,fr=127;function yl(r){if(r<IH)return 1;if(r<kH)return 2;if(r<RH)return 3;if(r<B8)return 4;if(r<M8)return 5;if(r<F8)return 6;if(r<U8)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $8(r,e,t=0){switch(yl(r)){case 8:e[t++]=r&255|ut,r/=128;case 7:e[t++]=r&255|ut,r/=128;case 6:e[t++]=r&255|ut,r/=128;case 5:e[t++]=r&255|ut,r/=128;case 4:e[t++]=r&255|ut,r>>>=7;case 3:e[t++]=r&255|ut,r>>>=7;case 2:e[t++]=r&255|ut,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function PH(r,e){let t=r[e],n=0;if(n+=t&fr,t<ut||(t=r[e+1],n+=(t&fr)<<7,t<ut)||(t=r[e+2],n+=(t&fr)<<14,t<ut)||(t=r[e+3],n+=(t&fr)<<21,t<ut)||(t=r[e+4],n+=(t&fr)*B8,t<ut)||(t=r[e+5],n+=(t&fr)*M8,t<ut)||(t=r[e+6],n+=(t&fr)*F8,t<ut)||(t=r[e+7],n+=(t&fr)*U8,t<ut))return n;throw new RangeError("Could not decode varint")}function DH(r,e){let t=r.get(e),n=0;if(n+=t&fr,t<ut||(t=r.get(e+1),n+=(t&fr)<<7,t<ut)||(t=r.get(e+2),n+=(t&fr)<<14,t<ut)||(t=r.get(e+3),n+=(t&fr)<<21,t<ut)||(t=r.get(e+4),n+=(t&fr)*B8,t<ut)||(t=r.get(e+5),n+=(t&fr)*M8,t<ut)||(t=r.get(e+6),n+=(t&fr)*F8,t<ut)||(t=r.get(e+7),n+=(t&fr)*U8,t<ut))return n;throw new RangeError("Could not decode varint")}function H8(r,e=0){return r instanceof Uint8Array?PH(r,e):DH(r,e)}function NH(r){return r.buffer instanceof ArrayBuffer}function q8(r){return NH(r)?r:r.slice()}function OH(r){return r?.buffer instanceof ArrayBuffer}function V8(r){if(OH(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function wl(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=Oa(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return V8(t)}function PS(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var RS=PS("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),K8=PS("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=Oa(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),BH={utf8:RS,"utf-8":RS,hex:oe.base16,latin1:K8,ascii:K8,binary:K8,...oe},xm=BH;function bl(r,e="utf8"){let t=xm[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function ds(r,e="utf8"){let t=xm[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var er=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},gi=class extends Error{static name="ValidationError";name="ValidationError"},Em=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},vm=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function G8(r){return e=>ds(e,r)}function W8(r){return e=>bl(e,r)}function xl(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ba(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function DS(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=bl(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=Ba(n);return wl([t,o],t.length+o.length)}function LS(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=$t.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=Ba(n);return wl([t,o],t.length+o.length)}function j8(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=ds(e,"base32"),o=xl(t);return`${n}:${o}`}var Y8=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 er("Invalid byte value in IP address");e[n]=o}),e},NS=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=co(t[n]),s;i&&(s=Y8(t[n]),t[n]=ds(s.subarray(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,ds(s.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 i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let i=parseInt(t[n],16);if(isNaN(i)||i<0||i>65535)throw new er("Invalid byte value in IP address");o[e++]=i>>8&255,o[e++]=i&255}return o},OS=function(r){if(r.byteLength!==4)throw new er("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},BS=function(r){if(r.byteLength!==16)throw new er("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],i=r[n+1],s=`${o.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`;e.push(s)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new er(`Invalid IPv6 address "${t}"`)}};function MS(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new er(`Invalid IPv6 address "${r}"`)}}var z8=Object.values(oe).map(r=>r.decoder),MH=(function(){let r=z8[0].or(z8[1]);return z8.slice(2).forEach(e=>r=r.or(e)),r})();function FS(r){return MH.decode(r)}function US(r){return e=>r.encoder.encode(e)}function FH(r){if(parseInt(r).toString()!==r)throw new gi("Value must be an integer")}function UH(r){if(r<0)throw new gi("Value must be a positive integer, or zero")}function $H(r){return e=>{if(e>r)throw new gi(`Value must be smaller than or equal to ${r}`)}}function HH(...r){return e=>{for(let t of r)t(e)}}var zd=HH(FH,UH,$H(65535));var Vt=-1,X8=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 vm(`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)}))}},wi=new X8,tq=[{code:4,name:"ip4",size:32,valueToBytes:Y8,bytesToValue:OS,validate:r=>{if(!co(r))throw new gi(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ba,bytesToValue:xl,validate:zd},{code:273,name:"udp",size:16,valueToBytes:Ba,bytesToValue:xl,validate:zd},{code:33,name:"dccp",size:16,valueToBytes:Ba,bytesToValue:xl,validate:zd},{code:41,name:"ip6",size:128,valueToBytes:NS,bytesToValue:BS,stringToValue:MS,validate:r=>{if(!wm(r))throw new gi(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:Vt},{code:43,name:"ipcidr",size:8,bytesToValue:G8("base10"),valueToBytes:W8("base10")},{code:53,name:"dns",size:Vt},{code:54,name:"dns4",size:Vt},{code:55,name:"dns6",size:Vt},{code:56,name:"dnsaddr",size:Vt},{code:132,name:"sctp",size:16,valueToBytes:Ba,bytesToValue:xl,validate:zd},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Vt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:Vt,bytesToValue:G8("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?W8("base58btc")(r):F.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:j8,valueToBytes:DS},{code:445,name:"onion3",size:296,bytesToValue:j8,valueToBytes:LS},{code:446,name:"garlic64",size:Vt},{code:447,name:"garlic32",size:Vt},{code:448,name:"tls"},{code:449,name:"sni",size:Vt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Vt,bytesToValue:US(ud),valueToBytes:FS},{code:480,name:"http"},{code:481,name:"http-path",size:Vt,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:Vt}];tq.forEach(r=>{wi.addProtocol(r)});function $S(r){let e=[],t=0;for(;t<r.length;){let n=H8(r,t),o=wi.getProtocol(n),i=yl(n),s=rq(o,r,t+i),a=0;s>0&&o.size===Vt&&(a=yl(s));let c=i+a+s,l={code:n,name:o.name,bytes:q8(r.subarray(t,t+c))};if(s>0){let u=t+i+a,d=r.subarray(u,u+s);l.value=o.bytesToValue?.(d)??ds(d)}e.push(l),t+=c}return e}function HS(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=wi.getProtocol(n.code),i=yl(n.code),s,a=0,c=0;n.value!=null&&(s=o.valueToBytes?.(n.value)??bl(n.value),a=s.byteLength,o.size===Vt&&(c=yl(a)));let l=new Uint8Array(i+c+a),u=0;$8(n.code,l,u),u+=i,s!=null&&(o.size===Vt&&($8(a,l,u),u+=c),l.set(s,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return wl(t,e)}function qS(r){if(r.charAt(0)!=="/")throw new er('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let i=1;i<r.length;i++){let s=r.charAt(i);s!=="/"&&(t==="protocol"?o+=r.charAt(i):n+=r.charAt(i));let a=i===r.length-1;if(s==="/"||a){let c=wi.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 er(`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 er(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new er("Incomplete multiaddr");return e}function VS(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=wi.getProtocol(e.code);if(t==null)throw new er(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function rq(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:H8(e,t)}var nq=Symbol.for("nodejs.util.inspect.custom"),i5=Symbol.for("@multiformats/multiaddr");function oq(r){if(r==null&&(r="/"),$o(r))return r.getComponents();if(r instanceof Uint8Array)return $S(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),qS(r);if(Array.isArray(r))return r;throw new er("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Cm=class r{[i5]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=oq(e),t.validate!==!1&&iq(this)}get bytes(){return this.#r==null&&(this.#r=HS(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=VS(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 Em(`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 O8(this.bytes,e.bytes)}[nq](){return`Multiaddr(${this.toString()})`}};function iq(r){r.getComponents().forEach(e=>{let t=wi.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function $o(r){return!!r?.[i5]}function j(r){return new Cm(r)}var Oe=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),ne=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),KS=r=>({match:e=>r.match(e)===!1?e:!1}),we=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),hr=(...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 Be(...r){function e(o){if(o==null)return!1;let i=o.getComponents();for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function t(o){return e(o)!==!1}function n(o){let i=e(o);return i===!1?!1:i.length===0}return{matchers:r,matches:t,exactMatch:n}}var sq=ne(421),zS=Be(sq),km=ne(54),Rm=ne(55),Pm=ne(56),a5=ne(53),$ue=Be(km,we(ne(421))),Hue=Be(Rm,we(ne(421))),que=Be(Pm,we(ne(421))),Dm=Be(hr(a5,Pm,km,Rm),we(ne(421))),GS=Ae(ne(4),we(ne(43))),WS=Ae(we(ne(42)),ne(41),we(ne(43))),c5=hr(GS,WS),Al=hr(c5,a5,km,Rm,Pm),jS=Be(hr(c5,Ae(hr(a5,Pm,km,Rm),we(ne(421))))),l5=Be(GS),u5=Be(WS),YS=Be(c5),d5=Ae(Al,ne(6)),Qd=Ae(Al,ne(273)),bi=Be(Ae(d5,we(ne(421)))),Vue=Be(Qd),f5=Ae(Qd,Oe(460),we(ne(421))),Lm=Ae(Qd,Oe(461),we(ne(421))),aq=hr(f5,Lm),XS=Be(f5),Nm=Be(Lm),s5=hr(Al,d5,Qd,f5,Lm),QS=hr(Ae(s5,Oe(477),we(ne(421)))),fo=Be(QS),ZS=hr(Ae(s5,Oe(478),we(ne(421))),Ae(s5,Oe(448),we(ne(449)),Oe(477),we(ne(421)))),xi=Be(ZS),JS=Ae(Qd,Oe(280),we(ne(466)),we(ne(466)),we(ne(421))),Fa=Be(JS),eA=Ae(Lm,Oe(465),we(ne(466)),we(ne(466)),we(ne(421))),Zd=Be(eA),Im=hr(QS,ZS,Ae(d5,we(ne(421))),Ae(aq,we(ne(421))),Ae(Al,we(ne(421))),JS,eA,ne(421)),Tl=Be(Im),cq=Ae(we(Im),Oe(290),KS(Oe(281)),we(ne(421))),Kt=Be(cq),lq=hr(Ae(Im,Oe(290),Oe(281),we(ne(421))),Ae(Im,Oe(281),we(ne(421))),Ae(Oe(281),we(ne(421)))),Ua=Be(lq),uq=Ae(Al,hr(Ae(ne(6,"80")),Ae(ne(6),Oe(480)),Oe(480)),we(ne(481)),we(ne(421))),Om=Be(uq),dq=Ae(Al,hr(Ae(ne(6,"443")),Ae(ne(6,"443"),Oe(480)),Ae(ne(6),Oe(443)),Ae(ne(6),Oe(448),Oe(480)),Ae(Oe(448),Oe(480)),Oe(448),Oe(443)),we(ne(481)),we(ne(421))),Bm=Be(dq),fq=hr(Ae(ne(777),we(ne(421)))),Kue=Be(fq),hq=hr(Ae(ne(400),we(ne(421)))),zue=Be(hq);function tA(r,e){let t=bi.exactMatch(r),n=bi.exactMatch(e);if(t&&!n)return-1;if(!t&&n)return 1;let o=xi.exactMatch(r),i=xi.exactMatch(e);if(o&&!i)return-1;if(!o&&i)return 1;let s=fo.exactMatch(r),a=fo.exactMatch(e);if(s&&!a)return-1;if(!s&&a)return 1;let c=Ua.exactMatch(r),l=Ua.exactMatch(e);if(c&&!l)return-1;if(!c&&l)return 1;let u=Fa.exactMatch(r),d=Fa.exactMatch(e);if(u&&!d)return-1;if(!u&&d)return 1;let f=Zd.exactMatch(r),h=Zd.exactMatch(e);return f&&!h?-1:!f&&h?1:0}function rA(r,e){let t=Kd(r),n=Kd(e);return t&&!n?1:!t&&n?-1:0}function nA(r,e){let t=wt(r),n=wt(e);return t&&!n?1:!t&&n?-1:0}function oA(r,e){let t=Kt.exactMatch(r),n=Kt.exactMatch(e);return t&&!n?1:!t&&n?-1:0}function me(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Mm=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}},_l=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Mm(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 Mm(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 h5=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Nt(r={}){return pq(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 pq(r,e){e=e??{};let t=e.onEnd,n=new _l,o,i,s,a=me(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((g,m)=>{i=b=>{i=null,n.push(b);try{g(r(n))}catch(T){m(T)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=me()})}},l=g=>i!=null?i(g):(n.push(g),o),u=g=>(n=new _l,i!=null?i({error:g}):(n.push({error:g}),o)),d=g=>{if(s)return o;if(e?.objectMode!==!0&&g?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:g})},f=g=>s?o:(s=!0,g!=null?u(g):l({done:!0})),h=()=>(n=new _l,f(),{done:!0}),p=g=>(f(g),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:p,push:d,end:f,get readableLength(){return n.size},onEmpty:async g=>{let m=g?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let b,T;m!=null&&(b=new Promise((R,D)=>{T=()=>{D(new h5)},m.addEventListener("abort",T)}));try{await Promise.race([a.promise,b])}finally{T!=null&&m!=null&&m?.removeEventListener("abort",T)}}},t==null)return o;let y=o;return o={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(g){return y.throw(g),t!=null&&(t(g),t=void 0),{done:!0}},return(){return y.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(g){return y.end(g),t!=null&&(t(g),t=void 0),o},get readableLength(){return y.readableLength},onEmpty:g=>y.onEmpty(g)},o}var p5=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},iA=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function Jd(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout},signal:s}=e,a,c,u=new Promise((d,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(s?.aborted){f(iA(s));return}if(s&&(c=()=>{f(iA(s))},s.addEventListener("abort",c,{once:!0})),r.then(d,f),t===Number.POSITIVE_INFINITY)return;let h=new p5;a=i.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${t} milliseconds`,f(h))},t)}).finally(()=>{u.clear(),c&&s&&s.removeEventListener("abort",c)});return u.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},u}var mq=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 gq(r,e,t){let n,o=new Promise((i,s)=>{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}=mq(r),d=async(...h)=>{let p=t.multiArgs?h:h[0];if(t.filter)try{if(!await t.filter(p))return}catch(y){n(),s(y);return}c.push(p),t.count===c.length&&(n(),i(c))},f=(...h)=>{n(),s(t.rejectionMultiArgs?h:h[0])};n=()=>{for(let h of a)u(h,d);for(let h of t.rejectionEvents)a.includes(h)||u(h,f)};for(let h of a)l(h,d);for(let h of t.rejectionEvents)a.includes(h)||l(h,f);t.signal&&t.signal.addEventListener("abort",()=>{f(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(o.cancel=n,typeof t.timeout=="number"){let i=Jd(o,{milliseconds:t.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function ke(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=gq(r,e,t),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function Ei(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 Fm=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}},Um=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},$a=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},$m=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Hm=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function yq(r){return r.reason}async function Me(r,e,t){if(e==null)return r;let n=t?.translateError??yq;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((i,s)=>{o=()=>{s(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var qm=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=me(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Tr)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function wq(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Vm=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=wq(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,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 Tr),this.cleanup())}async join(e){let t=new qm(e);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 Me(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),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 vt=class extends se{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=Ei(this.emitEmpty.bind(this),1),this.emitIdle=Ei(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 Um;let n=new Vm(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{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:i}}),i});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Tr)}),this.clear()}async onEmpty(e){this.size!==0&&await ke(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await ke(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ke(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=Nt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new Tr("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var bq=Math.pow(2,20)*4,hs=class extends se{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??bq,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new G,this.writeBuffer=new G,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(o){this.log.error("processSendQueue threw - %e",o)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=o=>{this.onDrainPromise?.reject(o.error??new Hm)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Me(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Nt(),t=i=>{e.push(i.data)};this.addEventListener("message",t);let n=i=>{e.end(i.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Io(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new kp(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Io("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Io("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Io(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Io(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new Hc;this.dispatchEvent(new Rp(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new Yi))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let i=this.writeBuffer.sublist(0,o),s=new G(i);this.writeBuffer.consume(i.byteLength);let a;try{a=this.sendData(i)}catch(c){throw this.writeBuffer.prepend(s),this.abort(c),c}if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==s.byteLength&&(s.consume(a.sentBytes),this.writeBuffer.prepend(s)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Ip(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new td(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new td(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var ps=class extends hs{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await ke(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await ke(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function ms(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var gs=class extends se{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let n=s=>{try{this.onData(s.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(s=>{s.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let i=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",i)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await Me(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new Xn;let t=this.onCreateStream({...this.streamOptions,...e});return ms(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new $m(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=n=>{let o=this.streams.findIndex(i=>i===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var ys=class extends hs{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await ke(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await ke(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};var Cl=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,i=n*o;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+o*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*o}else this.movingAverage=e;this.previousTime=t}};var xq=1.2,Eq=2,vq=5e3,Sq=6e4,Aq=5e3,ho=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??Aq;this.success=new Cl(t),this.failure=new Cl(t),this.next=new Cl(t),this.failureMultiplier=e.failureMultiplier??Eq,this.timeoutMultiplier=e.timeoutMultiplier??xq,this.minTimeout=e.minTimeout??vq,this.maxTimeout=e.maxTimeout??Sq,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=ae([e.signal,n]);return o.start=Date.now(),o.timeout=t,o}cleanUp(e){e.clear();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 m5=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=me(),this.haveNext=me()}[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=me(),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=me(),await Me(this.readNext.promise,t?.signal,t)}};function sA(){return new m5}function Tq(r){return r[Symbol.asyncIterator]!=null}async function _q(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*Cq(r){let e=new AbortController,t=sA();_q(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Iq(r){for(let e of r)yield*e}function kq(...r){let e=[];for(let t of r)Tq(t)||e.push(t);return e.length===r.length?Iq(e):Cq(r)}var Rr=kq;function on(r,...e){if(r==null)throw new Error("Empty pipeline");if(g5(r)){let n=r;r=()=>n.source}else if(cA(r)||aA(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&g5(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)g5(t[n])&&(t[n]=Pq(t[n]));return Rq(...t)}var Rq=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},aA=r=>r?.[Symbol.asyncIterator]!=null,cA=r=>r?.[Symbol.iterator]!=null,g5=r=>r==null?!1:r.sink!=null&&r.source!=null,Pq=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Nt({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(aA(i))o=async function*(){yield*i,n.end()};else if(cA(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Rr(n,o())}return r.source};var Dq=4194304,Km=class extends Error{static name="UnwrappedError";name="UnwrappedError"},ef=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},w5=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},b5=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Lq(r){return typeof r?.closeRead=="function"}function Nq(r){return typeof r?.close=="function"}function y5(r){return Lq(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Nq(r)?r.status!=="open":!1}function Oq(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function zm(r,e){let t=e?.maxBufferSize??Dq,n=new G,o,i=!1;if(!Oq(r))throw new E("Argument should be a Stream or a Multiaddr");let s=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}o?.resolve()};r.addEventListener("message",s);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(i===!0)throw new Km("Stream was unwrapped");if(y5(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new $a(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await Me(o.promise,u?.signal),y5(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let f=u?.bytes??n.byteLength;if(n.byteLength<f){if(y5(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,f),new $a(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return l.read(u)}let h=n.sublist(0,f);return n.consume(f),h},async write(u,d){if(i===!0)throw new Km("Stream was unwrapped");r.send(u)||await ke(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return i||(i=!0,r.removeEventListener("message",s),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return l}function ws(r,e={}){let t=zm(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ye(e.maxDataLength));let n=e?.lengthDecoder??No,o=e?.lengthEncoder??ur;return{async read(s){let a=-1,c=new G;for(;;){let u=await t.read({...s,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new ef("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new b5(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new w5(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...s,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new $a(`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 $a(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(s,a){await t.write(new G(o(s.byteLength),s),a)},async writeV(s,a){let c=new G(...s.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function Xe(r,e){let t=ws(r,e),n={read:async(o,i)=>{let s=await t.read(i);return o.decode(s)},write:async(o,i,s)=>{await t.write(i.encode(o),s)},writeV:async(o,i,s)=>{await t.writeV(o.map(a=>i.encode(a)),s)},pb:o=>({read:async i=>n.read(o,i),write:async(i,s)=>n.write(i,o,s),writeV:async(i,s)=>n.writeV(i,o,s),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var Bq=1024*1024*4,Mq=1024*1024*4,Gm=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new G,this.maxBufferSize=e.maxBufferSize??Bq,this.maxDataLength=e.maxDataLength??Mq,this.lengthDecoder=e.lengthDecoder??No,this.encodingLength=e.encodingLength??ye}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new E(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let t;try{t=this.lengthDecoder(this.buffer)}catch(i){if(i instanceof RangeError)break;throw i}if(t<0||t>this.maxDataLength)throw new ef("Invalid message length");let n=this.encodingLength(t),o=n+t;if(this.buffer.byteLength>=o){let i=this.buffer.sublist(n,o);this.buffer.consume(o),i.byteLength>0&&(yield i)}else break}}};var Fq=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function x5(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(r instanceof Uint8Array)return"Uint8Array";if(r.constructor===Object)return"Object";let t=Uq(r);return t||"Object"}function Uq(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(Fq.includes(e))return e}var w=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}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};w.uint=new w(0,"uint",!0);w.negint=new w(1,"negint",!0);w.bytes=new w(2,"bytes",!0);w.string=new w(3,"string",!0);w.array=new w(4,"array",!1);w.map=new w(5,"map",!1);w.tag=new w(6,"tag",!1);w.float=new w(7,"float",!0);w.false=new w(7,"false",!0);w.true=new w(7,"true",!0);w.null=new w(7,"null",!0);w.undefined=new w(7,"undefined",!0);w.break=new w(7,"break",!0);var N=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 tf=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",$q=new TextEncoder;function Wm(r){return tf&&globalThis.Buffer.isBuffer(r)}function Ha(r){return r instanceof Uint8Array?Wm(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var Hq=24,qq=200,Il=tf?r=>r.length>=Hq?globalThis.Buffer.from(r):lA(r):r=>r.length>=qq?$q.encode(r):lA(r),Ho=r=>Uint8Array.from(r),dA=tf?(r,e,t)=>Wm(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),fA=tf?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Ha(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},hA=tf?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function jm(r,e){if(Wm(r)&&Wm(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 lA(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):(o>=55296&&o<=57343&&(o=65533),e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}var uA=4096;function pA(r){let e=r.length;if(e<=uA)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=uA));return t}var Vq=256,rf=class{constructor(e=Vq){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=hA(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=dA(n,0,this.cursor)}else t=fA(this.chunks,this.cursor);return e&&this.reset(),t}},Ym=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};var W="CBOR decode error:",qo="CBOR encode error:",nf=[];nf[23]=1;nf[24]=2;nf[25]=3;nf[26]=5;nf[27]=9;function vi(r,e,t){if(r.length-e<t)throw new Error(`${W} not enough data for type`)}var zt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function sn(r,e,t){vi(r,e,1);let n=r[e];if(t.strict===!0&&n<zt[0])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);return n}function an(r,e,t){vi(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<zt[1])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);return n}function cn(r,e,t){vi(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<zt[2])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);return n}function ln(r,e,t){vi(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<zt[3])throw new Error(`${W} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${W} integers outside of the safe integer range are not supported`)}function mA(r,e,t,n){return new N(w.uint,sn(r,e+1,n),2)}function gA(r,e,t,n){return new N(w.uint,an(r,e+1,n),3)}function yA(r,e,t,n){return new N(w.uint,cn(r,e+1,n),5)}function wA(r,e,t,n){return new N(w.uint,ln(r,e+1,n),9)}function Mn(r,e){return Ze(r,0,e.value)}function Ze(r,e,t){if(t<zt[0]){let n=Number(t);r.push([e|n])}else if(t<zt[1]){let n=Number(t);r.push([e|24,n])}else if(t<zt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<zt[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<zt[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${W} encountered BigInt larger than allowable range`)}}Mn.encodedSize=function(e){return Ze.encodedSize(e.value)};Ze.encodedSize=function(e){return e<zt[0]?1:e<zt[1]?2:e<zt[2]?3:e<zt[3]?5:9};Mn.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function bA(r,e,t,n){return new N(w.negint,-1-sn(r,e+1,n),2)}function xA(r,e,t,n){return new N(w.negint,-1-an(r,e+1,n),3)}function EA(r,e,t,n){return new N(w.negint,-1-cn(r,e+1,n),5)}var E5=BigInt(-1),vA=BigInt(1);function SA(r,e,t,n){let o=ln(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new N(w.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${W} integers outside of the safe integer range are not supported`);return new N(w.negint,E5-BigInt(o),9)}function Xm(r,e){let t=e.value,n=typeof t=="bigint"?t*E5-vA:t*-1-1;Ze(r,e.type.majorEncoded,n)}Xm.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*E5-vA:t*-1-1;return n<zt[0]?1:n<zt[1]?2:n<zt[2]?3:n<zt[3]?5:9};Xm.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function of(r,e,t,n){vi(r,e,t+n);let o=r.slice(e+t,e+t+n);return new N(w.bytes,o,t+n)}function AA(r,e,t,n){return of(r,e,1,t)}function TA(r,e,t,n){return of(r,e,2,sn(r,e+1,n))}function _A(r,e,t,n){return of(r,e,3,an(r,e+1,n))}function CA(r,e,t,n){return of(r,e,5,cn(r,e+1,n))}function IA(r,e,t,n){let o=ln(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer bytes lengths not supported`);return of(r,e,9,o)}function Qm(r){return r.encodedBytes===void 0&&(r.encodedBytes=w.equals(r.type,w.string)?Il(r.value):r.value),r.encodedBytes}function kl(r,e){let t=Qm(e);Ze(r,e.type.majorEncoded,t.length),r.push(t)}kl.encodedSize=function(e){let t=Qm(e);return Ze.encodedSize(t.length)+t.length};kl.compareTokens=function(e,t){return zq(Qm(e),Qm(t))};function zq(r,e){return r.length<e.length?-1:r.length>e.length?1:jm(r,e)}var kA=new TextDecoder,Wq=32;function jq(r,e,t){if(t-e<Wq){let o="";for(let i=e;i<t;i++){let s=r[i];if(s&128)return kA.decode(r.subarray(e,t));o+=String.fromCharCode(s)}return o}return kA.decode(r.subarray(e,t))}function sf(r,e,t,n,o){let i=t+n;vi(r,e,i);let s=new N(w.string,jq(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=r.slice(e+t,e+i)),s}function RA(r,e,t,n){return sf(r,e,1,t,n)}function PA(r,e,t,n){return sf(r,e,2,sn(r,e+1,n),n)}function DA(r,e,t,n){return sf(r,e,3,an(r,e+1,n),n)}function LA(r,e,t,n){return sf(r,e,5,cn(r,e+1,n),n)}function NA(r,e,t,n){let o=ln(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer string lengths not supported`);return sf(r,e,9,o,n)}var OA=kl;function Rl(r,e,t,n){return new N(w.array,n,t)}function BA(r,e,t,n){return Rl(r,e,1,t)}function MA(r,e,t,n){return Rl(r,e,2,sn(r,e+1,n))}function FA(r,e,t,n){return Rl(r,e,3,an(r,e+1,n))}function UA(r,e,t,n){return Rl(r,e,5,cn(r,e+1,n))}function $A(r,e,t,n){let o=ln(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer array lengths not supported`);return Rl(r,e,9,o)}function HA(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${W} indefinite length items not allowed`);return Rl(r,e,1,1/0)}function Zm(r,e){Ze(r,w.array.majorEncoded,e.value)}Zm.compareTokens=Mn.compareTokens;Zm.encodedSize=function(e){return Ze.encodedSize(e.value)};function Pl(r,e,t,n){return new N(w.map,n,t)}function qA(r,e,t,n){return Pl(r,e,1,t)}function VA(r,e,t,n){return Pl(r,e,2,sn(r,e+1,n))}function KA(r,e,t,n){return Pl(r,e,3,an(r,e+1,n))}function zA(r,e,t,n){return Pl(r,e,5,cn(r,e+1,n))}function GA(r,e,t,n){let o=ln(r,e+1,n);if(typeof o=="bigint")throw new Error(`${W} 64-bit integer map lengths not supported`);return Pl(r,e,9,o)}function WA(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${W} indefinite length items not allowed`);return Pl(r,e,1,1/0)}function Jm(r,e){Ze(r,w.map.majorEncoded,e.value)}Jm.compareTokens=Mn.compareTokens;Jm.encodedSize=function(e){return Ze.encodedSize(e.value)};function jA(r,e,t,n){return new N(w.tag,t,1)}function YA(r,e,t,n){return new N(w.tag,sn(r,e+1,n),2)}function XA(r,e,t,n){return new N(w.tag,an(r,e+1,n),3)}function QA(r,e,t,n){return new N(w.tag,cn(r,e+1,n),5)}function ZA(r,e,t,n){return new N(w.tag,ln(r,e+1,n),9)}function e1(r,e){Ze(r,w.tag.majorEncoded,e.value)}e1.compareTokens=Mn.compareTokens;e1.encodedSize=function(e){return Ze.encodedSize(e.value)};var v5=20,S5=21,A5=22,T5=23;function JA(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${W} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new N(w.null,null,1):new N(w.undefined,void 0,1)}function eT(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${W} indefinite length items not allowed`);return new N(w.break,void 0,1)}function _5(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${W} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${W} Infinity values are not supported`)}return new N(w.float,r,e)}function tT(r,e,t,n){return _5(C5(r,e+1),3,n)}function rT(r,e,t,n){return _5(I5(r,e+1),5,n)}function nT(r,e,t,n){return _5(aT(r,e+1),9,n)}function af(r,e,t){let n=e.value;if(n===!1)r.push([w.float.majorEncoded|v5]);else if(n===!0)r.push([w.float.majorEncoded|S5]);else if(n===null)r.push([w.float.majorEncoded|A5]);else if(n===void 0)r.push([w.float.majorEncoded|T5]);else{let o,i=!1;(!t||t.float64!==!0)&&(iT(n),o=C5(po,1),n===o||Number.isNaN(n)?(po[0]=249,r.push(po.slice(0,3)),i=!0):(sT(n),o=I5(po,1),n===o&&(po[0]=250,r.push(po.slice(0,5)),i=!0))),i||(Jq(n),o=aT(po,1),po[0]=251,r.push(po.slice(0,9)))}}af.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){iT(n);let o=C5(po,1);if(n===o||Number.isNaN(n))return 3;if(sT(n),o=I5(po,1),n===o)return 5}return 9};var oT=new ArrayBuffer(9),Fn=new DataView(oT,1),po=new Uint8Array(oT,0);function iT(r){if(r===1/0)Fn.setUint16(0,31744,!1);else if(r===-1/0)Fn.setUint16(0,64512,!1);else if(Number.isNaN(r))Fn.setUint16(0,32256,!1);else{Fn.setFloat32(0,r);let e=Fn.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Fn.setUint16(0,31744,!1);else if(t===0)Fn.setUint16(0,(e&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Fn.setUint16(0,0):o<-14?Fn.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Fn.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function C5(r,e){if(r.length-e<2)throw new Error(`${W} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function sT(r){Fn.setFloat32(0,r,!1)}function I5(r,e){if(r.length-e<4)throw new Error(`${W} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function Jq(r){Fn.setFloat64(0,r,!1)}function aT(r,e){if(r.length-e<8)throw new Error(`${W} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}af.compareTokens=Mn.compareTokens;function Re(r,e,t){throw new Error(`${W} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function t1(r){return()=>{throw new Error(`${W} ${r}`)}}var z=[];for(let r=0;r<=23;r++)z[r]=Re;z[24]=mA;z[25]=gA;z[26]=yA;z[27]=wA;z[28]=Re;z[29]=Re;z[30]=Re;z[31]=Re;for(let r=32;r<=55;r++)z[r]=Re;z[56]=bA;z[57]=xA;z[58]=EA;z[59]=SA;z[60]=Re;z[61]=Re;z[62]=Re;z[63]=Re;for(let r=64;r<=87;r++)z[r]=AA;z[88]=TA;z[89]=_A;z[90]=CA;z[91]=IA;z[92]=Re;z[93]=Re;z[94]=Re;z[95]=t1("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)z[r]=RA;z[120]=PA;z[121]=DA;z[122]=LA;z[123]=NA;z[124]=Re;z[125]=Re;z[126]=Re;z[127]=t1("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)z[r]=BA;z[152]=MA;z[153]=FA;z[154]=UA;z[155]=$A;z[156]=Re;z[157]=Re;z[158]=Re;z[159]=HA;for(let r=160;r<=183;r++)z[r]=qA;z[184]=VA;z[185]=KA;z[186]=zA;z[187]=GA;z[188]=Re;z[189]=Re;z[190]=Re;z[191]=WA;for(let r=192;r<=215;r++)z[r]=jA;z[216]=YA;z[217]=XA;z[218]=QA;z[219]=ZA;z[220]=Re;z[221]=Re;z[222]=Re;z[223]=Re;for(let r=224;r<=243;r++)z[r]=t1("simple values are not supported");z[244]=Re;z[245]=Re;z[246]=Re;z[247]=JA;z[248]=t1("simple values are not supported");z[249]=tT;z[250]=rT;z[251]=nT;z[252]=Re;z[253]=Re;z[254]=Re;z[255]=eT;var mo=[];for(let r=0;r<24;r++)mo[r]=new N(w.uint,r,1);for(let r=-1;r>=-24;r--)mo[31-r]=new N(w.negint,r,1);mo[64]=new N(w.bytes,new Uint8Array(0),1);mo[96]=new N(w.string,"",1);mo[128]=new N(w.array,0,1);mo[160]=new N(w.map,0,1);mo[244]=new N(w.false,!1,1);mo[245]=new N(w.true,!0,1);mo[246]=new N(w.null,null,1);function r1(r){switch(r.type){case w.false:return Ho([244]);case w.true:return Ho([245]);case w.null:return Ho([246]);case w.bytes:return r.value.length?void 0:Ho([64]);case w.string:return r.value===""?Ho([96]):void 0;case w.array:return r.value===0?Ho([128]):void 0;case w.map:return r.value===0?Ho([160]):void 0;case w.uint:return r.value<24?Ho([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return Ho([31-Number(r.value)])}}var tV={float64:!1,mapSorter:nV,quickEncodeToken:r1},fT=Object.freeze({float64:!0,mapSorter:oV,quickEncodeToken:r1});function k5(){let r=[];return r[w.uint.major]=Mn,r[w.negint.major]=Xm,r[w.bytes.major]=kl,r[w.string.major]=OA,r[w.array.major]=Zm,r[w.map.major]=Jm,r[w.tag.major]=e1,r[w.float.major]=af,r}var Dl=k5(),n1=new rf,lf=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(`${qo} object contains circular references`);return new r(t,e)}},bs={null:new N(w.null,null),undefined:new N(w.undefined,void 0),true:new N(w.true,!0),false:new N(w.false,!1),emptyArray:new N(w.array,0),emptyMap:new N(w.map,0)},Vo={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new N(w.float,r):r>=0?new N(w.uint,r):new N(w.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new N(w.uint,r):new N(w.negint,r)},Uint8Array(r,e,t,n){return new N(w.bytes,r)},string(r,e,t,n){return new N(w.string,r)},boolean(r,e,t,n){return r?bs.true:bs.false},null(r,e,t,n){return bs.null},undefined(r,e,t,n){return bs.undefined},ArrayBuffer(r,e,t,n){return new N(w.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new N(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[bs.emptyArray,new N(w.break)]:bs.emptyArray;n=lf.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Va(s,t,n);return t.addBreakTokens?[new N(w.array,r.length),o,new N(w.break)]:[new N(w.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length,a;if(s){a=new Array(s),n=lf.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let u of i){let d=o?r.get(u):r[u];c&&d===void 0||(a[l++]=[Va(u,t,n),Va(d,t,n)])}l<s&&(a.length=l)}return a?.length?(rV(a,t),t.addBreakTokens?[new N(w.map,a.length),a,new N(w.break)]:[new N(w.map,a.length),a]):t.addBreakTokens===!0?[bs.emptyMap,new N(w.break)]:bs.emptyMap},Tagged(r,e,t,n){return[new N(w.tag,r.tag),Va(r.value,t,n)]}};Vo.Map=Vo.Object;Vo.Buffer=Vo.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Vo[`${r}Array`]=Vo.DataView;function Va(r,e={},t){let n=x5(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Vo[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=Vo[n];if(!i)throw new Error(`${qo} unsupported type: ${n}`);return i(r,n,e,t)}function rV(r,e){e.mapSorter&&r.sort(e.mapSorter)}function nV(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=Dl[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function oV(r,e){if(r[0]instanceof N&&e[0]instanceof N){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=cT(t.value)),n._keyBytes||(n._keyBytes=cT(n.value)),jm(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function cT(r){return o1(r,Dl,fT)}function cf(r,e,t,n){if(Array.isArray(e))for(let o of e)cf(r,o,t,n);else t[e.type.major](r,e,n)}var lT=w.uint.majorEncoded,uT=w.negint.majorEncoded,iV=w.bytes.majorEncoded,sV=w.string.majorEncoded,dT=w.array.majorEncoded,aV=w.float.majorEncoded|v5,cV=w.float.majorEncoded|S5,lV=w.float.majorEncoded|A5,uV=w.float.majorEncoded|T5,dV=BigInt(-1),fV=BigInt(1);function hV(r){return r.addBreakTokens!==!0}function hT(r,e,t,n){let o=x5(e),i=t.typeEncoders&&t.typeEncoders[o];if(i){let s=i(e,o,t,n);if(s!=null){cf(r,s,Dl,t);return}}switch(o){case"null":r.push([lV]);return;case"undefined":r.push([uV]);return;case"boolean":r.push([e?cV:aV]);return;case"number":!Number.isInteger(e)||!Number.isSafeInteger(e)?af(r,new N(w.float,e),t):e>=0?Ze(r,lT,e):Ze(r,uT,e*-1-1);return;case"bigint":e>=BigInt(0)?Ze(r,lT,e):Ze(r,uT,e*dV-fV);return;case"string":{let s=Il(e);Ze(r,sV,s.length),r.push(s);return}case"Uint8Array":Ze(r,iV,e.length),r.push(e);return;case"Array":if(!e.length){r.push([dT]);return}n=lf.createCheck(n,e),Ze(r,dT,e.length);for(let s of e)hT(r,s,t,n);return;case"Object":case"Map":{let s=Vo.Object(e,o,t,n);cf(r,s,Dl,t)}return;default:{let s=Vo[o];if(!s)throw new Error(`${qo} unsupported type: ${o}`);let a=s(e,o,t,n);cf(r,a,Dl,t)}}}function o1(r,e,t,n){let o=n instanceof Uint8Array,i=o?new Ym(n):n1,s=Va(r,t);if(!Array.isArray(s)&&t.quickEncodeToken){let a=t.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=e[s.type.major];if(c.encodedSize){let l=c.encodedSize(s,t);if(o||(i=new rf(l)),c(i,s,t),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():Ha(i.chunks[0])}}return i.reset(),cf(i,s,e,t),i.toBytes(!0)}function Ko(r,e){return e=Object.assign({},tV,e),hV(e)?(n1.reset(),hT(n1,r,e,void 0),n1.toBytes(!0)):o1(r,Dl,e)}var pV={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},i1=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=mo[e];if(t===void 0){let n=z[e];if(!n)throw new Error(`${W} 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}},xs=Symbol.for("DONE"),Ll=Symbol.for("BREAK");function mV(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=Es(e,t);if(i===Ll){if(r.value===1/0)break;throw new Error(`${W} got unexpected break to lengthed array`)}if(i===xs)throw new Error(`${W} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function gV(r,e,t){let n=t.useMaps===!0,o=t.rejectDuplicateMapKeys===!0,i=n?void 0:{},s=n?new Map:void 0;for(let a=0;a<r.value;a++){let c=Es(e,t);if(c===Ll){if(r.value===1/0)break;throw new Error(`${W} got unexpected break to lengthed map`)}if(c===xs)throw new Error(`${W} found map but not enough entries (got ${a} [no key], expected ${r.value})`);if(!n&&typeof c!="string")throw new Error(`${W} non-string keys not supported (got ${typeof c})`);if(o&&(n&&s.has(c)||!n&&Object.hasOwn(i,c)))throw new Error(`${W} found repeat map key "${c}"`);let l=Es(e,t);if(l===xs)throw new Error(`${W} found map but not enough entries (got ${a} [no value], expected ${r.value})`);n?s.set(c,l):i[c]=l}return n?s:i}function*yV(r,e,t){for(let n=0;n<r.value;n++){let o=Es(e,t);if(o===Ll){if(r.value===1/0)break;throw new Error(`${W} got unexpected break to lengthed map`)}if(o===xs)throw new Error(`${W} found map but not enough entries (got ${n} [no key], expected ${r.value})`);let i=Es(e,t);if(i===xs)throw new Error(`${W} found map but not enough entries (got ${n} [no value], expected ${r.value})`);yield[o,i]}}function wV(r,e){let t=!1,n=function(){if(t)throw new Error(`${W} tag decode() may only be called once`);t=!0;let o=Es(r,e);if(o===xs)throw new Error(`${W} tag content missing`);if(o===Ll)throw new Error(`${W} got unexpected break in tag content`);return o};return n.entries=function(){if(t)throw new Error(`${W} tag decode() may only be called once`);t=!0;let o=r.next();if(!w.equals(o.type,w.map))throw new Error(`${W} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of yV(o,r,e))i.push(s);return i},Object.defineProperty(n,"_called",{get(){return t},enumerable:!1}),n}function Es(r,e){if(r.done())return xs;let t=r.next();if(w.equals(t.type,w.break))return Ll;if(t.type.terminal)return t.value;if(w.equals(t.type,w.array))return mV(t,r,e);if(w.equals(t.type,w.map))return gV(t,r,e);if(w.equals(t.type,w.tag)){if(e.tags&&typeof e.tags[t.value]=="function"){let n=wV(r,e),o=e.tags[t.value](n);if(!n._called)throw new Error(`${W} tag decoder must call decode() or entries()`);return o}throw new Error(`${W} tag not supported (${t.value})`)}throw new Error("unsupported")}function R5(r,e){if(!(r instanceof Uint8Array))throw new Error(`${W} data to decode must be a Uint8Array`);e=Object.assign({},pV,e);let t=Ha(r),n=e.tokenizer||new i1(t,e),o=Es(n,e);if(o===xs)throw new Error(`${W} did not find any content to decode`);if(o===Ll)throw new Error(`${W} got unexpected break`);return[o,r.subarray(n.pos())]}function Pr(r,e){let[t,n]=R5(r,e);if(n.length>0)throw new Error(`${W} too many terminals, data makes no sense`);return t}var s1=class r{constructor(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=e,this.value=t}static decoder(e){return t=>new r(e,t())}static preserve(...e){let t={};for(let n of e)t[n]=r.decoder(n);return t}};Object.defineProperty(s1.prototype,Symbol.toStringTag,{value:"Tagged"});var c1=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Nl=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},l1=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},uf=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function u1(r){return r[Symbol.asyncIterator]!=null}function pT(r,e){if(r.byteLength>e)throw new Nl("Message length too long")}var f1=r=>{let e=ye(r),t=nt(e);return ur(r,t),f1.bytes=e,t};f1.bytes=0;function Si(r,e){e=e??{};let t=e.lengthEncoder??f1,n=e?.maxDataLength??4194304;function*o(i){pT(i,n);let s=t(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return u1(r)?(async function*(){for await(let i of r)yield*o(i)})():(function*(){for(let i of r)yield*o(i)})()}Si.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??f1,n=e?.maxDataLength??4194304;return pT(r,n),new G(t(r.byteLength),r)};var Ka;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ka||(Ka={}));var P5=r=>{let e=No(r);return P5.bytes=ye(e),e};P5.bytes=0;function za(r,e){let t=new G,n=Ka.LENGTH,o=-1,i=e?.lengthDecoder??P5,s=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===Ka.LENGTH)try{if(o=i(t),o<0)throw new c1("Invalid message length");if(o>a)throw new Nl("Message length too long");let l=i.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=Ka.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>s)throw new l1("Message length length too long");break}throw l}if(n===Ka.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=Ka.LENGTH}}}return u1(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new uf("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new uf("Unexpected end of input")})()}za.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:i,value:s}=await r.next(t);if(i===!0)return;s!=null&&(yield s)}catch(i){if(i.code==="ERR_UNDER_READ")return{done:!0,value:null};throw i}finally{t=1}})();return za(n,{...e??{},onLength:i=>{t=i}})};function h1(r,e){if(typeof r=="string")return xV(r);if(typeof r=="number")return SV(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function xV(r){if(typeof r!="string"||r.length===0||r.length>100)throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let 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),i=n.toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw new Error(`Unknown unit "${i}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function EV(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 vV(r){let e=Math.abs(r);return e>=315576e5?Ga(r,e,315576e5,"year"):e>=26298e5?Ga(r,e,26298e5,"month"):e>=6048e5?Ga(r,e,6048e5,"week"):e>=864e5?Ga(r,e,864e5,"day"):e>=36e5?Ga(r,e,36e5,"hour"):e>=6e4?Ga(r,e,6e4,"minute"):e>=1e3?Ga(r,e,1e3,"second"):`${r} ms`}function SV(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return e?.long?vV(r):EV(r)}function Ga(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function D5(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=s,t.humanize=h1,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let f=0;f<u.length;f++)d=(d<<5)-d+u.charCodeAt(f),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u,d){let f,h=null,p,y;function g(...m){if(!g.enabled)return;let b=g,T=Number(new Date),R=T-(f||T);b.diff=R,b.prev=f,b.curr=T,f=T,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let D=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(U,C)=>{if(U==="%%")return"%";D++;let L=t.formatters[C];if(typeof L=="function"){let H=m[D];U=L.call(b,H),m.splice(D,1),D--}return U}),t.formatArgs.call(b,m),d?.onLog!=null&&d.onLog(...m),(b.log||t.log).apply(b,m)}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:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,y=t.enabled(u)),y),set:m=>{h=m}}),typeof t.init=="function"&&t.init(g),g}function n(u,d){let f=t(this.namespace+(typeof d>"u"?":":d)+u);return f.log=this.log,f}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,f=(typeof u=="string"?u:"").split(/[\s,]+/),h=f.length;for(d=0;d<h;d++)f[d]&&(u=f[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function i(){let u=[...t.names.map(a),...t.skips.map(a).map(d=>"-"+d)].join(",");return t.enable(""),u}function s(u){if(u[u.length-1]==="*")return!0;let d,f;for(d=0,f=t.skips.length;d<f;d++)if(t.skips[d].test(u))return!1;for(d=0,f=t.names.length;d<f;d++)if(t.names[d].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var p1=RV(),AV=["#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 TV(){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 _V(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+h1(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 CV=console.debug??console.log??(()=>{});function IV(r){try{r?p1?.setItem("debug",r):p1?.removeItem("debug")}catch{}}function kV(){let r;try{r=p1?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function RV(){try{return localStorage}catch{}}function PV(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var gT=D5({formatArgs:_V,save:IV,load:kV,useColors:TV,setupFormatters:PV,colors:AV,storage:p1,log:CV});var $r=gT;$r.formatters.b=r=>r==null?"undefined":Ce.baseEncode(r);$r.formatters.t=r=>r==null?"undefined":$t.baseEncode(r);$r.formatters.m=r=>r==null?"undefined":Tt.baseEncode(r);$r.formatters.p=r=>r==null?"undefined":r.toString();$r.formatters.c=r=>r==null?"undefined":r.toString();$r.formatters.k=r=>r==null?"undefined":r.toString();$r.formatters.a=r=>r==null?"undefined":r.toString();function yT(r,e=""){let t=wT(r.message),n=wT(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
4
4
  `).join(`
5
5
  ${e}`)}`:`${t}
6
6
  ${e}${n.split(`
@@ -43,12 +43,12 @@ ${[...t.errors.entries()].map(([i,s])=>`
43
43
  `),t),n.trace('responded with "%s" for "%s"',i,i),o.unwrap(),i;if(i==="ls"){let s=new G(...e.map(a=>Si.single(qn(`${a}
44
44
  `))),qn(`
45
45
  `));n.trace('respond with "%s" for %s',e,i),await o.write(s,t),n.trace('responded with "%s" for %s',e,i);continue}n.trace('respond with "na" for "%s"',i),await o.write(qn(`na
46
- `),t),n('responded with "na" for "%s"',i)}}var a7=class extends se{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=Kw(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 Yi(n.local,n.error))})}[Symbol.toStringTag]="Connection";[Vx]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new Is("Connection is not multiplexed");if(this.muxer.status!=="open")throw new oa(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new oa(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new rd("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new k("connection:open-stream",{connection:this,protocols: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 c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await nu(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=qG(n.protocol,this.components.registrar,t),i=BC(n.protocol,"outbound",this);if(i>o){let c=new Kc(`Too many outbound protocol streams for protocol "${n.protocol}" - ${i}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let s=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,s);return t.onProgress?.(new k("connection:opened-stream",{connection:this,stream:a})),a}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 ou(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=HG(t.protocol,this.components.registrar);if(BC(t.protocol,"inbound",this)>o)throw new Cp(`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:s,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new rd("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,d)=>{await s(l,u),d(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 i=n[o];e.log.trace("running middleware",o,i),await new Promise((s,a)=>{try{let c=i(e,t,(l,u)=>{e=l,t=u,s()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,i)}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 MC(r,e){return new a7(r,e)}function HG(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 n7}function qG(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??o7}function BC(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var S2=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=_t({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=_t({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 r2(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=ae([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 n2("Connection denied");await Me(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(i){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[i.name??"Error"]:!0}),i}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(s=>s.code===421)?.value,o;n!=null&&(o=Ee(n),await Me(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let i="outbound";return t.initiator===!1&&(i="inbound"),await this._performUpgrade(e,i,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,i,s,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 d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),o=await d.protect(o,n))}try{if(VG(n)){if(n.remotePeer==null)throw new ko(`${t} connection that skipped encryption must have a peer id`);c="native",i=n.remotePeer}else{let d=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,f;d!=null&&(f=Ee(d)),n?.onProgress?.(new k(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:i,protocol:c,streamMuxer:s}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:f}):this._encryptOutbound(o,{...n,remotePeer:f}))}if(i.equals(this.components.peerId)){let d=new qc("Can not dial self");throw e.abort(d),d}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",i,e),n?.muxerFactory!=null?s=n.muxerFactory:s==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new k(`upgrader:multiplex-${t}-connection`)),s=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(d){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,d),d}s!=null&&(e.log("create muxer %s",s.protocol),a=s.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",i,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:i,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=MC(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 ou(e,n,t),i=this.connectionEncrypters.get(o);if(i==null)throw new lc(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await i.secureInbound(e,t),protocol:o}}catch(o){throw new lc(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 nu(e,n,t),i=this.connectionEncrypters.get(o);if(i==null)throw new lc(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await i.secureOutbound(e,t),protocol:o}}catch(o){throw new lc(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 i=await nu(e,o,n),s=t.get(i);if(s==null)throw new Is(`No muxer configured for protocol "${i}"`);return e.log("selected %s as muxer protocol",i),s}catch(i){throw e.log.error("error multiplexing outbound connection - %e",i),new Is(String(i))}}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 i=await ou(e,o,n),s=t.get(i);if(s==null)throw new Is(`No muxer configured for protocol "${i}"`);return e.log("selected %s as muxer protocol",i),s}catch(i){throw e.log.error("error multiplexing inbound connection - %e",i),i}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function VG(r){return r.skipEncryption===!0}var A2="3.3.3",T2="js-libp2p";function _2(r,e){return`${r??T2}/${e??A2} browser/${globalThis.navigator.userAgent}`}var Gf=class extends se{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new se,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),d=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||d},this.peerId=e.peerId,this.logger=e.logger??Ol(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??T2,i=e.nodeInfo?.version??A2,s=this.components=xC({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:i,userAgent:e.nodeInfo?.userAgent??_2(o,i)},logger:this.logger,events:t,datastore:e.datastore??new cc,connectionGater:vC(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",dC(s,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),s.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(d=>d.multiaddr)};s.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(s)),this.components.upgrader=new S2(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 E2(this.components,e.transportManager)),this.configureComponent("connectionManager",new p2(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new m2(this.components,e.connectionMonitor)),this.configureComponent("registrar",new x2(this.components)),this.configureComponent("addressManager",new W0(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 w2(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 g2(this.components,{routers:c})),this.configureComponent("randomWalk",new b2(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",f=>{this.#e(f)})}),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],d=u(this.components);if(d==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=d,this.configureComponent(l,d),d[si]!=null&&(this.log("registering service %s for content routing",l),c.push(d[si])),d[ci]!=null&&(this.log("registering service %s for peer routing",l),a.push(d[ci])),d[aa]!=null&&(this.log("registering service %s for peer discovery",l),d[aa].addEventListener?.("peer",f=>{this.#e(f)}))}EC(s)}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 fn;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 E("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new E("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={}){$o(e)&&(e=Ee(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 s=await this.peerStore.get(e,t);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.name!=="NotFoundError")throw s}let n=hC([Uf("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),i=Et(o);return await this.peerStore.patch(e,{publicKey:i},t),i}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 C2(r={}){r.privateKey??=await um("Ed25519");let e=new Gf({...await K_(r),peerId:LT(r.privateKey)});return r.start!==!1&&await e.start(),e}var KG=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function UC(r){return r==null?!1:r instanceof Gf?!0:KG.every(e=>typeof r[e]=="function")}var qI=Yt(jC(),1);function YC(r=0){return new Uint8Array(r)}function QC(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var XC=QC("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),c7=QC("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=YC(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),nW={utf8:XC,"utf-8":XC,hex:oe.base16,latin1:c7,ascii:c7,binary:c7,...oe},I2=nW;function Ni(r,e="utf8"){let t=I2[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function jo(r,e="utf8"){let t=I2[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var l7={keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"};var iu={};xt(iu,{create:()=>oW,derivedEmptyPasswordKey:()=>k2});var k2={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function oW(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",i=r?.saltLength??16,s=r?.iterations??32767,a=At.get();t*=8;async function c(d,f){let h=a.getRandomValues(new Uint8Array(i)),p=a.getRandomValues(new Uint8Array(n)),y={name:e,iv:p};typeof f=="string"&&(f=lt(f));let g;if(f.length===0){g=await a.subtle.importKey("jwk",k2,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},_=await a.subtle.importKey("raw",Pt(f),{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,_,{name:e,length:t},!0,["encrypt"])}catch{g=await a.subtle.importKey("jwk",k2,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},_=await a.subtle.importKey("raw",Pt(f),{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,_,{name:e,length:t},!0,["encrypt"])}let m=await a.subtle.encrypt(y,g,Pt(d));return M6([h,y.iv,new Uint8Array(m)])}async function l(d,f){let h=d.subarray(0,i),p=d.subarray(i,i+n),y=d.subarray(i+n),g={name:e,iv:p};typeof f=="string"&&(f=lt(f));let m;if(f.length===0)try{let _={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},R=await a.subtle.importKey("raw",Pt(f),{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(_,R,{name:e,length:t},!0,["decrypt"])}catch{m=await a.subtle.importKey("jwk",k2,{name:"AES-GCM"},!0,["decrypt"])}else{let _={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},R=await a.subtle.importKey("raw",Pt(f),{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(_,R,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(g,m,Pt(y));return new Uint8Array(b)}return{encrypt:c,decrypt:l}}var ve=Yt(ZC());function uc(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 ks(r,e,t=-1){let n=t,o=r,i=0,s=Math.pow(2,e);for(let a=1;a<8;a++){if(r<s){let c;if(n<0)c=new ArrayBuffer(a),i=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),i=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let d=Math.pow(2,u*e);l[i-u-1]=Math.floor(o/d),o-=l[i-u-1]*d}return c}s*=Math.pow(2,e)}return new ArrayBuffer(0)}function D2(...r){let e=0,t=0;for(let i of r)e+=i.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let i of r)o.set(i,t),t+=i.length;return o}function d7(){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=uc(t,8),o=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)i[a]=r[a];return i[0]&=127,uc(i,8)-n}function JC(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let s=t-e,a=ks(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=ks(e,8,n),i=new Uint8Array(o);if(i[0]&128){let s=o.slice(0),a=new Uint8Array(s);o=new ArrayBuffer(o.byteLength+1),i=new Uint8Array(o);for(let c=0;c<s.byteLength;c++)i[c+1]=a[c];i[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function eI(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 Vr(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]="0";return o.join("").concat(t)}var oxe=Math.log(2);function L2(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function f7(r){let e=0,t=0;for(let o=0;o<r.length;o++){let i=r[o];e+=i.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let i=r[o];n.set(new Uint8Array(i),t),t+=i.byteLength}return n.buffer}function $i(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 Yf=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return f7(this.items)}},Wf=[new Uint8Array([1])],tI="0123456789";var au="",Qo=new ArrayBuffer(0),h7=new Uint8Array(0),Xf="EndOfContent",nI="OCTET STRING",oI="BIT STRING";function Hi(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 i=n[0]||{};this.isHexOnly=(o=i.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=i.valueHex?ve.BufferSourceConverter.toUint8Array(i.valueHex):h7}fromBER(n,o,i,s){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!$i(this,a,o,i))return-1;let c=o+i;return this.valueHexView=a.subarray(o,c),this.valueHexView.length?(this.blockLength=i,c):(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",Qo)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ve.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Bi=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=au,warnings:n=[],valueBeforeDecode:o=h7}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=ve.BufferSourceConverter.toUint8Array(o)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ve.Convert.ToHex(this.valueBeforeDecodeView)}}};Bi.NAME="baseBlock";var nr=class extends Bi{fromBER(e,t,n,o){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'")}};nr.NAME="valueBlock";var N2=class extends Hi(Bi){constructor({idBlock:e={}}={}){var t,n,o,i;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?ve.BufferSourceConverter.toUint8Array(e.valueHex):h7,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(i=e.isConstructed)!==null&&i!==void 0?i:!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",Qo}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let i=this.tagNumber;i&=31,t|=i,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=ks(this.tagNumber,7),i=new Uint8Array(o),s=o.byteLength,a=new Uint8Array(s+1);if(a[0]=t|31,!e){for(let c=0;c<s-1;c++)a[c+1]=i[c]|128;a[s]=i[s-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let i=0;i<o.length-1;i++)n[i+1]=o[i]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=ve.BufferSourceConverter.toUint8Array(e);if(!$i(this,o,t,n))return-1;let i=o.subarray(t,t+n);if(i.length===0)return this.error="Zero buffer length",-1;switch(i[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=(i[0]&32)===32,this.isHexOnly=!1;let a=i[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){let u=c+1;if(u>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(i[u]&128)===0)break}this.blockLength=c+1;let l=this.valueHexView=new Uint8Array(c);for(let u=0;u<c;u++)l[u]=i[u+1]&127;this.blockLength<=9?this.tagNumber=uc(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}}};N2.NAME="identificationBlock";var O2=class extends Bi{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=ve.BufferSourceConverter.toUint8Array(e);if(!$i(this,o,t,n))return-1;let i=o.subarray(t,t+n);if(i.length===0)return this.error="Zero buffer length",-1;if(i[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=i[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,t+this.blockLength;let s=i[0]&127;if(s>8)return this.error="Too big integer",-1;if(s+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+s);return c[s-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=uc(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=s+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=ks(this.length,8);if(o.byteLength>127)return this.error="Too big length",Qo;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let i=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let s=0;s<o.byteLength;s++)n[s+1]=i[s];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}}};O2.NAME="lengthBlock";var Q={},Wt=class extends Bi{constructor({name:e=au,optional:t=!1,primitiveSchema:n,...o}={},i){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new N2(o),this.lenBlock=new O2(o),this.valueBlock=i?new i(o):new nr(o)}fromBER(e,t,n,o){let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return i===-1?(this.error=this.valueBlock.error,i):(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),i)}toBER(e,t){let n=t||new Yf;t||iI(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 i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;let s=this.lenBlock.toBER(e);n.write(s),n.write(i)}return t?Qo: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():ve.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=ve.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 eI(t,n)}};Wt.NAME="BaseBlock";function iI(r){var e;if(r instanceof Q.Constructed)for(let t of r.valueBlock.value)iI(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var B2=class extends Wt{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=au,...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}'`}};B2.NAME="BaseStringBlock";var M2=class extends Hi(nr){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};M2.NAME="PrimitiveValueBlock";var sI,F2=class extends Wt{constructor(e={}){super(e,M2),this.idBlock.isConstructed=!1}};sI=F2;Q.Primitive=sI;F2.NAME="PRIMITIVE";var hW=100,pW=1e4,mW=16*1024*1024,gW="Maximum ASN.1 nesting depth exceeded",yW="Maximum ASN.1 node count exceeded",wW="Maximum ASN.1 content length exceeded";function rh(r={}){var e,t,n;return{depth:0,maxDepth:(e=r.maxDepth)!==null&&e!==void 0?e:hW,nodesCount:0,maxNodes:(t=r.maxNodes)!==null&&t!==void 0?t:pW,maxContentLength:(n=r.maxContentLength)!==null&&n!==void 0?n:mW}}function bW(r){let e=new Wt({},nr);return e.error=r,{offset:-1,result:e}}function xW(r){if(r.nodesCount+=1,r.nodesCount>r.maxNodes)return yW}function EW(r,e){if(r>e.maxContentLength)return wW}function p7(r,e,t,n){let o=n.depth+1;if(o>n.maxDepth)return bW(gW);n.depth=o;try{return aI(r,e,t,n)}finally{n.depth-=1}}function vW(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 aI(r,e=0,t=r.length,n=rh()){let o=e,i=new Wt({},nr),s=new Bi;if(!$i(s,r,e,t))return i.error=s.error,{offset:-1,result:i};if(!r.subarray(e,e+t).length)return i.error="Zero buffer length",{offset:-1,result:i};let c=xW(n);if(c)return i.error=c,{offset:-1,result:i};let l=i.idBlock.fromBER(r,e,t);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),l===-1)return i.error=i.idBlock.error,{offset:-1,result:i};if(e=l,t-=i.idBlock.blockLength,l=i.lenBlock.fromBER(r,e,t),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),l===-1)return i.error=i.lenBlock.error,{offset:-1,result:i};e=l,t-=i.lenBlock.blockLength;let u=i.lenBlock.isIndefiniteForm?t:i.lenBlock.length,d=EW(u,n);if(d)return i.error=d,{offset:-1,result:i};if(!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let f=Wt;switch(i.idBlock.tagClass){case 1:if(i.idBlock.tagNumber>=37&&i.idBlock.isHexOnly===!1)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};f=Q.EndOfContent;break;case 1:f=Q.Boolean;break;case 2:f=Q.Integer;break;case 3:f=Q.BitString;break;case 4:f=Q.OctetString;break;case 5:f=Q.Null;break;case 6:f=Q.ObjectIdentifier;break;case 10:f=Q.Enumerated;break;case 12:f=Q.Utf8String;break;case 13:f=Q.RelativeObjectIdentifier;break;case 14:f=Q.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:f=Q.Sequence;break;case 17:f=Q.Set;break;case 18:f=Q.NumericString;break;case 19:f=Q.PrintableString;break;case 20:f=Q.TeletexString;break;case 21:f=Q.VideotexString;break;case 22:f=Q.IA5String;break;case 23:f=Q.UTCTime;break;case 24:f=Q.GeneralizedTime;break;case 25:f=Q.GraphicString;break;case 26:f=Q.VisibleString;break;case 27:f=Q.GeneralString;break;case 28:f=Q.UniversalString;break;case 29:f=Q.CharacterString;break;case 30:f=Q.BmpString;break;case 31:f=Q.DATE;break;case 32:f=Q.TimeOfDay;break;case 33:f=Q.DateTime;break;case 34:f=Q.Duration;break;default:{let h=i.idBlock.isConstructed?new Q.Constructed:new Q.Primitive;h.idBlock=i.idBlock,h.lenBlock=i.lenBlock,h.warnings=i.warnings,i=h}}break;default:f=i.idBlock.isConstructed?Q.Constructed:Q.Primitive}return i=vW(i,f),l=i.fromBER(r,e,u,n),i.valueBeforeDecodeView=r.subarray(o,o+i.blockLength),{offset:l,result:i}}function wg(r,e={}){if(!r.byteLength){let t=new Wt({},nr);return t.error="Input buffer has zero length",{offset:-1,result:t}}return aI(ve.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength,rh(e))}function SW(r,e){return r?1:e}var Yo=class extends nr{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n,o){let i=ve.BufferSourceConverter.toUint8Array(e),s=o??rh();if(!$i(this,i,t,n))return-1;if(this.valueBeforeDecodeView=i.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let a=t;for(;SW(this.isIndefiniteForm,n)>0;){let c=p7(i,a,n,s);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===Xf)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Xf?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,t){let n=t||new Yf;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?Qo:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};Yo.NAME="ConstructedValueBlock";var cI,Rs=class extends Wt{constructor(e={}){super(e,Yo),this.idBlock.isConstructed=!0}fromBER(e,t,n,o){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return i===-1?(this.error=this.valueBlock.error,i):(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),i)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
46
+ `),t),n('responded with "na" for "%s"',i)}}var a7=class extends se{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=Kw(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 Yi(n.local,n.error))})}[Symbol.toStringTag]="Connection";[Vx]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new Is("Connection is not multiplexed");if(this.muxer.status!=="open")throw new oa(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new oa(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new rd("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),t.onProgress?.(new k("connection:open-stream",{connection:this,protocols: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 c=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:c}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await nu(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=qG(n.protocol,this.components.registrar,t),i=BC(n.protocol,"outbound",this);if(i>o){let c=new Kc(`Too many outbound protocol streams for protocol "${n.protocol}" - ${i}/${o}`);throw n.abort(c),c}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let s=this.components.registrar.getMiddleware(n.protocol),a=await this.runMiddlewareChain(n,this,s);return t.onProgress?.(new k("connection:opened-stream",{connection:this,stream:a})),a}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 ou(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=HG(t.protocol,this.components.registrar);if(BC(t.protocol,"inbound",this)>o)throw new Cp(`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:s,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new rd("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,d)=>{await s(l,u),d(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 i=n[o];e.log.trace("running middleware",o,i),await new Promise((s,a)=>{try{let c=i(e,t,(l,u)=>{e=l,t=u,s()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,i)}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 MC(r,e){return new a7(r,e)}function HG(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 n7}function qG(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??o7}function BC(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var S2=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=_t({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=_t({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 r2(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=ae([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 n2("Connection denied");await Me(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(i){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[i.name??"Error"]:!0}),i}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(s=>s.code===421)?.value,o;n!=null&&(o=Ee(n),await Me(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let i="outbound";return t.initiator===!1&&(i="inbound"),await this._performUpgrade(e,i,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,i,s,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 d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),o=await d.protect(o,n))}try{if(VG(n)){if(n.remotePeer==null)throw new ko(`${t} connection that skipped encryption must have a peer id`);c="native",i=n.remotePeer}else{let d=e.remoteAddr.getComponents().findLast(h=>h.code===421)?.value,f;d!=null&&(f=Ee(d)),n?.onProgress?.(new k(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:i,protocol:c,streamMuxer:s}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:f}):this._encryptOutbound(o,{...n,remotePeer:f}))}if(i.equals(this.components.peerId)){let d=new qc("Can not dial self");throw e.abort(d),d}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",i,e),n?.muxerFactory!=null?s=n.muxerFactory:s==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new k(`upgrader:multiplex-${t}-connection`)),s=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(d){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,d),d}s!=null&&(e.log("create muxer %s",s.protocol),a=s.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",i,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:i,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=MC(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 ou(e,n,t),i=this.connectionEncrypters.get(o);if(i==null)throw new lc(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await i.secureInbound(e,t),protocol:o}}catch(o){throw new lc(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 nu(e,n,t),i=this.connectionEncrypters.get(o);if(i==null)throw new lc(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await i.secureOutbound(e,t),protocol:o}}catch(o){throw new lc(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 i=await nu(e,o,n),s=t.get(i);if(s==null)throw new Is(`No muxer configured for protocol "${i}"`);return e.log("selected %s as muxer protocol",i),s}catch(i){throw e.log.error("error multiplexing outbound connection - %e",i),new Is(String(i))}}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 i=await ou(e,o,n),s=t.get(i);if(s==null)throw new Is(`No muxer configured for protocol "${i}"`);return e.log("selected %s as muxer protocol",i),s}catch(i){throw e.log.error("error multiplexing inbound connection - %e",i),i}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function VG(r){return r.skipEncryption===!0}var A2="3.3.3",T2="js-libp2p";function _2(r,e){return`${r??T2}/${e??A2} browser/${globalThis.navigator.userAgent}`}var Gf=class extends se{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new se,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),d=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||d},this.peerId=e.peerId,this.logger=e.logger??Ol(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??T2,i=e.nodeInfo?.version??A2,s=this.components=xC({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:i,userAgent:e.nodeInfo?.userAgent??_2(o,i)},logger:this.logger,events:t,datastore:e.datastore??new cc,connectionGater:vC(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",dC(s,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),s.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(d=>d.multiaddr)};s.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(s)),this.components.upgrader=new S2(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 E2(this.components,e.transportManager)),this.configureComponent("connectionManager",new p2(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new m2(this.components,e.connectionMonitor)),this.configureComponent("registrar",new x2(this.components)),this.configureComponent("addressManager",new W0(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 w2(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 g2(this.components,{routers:c})),this.configureComponent("randomWalk",new b2(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",f=>{this.#e(f)})}),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],d=u(this.components);if(d==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=d,this.configureComponent(l,d),d[si]!=null&&(this.log("registering service %s for content routing",l),c.push(d[si])),d[ci]!=null&&(this.log("registering service %s for peer routing",l),a.push(d[ci])),d[aa]!=null&&(this.log("registering service %s for peer discovery",l),d[aa].addEventListener?.("peer",f=>{this.#e(f)}))}EC(s)}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 fn;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 E("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new E("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={}){$o(e)&&(e=Ee(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 s=await this.peerStore.get(e,t);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.name!=="NotFoundError")throw s}let n=hC([Uf("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),i=Et(o);return await this.peerStore.patch(e,{publicKey:i},t),i}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 C2(r={}){r.privateKey??=await um("Ed25519");let e=new Gf({...await K_(r),peerId:LT(r.privateKey)});return r.start!==!1&&await e.start(),e}var KG=["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"];function UC(r){return r==null?!1:r instanceof Gf?!0:KG.every(e=>typeof r[e]=="function")}var qI=Yt(jC(),1);function YC(r=0){return new Uint8Array(r)}function QC(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var XC=QC("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),c7=QC("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=YC(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),nW={utf8:XC,"utf-8":XC,hex:oe.base16,latin1:c7,ascii:c7,binary:c7,...oe},I2=nW;function Ni(r,e="utf8"){let t=I2[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function jo(r,e="utf8"){let t=I2[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var l7={keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"};var iu={};xt(iu,{create:()=>oW,derivedEmptyPasswordKey:()=>k2});var k2={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function oW(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",i=r?.saltLength??16,s=r?.iterations??32767,a=At.get();t*=8;async function c(d,f){let h=a.getRandomValues(new Uint8Array(i)),p=a.getRandomValues(new Uint8Array(n)),y={name:e,iv:p};typeof f=="string"&&(f=lt(f));let g;if(f.length===0){g=await a.subtle.importKey("jwk",k2,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},T=await a.subtle.importKey("raw",Pt(f),{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,T,{name:e,length:t},!0,["encrypt"])}catch{g=await a.subtle.importKey("jwk",k2,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},T=await a.subtle.importKey("raw",Pt(f),{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(b,T,{name:e,length:t},!0,["encrypt"])}let m=await a.subtle.encrypt(y,g,Pt(d));return M6([h,y.iv,new Uint8Array(m)])}async function l(d,f){let h=d.subarray(0,i),p=d.subarray(i,i+n),y=d.subarray(i+n),g={name:e,iv:p};typeof f=="string"&&(f=lt(f));let m;if(f.length===0)try{let T={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},R=await a.subtle.importKey("raw",Pt(f),{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(T,R,{name:e,length:t},!0,["decrypt"])}catch{m=await a.subtle.importKey("jwk",k2,{name:"AES-GCM"},!0,["decrypt"])}else{let T={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},R=await a.subtle.importKey("raw",Pt(f),{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(T,R,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(g,m,Pt(y));return new Uint8Array(b)}return{encrypt:c,decrypt:l}}var ve=Yt(ZC());function uc(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 ks(r,e,t=-1){let n=t,o=r,i=0,s=Math.pow(2,e);for(let a=1;a<8;a++){if(r<s){let c;if(n<0)c=new ArrayBuffer(a),i=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),i=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let d=Math.pow(2,u*e);l[i-u-1]=Math.floor(o/d),o-=l[i-u-1]*d}return c}s*=Math.pow(2,e)}return new ArrayBuffer(0)}function D2(...r){let e=0,t=0;for(let i of r)e+=i.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let i of r)o.set(i,t),t+=i.length;return o}function d7(){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=uc(t,8),o=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)i[a]=r[a];return i[0]&=127,uc(i,8)-n}function JC(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let s=t-e,a=ks(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=ks(e,8,n),i=new Uint8Array(o);if(i[0]&128){let s=o.slice(0),a=new Uint8Array(s);o=new ArrayBuffer(o.byteLength+1),i=new Uint8Array(o);for(let c=0;c<s.byteLength;c++)i[c+1]=a[c];i[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function eI(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 Vr(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]="0";return o.join("").concat(t)}var oxe=Math.log(2);function L2(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function f7(r){let e=0,t=0;for(let o=0;o<r.length;o++){let i=r[o];e+=i.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let i=r[o];n.set(new Uint8Array(i),t),t+=i.byteLength}return n.buffer}function $i(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 Yf=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return f7(this.items)}},Wf=[new Uint8Array([1])],tI="0123456789";var au="",Qo=new ArrayBuffer(0),h7=new Uint8Array(0),Xf="EndOfContent",nI="OCTET STRING",oI="BIT STRING";function Hi(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 i=n[0]||{};this.isHexOnly=(o=i.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=i.valueHex?ve.BufferSourceConverter.toUint8Array(i.valueHex):h7}fromBER(n,o,i,s){let a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!$i(this,a,o,i))return-1;let c=o+i;return this.valueHexView=a.subarray(o,c),this.valueHexView.length?(this.blockLength=i,c):(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",Qo)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ve.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Bi=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=au,warnings:n=[],valueBeforeDecode:o=h7}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=ve.BufferSourceConverter.toUint8Array(o)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ve.Convert.ToHex(this.valueBeforeDecodeView)}}};Bi.NAME="baseBlock";var nr=class extends Bi{fromBER(e,t,n,o){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'")}};nr.NAME="valueBlock";var N2=class extends Hi(Bi){constructor({idBlock:e={}}={}){var t,n,o,i;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?ve.BufferSourceConverter.toUint8Array(e.valueHex):h7,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(i=e.isConstructed)!==null&&i!==void 0?i:!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",Qo}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let i=this.tagNumber;i&=31,t|=i,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=ks(this.tagNumber,7),i=new Uint8Array(o),s=o.byteLength,a=new Uint8Array(s+1);if(a[0]=t|31,!e){for(let c=0;c<s-1;c++)a[c+1]=i[c]|128;a[s]=i[s-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let i=0;i<o.length-1;i++)n[i+1]=o[i]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=ve.BufferSourceConverter.toUint8Array(e);if(!$i(this,o,t,n))return-1;let i=o.subarray(t,t+n);if(i.length===0)return this.error="Zero buffer length",-1;switch(i[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=(i[0]&32)===32,this.isHexOnly=!1;let a=i[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){let u=c+1;if(u>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(i[u]&128)===0)break}this.blockLength=c+1;let l=this.valueHexView=new Uint8Array(c);for(let u=0;u<c;u++)l[u]=i[u+1]&127;this.blockLength<=9?this.tagNumber=uc(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}}};N2.NAME="identificationBlock";var O2=class extends Bi{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=ve.BufferSourceConverter.toUint8Array(e);if(!$i(this,o,t,n))return-1;let i=o.subarray(t,t+n);if(i.length===0)return this.error="Zero buffer length",-1;if(i[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=i[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,t+this.blockLength;let s=i[0]&127;if(s>8)return this.error="Too big integer",-1;if(s+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+s);return c[s-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=uc(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=s+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=ks(this.length,8);if(o.byteLength>127)return this.error="Too big length",Qo;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let i=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let s=0;s<o.byteLength;s++)n[s+1]=i[s];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}}};O2.NAME="lengthBlock";var Q={},Wt=class extends Bi{constructor({name:e=au,optional:t=!1,primitiveSchema:n,...o}={},i){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new N2(o),this.lenBlock=new O2(o),this.valueBlock=i?new i(o):new nr(o)}fromBER(e,t,n,o){let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return i===-1?(this.error=this.valueBlock.error,i):(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),i)}toBER(e,t){let n=t||new Yf;t||iI(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 i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;let s=this.lenBlock.toBER(e);n.write(s),n.write(i)}return t?Qo: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():ve.Convert.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,t=ve.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 eI(t,n)}};Wt.NAME="BaseBlock";function iI(r){var e;if(r instanceof Q.Constructed)for(let t of r.valueBlock.value)iI(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!(!((e=r.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}var B2=class extends Wt{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=au,...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}'`}};B2.NAME="BaseStringBlock";var M2=class extends Hi(nr){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};M2.NAME="PrimitiveValueBlock";var sI,F2=class extends Wt{constructor(e={}){super(e,M2),this.idBlock.isConstructed=!1}};sI=F2;Q.Primitive=sI;F2.NAME="PRIMITIVE";var hW=100,pW=1e4,mW=16*1024*1024,gW="Maximum ASN.1 nesting depth exceeded",yW="Maximum ASN.1 node count exceeded",wW="Maximum ASN.1 content length exceeded";function rh(r={}){var e,t,n;return{depth:0,maxDepth:(e=r.maxDepth)!==null&&e!==void 0?e:hW,nodesCount:0,maxNodes:(t=r.maxNodes)!==null&&t!==void 0?t:pW,maxContentLength:(n=r.maxContentLength)!==null&&n!==void 0?n:mW}}function bW(r){let e=new Wt({},nr);return e.error=r,{offset:-1,result:e}}function xW(r){if(r.nodesCount+=1,r.nodesCount>r.maxNodes)return yW}function EW(r,e){if(r>e.maxContentLength)return wW}function p7(r,e,t,n){let o=n.depth+1;if(o>n.maxDepth)return bW(gW);n.depth=o;try{return aI(r,e,t,n)}finally{n.depth-=1}}function vW(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 aI(r,e=0,t=r.length,n=rh()){let o=e,i=new Wt({},nr),s=new Bi;if(!$i(s,r,e,t))return i.error=s.error,{offset:-1,result:i};if(!r.subarray(e,e+t).length)return i.error="Zero buffer length",{offset:-1,result:i};let c=xW(n);if(c)return i.error=c,{offset:-1,result:i};let l=i.idBlock.fromBER(r,e,t);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),l===-1)return i.error=i.idBlock.error,{offset:-1,result:i};if(e=l,t-=i.idBlock.blockLength,l=i.lenBlock.fromBER(r,e,t),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),l===-1)return i.error=i.lenBlock.error,{offset:-1,result:i};e=l,t-=i.lenBlock.blockLength;let u=i.lenBlock.isIndefiniteForm?t:i.lenBlock.length,d=EW(u,n);if(d)return i.error=d,{offset:-1,result:i};if(!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let f=Wt;switch(i.idBlock.tagClass){case 1:if(i.idBlock.tagNumber>=37&&i.idBlock.isHexOnly===!1)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};f=Q.EndOfContent;break;case 1:f=Q.Boolean;break;case 2:f=Q.Integer;break;case 3:f=Q.BitString;break;case 4:f=Q.OctetString;break;case 5:f=Q.Null;break;case 6:f=Q.ObjectIdentifier;break;case 10:f=Q.Enumerated;break;case 12:f=Q.Utf8String;break;case 13:f=Q.RelativeObjectIdentifier;break;case 14:f=Q.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:f=Q.Sequence;break;case 17:f=Q.Set;break;case 18:f=Q.NumericString;break;case 19:f=Q.PrintableString;break;case 20:f=Q.TeletexString;break;case 21:f=Q.VideotexString;break;case 22:f=Q.IA5String;break;case 23:f=Q.UTCTime;break;case 24:f=Q.GeneralizedTime;break;case 25:f=Q.GraphicString;break;case 26:f=Q.VisibleString;break;case 27:f=Q.GeneralString;break;case 28:f=Q.UniversalString;break;case 29:f=Q.CharacterString;break;case 30:f=Q.BmpString;break;case 31:f=Q.DATE;break;case 32:f=Q.TimeOfDay;break;case 33:f=Q.DateTime;break;case 34:f=Q.Duration;break;default:{let h=i.idBlock.isConstructed?new Q.Constructed:new Q.Primitive;h.idBlock=i.idBlock,h.lenBlock=i.lenBlock,h.warnings=i.warnings,i=h}}break;default:f=i.idBlock.isConstructed?Q.Constructed:Q.Primitive}return i=vW(i,f),l=i.fromBER(r,e,u,n),i.valueBeforeDecodeView=r.subarray(o,o+i.blockLength),{offset:l,result:i}}function wg(r,e={}){if(!r.byteLength){let t=new Wt({},nr);return t.error="Input buffer has zero length",{offset:-1,result:t}}return aI(ve.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength,rh(e))}function SW(r,e){return r?1:e}var Yo=class extends nr{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n,o){let i=ve.BufferSourceConverter.toUint8Array(e),s=o??rh();if(!$i(this,i,t,n))return-1;if(this.valueBeforeDecodeView=i.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let a=t;for(;SW(this.isIndefiniteForm,n)>0;){let c=p7(i,a,n,s);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===Xf)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Xf?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,t){let n=t||new Yf;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?Qo:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};Yo.NAME="ConstructedValueBlock";var cI,Rs=class extends Wt{constructor(e={}){super(e,Yo),this.idBlock.isConstructed=!0}fromBER(e,t,n,o){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return i===-1?(this.error=this.valueBlock.error,i):(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),i)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
47
47
  `).map(o=>` ${o}`).join(`
48
48
  `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
49
49
  ${e.join(`
50
50
  `)}`:`${t} :`}};cI=Rs;Q.Constructed=cI;Rs.NAME="CONSTRUCTED";var U2=class extends nr{fromBER(e,t,n){return t}toBER(e){return Qo}};U2.override="EndOfContentValueBlock";var lI,$2=class extends Wt{constructor(e={}){super(e,U2),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};lI=$2;Q.EndOfContent=lI;$2.NAME=Xf;var uI,dc=class extends Wt{constructor(e={}){super(e,nr),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}`}};uI=dc;Q.Null=uI;dc.NAME="NULL";var H2=class extends Hi(nr){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=ve.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,n){let o=ve.BufferSourceConverter.toUint8Array(e);return $i(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,d7.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};H2.NAME="BooleanValueBlock";var dI,q2=class extends Wt{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,H2),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};dI=q2;Q.Boolean=dI;q2.NAME="BOOLEAN";var V2=class extends Hi(Yo){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n,o){let i=0;if(this.isConstructed){if(this.isHexOnly=!1,i=Yo.prototype.fromBER.call(this,e,t,n,o),i===-1)return i;for(let s=0;s<this.value.length;s++){let a=this.value[s].constructor.NAME;if(a===Xf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==nI)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,i=super.fromBER(e,t,n),this.blockLength=n;return i}toBER(e,t){return this.isConstructed?Yo.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};V2.NAME="OctetStringValueBlock";var m7,Mi=class extends Wt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},V2),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n,o){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let a=o??rh(),c=p7(s,0,s.byteLength,a);c.offset!==-1&&c.offset===n&&(this.valueBlock.value=[c.result])}}catch{}}return super.fromBER(e,t,n,o)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Rs.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,t=ve.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 m7&&e.push(t.valueBlock.valueHexView);return ve.BufferSourceConverter.concat(e)}};m7=Mi;Q.OctetString=m7;Mi.NAME=nI;var K2=class extends Hi(Yo){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n,o){if(!n)return t;let i=-1;if(this.isConstructed){if(i=Yo.prototype.fromBER.call(this,e,t,n,o),i===-1)return i;for(let c of this.value){let l=c.constructor.NAME;if(l===Xf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(l!==oI)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let u=c.valueBlock;if(this.unusedBits>0&&u.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=u.unusedBits}return i}let s=ve.BufferSourceConverter.toUint8Array(e);if(!$i(this,s,t,n))return-1;let a=s.subarray(t,t+n);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let c=a.subarray(1);try{if(c.byteLength){let l=o??rh(),u=p7(c,0,c.byteLength,l);u.offset!==-1&&u.offset===n-1&&(this.value=[u.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,t+n}toBER(e,t){if(this.isConstructed)return Yo.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let o=new Uint8Array(1);return o[0]=0,o.buffer}let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};K2.NAME="BitStringValueBlock";var fI,z2=class extends Wt{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},K2),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n,o){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n,o)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Rs.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let s of t)e.push(s.toString(2).padStart(8,"0"));let n=e.join(""),o=this.constructor.NAME,i=n.substring(0,n.length-this.valueBlock.unusedBits);return`${o} : ${i}`}}};fI=z2;Q.BitString=fI;z2.NAME=oI;var hI;function AW(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<s?s:c,d=0;for(let f=u;f>=0;f--,d++)!0===d<a.length?l=i[s-d]+a[c-d]+t[0]:l=i[s-d]+t[0],t[0]=l/10,!0===d>=i.length?i=D2(new Uint8Array([l%10]),i):i[s-d]=l%10;return t[0]>0&&(i=D2(t,i)),i}function rI(r){if(r>=Wf.length)for(let e=Wf.length;e<=r;e++){let t=new Uint8Array([0]),n=Wf[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let i=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=i[0]/10,n[o]=i[0]%10}t[0]>0&&(n=D2(t,n)),Wf.push(n)}return Wf[r]}function TW(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let d=c;d>=0;d--,u++)l=i[s-u]-a[c-u]-t,!0===l<0?(t=1,i[s-u]=l+10):(t=0,i[s-u]=l);if(t>0)for(let d=s-c+1;d>=0;d--,u++)if(l=i[s-u]-t,l<0)t=1,i[s-u]=l+10;else{t=0,i[s-u]=l;break}return i.slice()}var Qf=class extends Hi(nr){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=d7.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(JC(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let i=this.fromBER(e,t,n);if(i===-1)return i;let s=this.valueHexView;return s[0]===0&&(s[1]&128)!==0?this.valueHexView=s.subarray(1):o!==0&&s.length<o&&(o-s.length>1&&(o=s.length+1),this.valueHexView=s.subarray(o-s.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,i=this.valueHexView,s="",a=!1;for(let c=i.byteLength-1;c>=0;c--){o=i[c];for(let l=0;l<8;l++)(o&1)===1&&(n===e?(t=TW(rI(n),t),s="-"):t=AW(t,rI(n))),n++,o>>=1}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(s+=tI.charAt(t[c]));return a===!1&&(s+=tI.charAt(0)),s}};hI=Qf;Qf.NAME="IntegerValueBlock";Object.defineProperty(hI.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var jf,Fi=class extends Wt{constructor(e={}){super(e,Qf),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return L2(),BigInt(this.valueBlock.toString())}static fromBigInt(e){L2();let t=BigInt(e),n=new Yf,o=t.toString(16).replace(/^-/,""),i=new Uint8Array(ve.Convert.FromHex(o));if(t<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${ve.Convert.ToHex(a)}`)+t,u=ve.BufferSourceConverter.toUint8Array(ve.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new jf({valueHex:n.final()})}convertToDER(){let e=new jf({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new jf({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};jf=Fi;Q.Integer=jf;Fi.NAME="INTEGER";var pI,G2=class extends Fi{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};pI=G2;Q.Enumerated=pI;G2.NAME="ENUMERATED";var Zf=class extends Hi(nr){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=ve.BufferSourceConverter.toUint8Array(e);if(!$i(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,(i[a]&128)!==0);a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,(i[this.blockLength-1]&128)!==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=uc(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){L2();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=ks(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Qo;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n}toString(){let e="";if(this.isHexOnly)e=ve.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}}};Zf.NAME="sidBlock";var W2=class extends nr{constructor({value:e=au,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new Zf;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,Qo;t.push(o)}return f7(t)}fromString(e){this.value=[];let t=0,n=0,o="",i=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,i){let s=this.value[0],a=0;switch(s.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;s.valueDec=c+a,i=!1}else{let s=new Zf;if(o>Number.MAX_SAFE_INTEGER){L2();let a=BigInt(o);s.valueBigInt=a}else if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return;this.value.length||(s.isFirstSid=!0,i=!0),this.value.push(s)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};W2.NAME="ObjectIdentifierValueBlock";var mI,Xo=class extends Wt{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,W2),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};mI=Xo;Q.ObjectIdentifier=mI;Xo.NAME="OBJECT IDENTIFIER";var Jf=class extends Hi(Bi){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=ve.BufferSourceConverter.toUint8Array(e);if(!$i(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,(i[a]&128)!==0);a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,(i[this.blockLength-1]&128)!==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=uc(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=ks(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Qo;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n.buffer}toString(){let e="";return this.isHexOnly?e=ve.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Jf.NAME="relativeSidBlock";var j2=class extends nr{constructor({value:e=au,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new Jf;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let i=this.value[o].toBER(e);if(i.byteLength===0)return this.error=this.value[o].error,Qo;n.push(i)}return f7(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let i=new Jf;if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};j2.NAME="RelativeObjectIdentifierValueBlock";var gI,Y2=class extends Wt{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,j2),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};gI=Y2;Q.RelativeObjectIdentifier=gI;Y2.NAME="RelativeObjectIdentifier";var yI,Kr=class extends Rs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};yI=Kr;Q.Sequence=yI;Kr.NAME="SEQUENCE";var wI,X2=class extends Rs{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};wI=X2;Q.Set=wI;X2.NAME="SET";var Q2=class extends Hi(nr){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=au}toJSON(){return{...super.toJSON(),value:this.value}}};Q2.NAME="StringValueBlock";var Z2=class extends Q2{};Z2.NAME="SimpleStringValueBlock";var Br=class extends B2{constructor({...e}={}){super(e,Z2)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,ve.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}};Br.NAME="SIMPLE STRING";var J2=class extends Br{fromBuffer(e){this.valueBlock.valueHexView=ve.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=ve.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=ve.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(ve.Convert.FromUtf8String(e)),this.valueBlock.value=e}};J2.NAME="Utf8StringValueBlock";var bI,Ui=class extends J2{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};bI=Ui;Q.Utf8String=bI;Ui.NAME="UTF8String";var eg=class extends Br{fromBuffer(e){this.valueBlock.value=ve.Convert.ToUtf16String(e),this.valueBlock.valueHexView=ve.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(ve.Convert.FromUtf16String(e))}};eg.NAME="BmpStringValueBlock";var xI,tg=class extends eg{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};xI=tg;Q.BmpString=xI;tg.NAME="BMPString";var rg=class extends Br{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let i=ks(e.charCodeAt(o),8),s=new Uint8Array(i);if(s.length>4)continue;let a=4-s.length;for(let c=s.length-1;c>=0;c--)n[o*4+c+a]=s[c]}this.valueBlock.value=e}};rg.NAME="UniversalStringValueBlock";var EI,ng=class extends rg{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};EI=ng;Q.UniversalString=EI;ng.NAME="UniversalString";var vI,og=class extends Br{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};vI=og;Q.NumericString=vI;og.NAME="NumericString";var SI,ig=class extends Br{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};SI=ig;Q.PrintableString=SI;ig.NAME="PrintableString";var AI,sg=class extends Br{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};AI=sg;Q.TeletexString=AI;sg.NAME="TeletexString";var TI,ag=class extends Br{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};TI=ag;Q.VideotexString=TI;ag.NAME="VideotexString";var _I,cg=class extends Br{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};_I=cg;Q.IA5String=_I;cg.NAME="IA5String";var CI,lg=class extends Br{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};CI=lg;Q.GraphicString=CI;lg.NAME="GraphicString";var II,eh=class extends Br{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};II=eh;Q.VisibleString=II;eh.NAME="VisibleString";var kI,ug=class extends Br{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};kI=ug;Q.GeneralString=kI;ug.NAME="GeneralString";var RI,dg=class extends Br{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};RI=dg;Q.CharacterString=RI;dg.NAME="CharacterString";var PI,th=class extends eh{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,ve.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]=Vr(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=Vr(this.month,2),t[2]=Vr(this.day,2),t[3]=Vr(this.hour,2),t[4]=Vr(this.minute,2),t[5]=Vr(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}}};PI=th;Q.UTCTime=PI;th.NAME="UTCTime";var DI,fg=class extends th{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="",i=0,s,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let d=new Number(e[e.length-1]);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let d=1,f=n.indexOf("+"),h="";if(f===-1&&(f=n.indexOf("-"),d=-1),f!==-1){if(h=n.substring(f+1),n=n.substring(0,f),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(h.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=d*p,h.length===4){if(p=parseInt(h.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=d*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let d=new Number(`0${n.substring(l)}`);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");i=d.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=60*i;this.minute=Math.floor(d),d=60*(d-this.minute),this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case o.length===12:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=60*i;this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case o.length===14:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let d=1e3*i;this.millisecond=Math.floor(d)}break;default:throw new Error("Wrong input string for conversion")}let u=s.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let d=1;d<u.length;d++)switch(d){case 1:this.year=parseInt(u[d],10);break;case 2:this.month=parseInt(u[d],10);break;case 3:this.day=parseInt(u[d],10);break;case 4:this.hour=parseInt(u[d],10)+a;break;case 5:this.minute=parseInt(u[d],10)+c;break;case 6:this.second=parseInt(u[d],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let d=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=d.getUTCFullYear(),this.month=d.getUTCMonth(),this.day=d.getUTCDay(),this.hour=d.getUTCHours(),this.minute=d.getUTCMinutes(),this.second=d.getUTCSeconds(),this.millisecond=d.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(Vr(this.year,4)),t.push(Vr(this.month,2)),t.push(Vr(this.day,2)),t.push(Vr(this.hour,2)),t.push(Vr(this.minute,2)),t.push(Vr(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(Vr(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};DI=fg;Q.GeneralizedTime=DI;fg.NAME="GeneralizedTime";var LI,hg=class extends Ui{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};LI=hg;Q.DATE=LI;hg.NAME="DATE";var NI,pg=class extends Ui{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};NI=pg;Q.TimeOfDay=NI;pg.NAME="TimeOfDay";var OI,mg=class extends Ui{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};OI=mg;Q.DateTime=OI;mg.NAME="DateTime";var BI,gg=class extends Ui{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};BI=gg;Q.Duration=BI;gg.NAME="Duration";var MI,yg=class extends Ui{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};MI=yg;Q.TIME=MI;yg.NAME="TIME";function _W(r){return r.buffer instanceof ArrayBuffer}function Ps(r){return _W(r)?r:r.slice()}async function bg(r,e){let n=await iu.create().encrypt(r,e);return Tt.encode(n)}async function g7(r,e,t){if(r.type==="RSA")return RW(r,e,t);if(r.type==="Ed25519")return CW(r,e,t);if(r.type==="secp256k1")return IW(r,e,t);if(r.type==="ECDSA")return kW(r,e,t);throw new Zn}async function CW(r,e,t="libp2p-key"){if(t==="libp2p-key")return bg(Ia(r),e);throw new E(`export format '${t}' is not supported`)}async function IW(r,e,t="libp2p-key"){if(t==="libp2p-key")return bg(Ia(r),e);throw new E("Export format is not supported")}async function kW(r,e,t="libp2p-key"){if(t==="libp2p-key")return bg(Ia(r),e);throw new E(`export format '${t}' is not supported`)}async function RW(r,e,t="pkcs-8"){if(t==="pkcs-8")return PW(r,e);if(t==="libp2p-key")return bg(Ia(r),e);throw new E("Export format is not supported")}async function PW(r,e){let t=At.get(),o=new Kr({value:[new Fi({value:0}),new Kr({value:[new Xo({value:"1.2.840.113549.1.1.1"}),new dc]}),new Mi({valueHex:r.raw})]}).toBER(),i=new Uint8Array(o,0,o.byteLength),s=kr(16),a=await fm(Lo,e,s,{c:1e4,dkLen:32}),c=kr(16),l=await t.subtle.importKey("raw",Ps(a),"AES-CBC",!1,["encrypt"]),u=await t.subtle.encrypt({name:"AES-CBC",iv:Ps(c)},l,Ps(i)),d=new Kr({value:[new Mi({valueHex:s}),new Fi({value:1e4}),new Fi({value:32}),new Kr({value:[new Xo({value:"1.2.840.113549.2.11"}),new dc]})]}),f=new Kr({value:[new Xo({value:"1.2.840.113549.1.5.13"}),new Kr({value:[new Kr({value:[new Xo({value:"1.2.840.113549.1.5.12"}),d]}),new Kr({value:[new Xo({value:"2.16.840.1.101.3.4.1.42"}),new Mi({valueHex:c})]})]})]}),p=new Kr({value:[f,new Mi({valueHex:u})]}).toBER(),y=new Uint8Array(p,0,p.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...jo(y,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
51
- `)}async function y7(r,e){try{let t=await DW(r,e);return tS(t)}catch{}if(!r.includes("BEGIN"))throw new E("Encrypted key was not a libp2p-key or a PEM file");return LW(r,e)}async function DW(r,e){let t=Tt.decode(r);return iu.create().decrypt(t,e)}async function LW(r,e){let t=At.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let i=Ni(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=wg(i),{iv:a,salt:c,iterations:l,keySize:u,cipherText:d}=NW(s),f=await fm(Lo,e,c,{c:l,dkLen:u}),h=await t.subtle.importKey("raw",Ps(f),"AES-CBC",!1,["decrypt"]),p=nh(await t.subtle.decrypt({name:"AES-CBC",iv:Ps(a)},h,Ps(d))),{result:y}=wg(p);n=HI(y)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let i=Ni(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=wg(i);n=HI(s)}else throw new E("Could not parse private key from PEM data");let o=rS(n);if(o.type!=="RSA")throw new E("Could not parse RSA private key from PEM data");return o}function NW(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new E("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 E("Only pkcs5PBKDF2 key derivation functions are supported");let i=n.valueBlock.value[1],s=nh(i.valueBlock.value[0].getValue()),a=1e4,c=32;if(i.valueBlock.value.length===3)a=Number(i.valueBlock.value[1].toBigInt()),c=Number(i.valueBlock.value[2].toBigInt());else if(i.valueBlock.value.length===2)throw new E("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 E("Only AES-CBC encryption schemes are supported")}}}}let d=nh(l.valueBlock.value[1].getValue());return{cipherText:nh(r.valueBlock.value[1].getValue()),salt:s,iterations:a,keySize:c,iv:d}}function HI(r){return nh(r.valueBlock.value[2].getValue())}function nh(r){return new Uint8Array(r,0,r.byteLength)}var OW="/pkcs8/",w7="/info/",oh=new WeakMap,fc={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3};function cu(r){return r==null||typeof r!="string"?!1:r===(0,qI.default)(r.trim())&&r.length>0}async function or(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function hc(r){return new He(OW+r)}function lu(r){return new He(w7+r)}async function BW(r){let e=Ia(r),t=await ct.digest(e);return Ce.encode(t.bytes).substring(1)}var xg=class{components;init;log;self;constructor(e,t){if(this.components=e,this.log=e.logger.forComponent("libp2p:keychain"),this.init={...t,dek:{...l7,...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<fc.minKeyLength)throw new Error(`dek.keyLength must be least ${fc.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<fc.minSaltLength)throw new Error(`dek.saltLength must be least ${fc.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<fc.minIterationCount)throw new Error(`dek.iterationCount must be least ${fc.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?$d(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";oh.set(this,{dek:n})}[Symbol.toStringTag]="@libp2p/keychain";[be]=["@libp2p/keychain"];static generateOptions(){let e=Object.assign({},this.options),t=Math.ceil(fc.minSaltLength/3)*3;return e.dek!=null&&(e.dek.salt=jo(kr(t),"base64")),e}static get options(){return{dek:{...l7}}}async findKeyByName(e){if(!cu(e))throw await or(),new E(`Invalid key name '${e}'`);let t=lu(e);try{let n=await this.components.datastore.get(t);return JSON.parse(jo(n))}catch(n){throw await or(),this.log.error("could not read key from datastore - %e",n),new qe(`Key '${e}' does not exist.`)}}async findKeyById(e){try{let t={prefix:w7};for await(let n of this.components.datastore.query(t)){let o=JSON.parse(jo(n.value));if(o.id===e)return o}throw new E(`Key with id '${e}' does not exist.`)}catch(t){throw await or(),t}}async importKey(e,t){if(!cu(e))throw await or(),new E(`Invalid key name '${e}'`);if(t==null)throw await or(),new E("Key is required");let n=hc(e);if(await this.components.datastore.has(n))throw await or(),new E(`Key '${e}' already exists`);let i,s;try{i=await BW(t);let l=oh.get(this);if(l==null)throw new E("dek missing");let u=l.dek;s=await g7(t,u,t.type==="RSA"?"pkcs-8":"libp2p-key")}catch(l){throw await or(),l}let a={name:e,id:i},c=this.components.datastore.batch();return c.put(n,Ni(s)),c.put(lu(e),Ni(JSON.stringify(a))),await c.commit(),a}async exportKey(e){if(!cu(e))throw await or(),new E(`Invalid key name '${e}'`);let t=hc(e);try{let n=await this.components.datastore.get(t),o=jo(n),i=oh.get(this);if(i==null)throw new E("dek missing");let s=i.dek;return await y7(o,s)}catch(n){throw await or(),n}}async removeKey(e){if(!cu(e)||e===this.self)throw await or(),new E(`Invalid key name '${e}'`);let t=hc(e),n=await this.findKeyByName(e),o=this.components.datastore.batch();return o.delete(t),o.delete(lu(e)),await o.commit(),n}async listKeys(){let e={prefix:w7},t=[];for await(let n of this.components.datastore.query(e))t.push(JSON.parse(jo(n.value)));return t}async renameKey(e,t){if(!cu(e)||e===this.self)throw await or(),new E(`Invalid old key name '${e}'`);if(!cu(t)||t===this.self)throw await or(),new E(`Invalid new key name '${t}'`);let n=hc(e),o=hc(t),i=lu(e),s=lu(t);if(await this.components.datastore.has(o))throw await or(),new E(`Key '${t}' already exists`);try{let c=await this.components.datastore.get(n),l=await this.components.datastore.get(i),u=JSON.parse(jo(l));u.name=t;let d=this.components.datastore.batch();return d.put(o,c),d.put(s,Ni(JSON.stringify(u))),d.delete(n),d.delete(i),await d.commit(),u}catch(c){throw await or(),c}}async rotateKeychainPass(e,t){if(typeof e!="string")throw await or(),new E(`Invalid old pass type '${typeof e}'`);if(typeof t!="string")throw await or(),new E(`Invalid new pass type '${typeof t}'`);if(t.length<20)throw await or(),new E(`Invalid pass length ${t.length}`);this.log("recreating keychain");let n=oh.get(this);if(n==null)throw new E("dek missing");let o=n.dek;this.init.pass=t;let i=t!=null&&this.init.dek?.salt!=null?$d(t,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";oh.set(this,{dek:i});let s=await this.listKeys();for(let a of s){let c=await this.components.datastore.get(hc(a.name)),l=jo(c),u=await y7(l,o),d=i.toString(),f=await g7(u,d,u.type==="RSA"?"pkcs-8":"libp2p-key"),h=this.components.datastore.batch(),p={name:a.name,id:a.id};h.put(hc(a.name),Ni(f)),h.put(lu(a.name),Ni(JSON.stringify(p))),await h.commit()}this.log("keychain reconstructed")}};function Eg(r={}){return e=>new xg(e,r)}async function b7(r,e={}){let t=e.selfKey??"self",n=Eg(e)({datastore:r,logger:Ol()}),o;return await r.has(new He(`/pkcs8/${t}`))?o=await n.exportKey(t):(o=await um(e.keyType??"Ed25519"),await n.importKey(t,o)),o}var uu=!!globalThis.process?.env?.DUMP_SESSION_KEYS,x7=16;function MW(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function vg(r){if(typeof r!="boolean")throw new TypeError(`boolean expected, not ${r}`)}function du(r){if(typeof r!="number")throw new TypeError("number expected, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError("positive integer expected, got "+r)}function Ot(r,e,t=""){let n=MW(r),o=r?.length,i=e!==void 0;if(!n||i&&o!==e){let s=t&&`"${t}" `,a=i?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function E7(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 VI(r,e,t=!1){Ot(r,void 0,"output");let n=e.outputLen;if(r.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(t&&!fu(r))throw new Error("invalid output, must be aligned")}function Zo(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function xo(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function FW(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var pc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,UW=r=>r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255;var $W=r=>{for(let e=0;e<r.length;e++)r[e]=UW(r[e]);return r},qi=pc?r=>r:$W;function KI(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function zI(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 GI(r,e,t){let n=e,o=t||(()=>[]),i=(a,c)=>n(c,...o(a)).update(a).digest(),s=n(new Uint8Array(r),...o(new Uint8Array(0)));return i.outputLen=s.outputLen,i.blockLen=s.blockLen,i.create=(a,...c)=>n(a,...c),i}var WI=(r,e)=>{function t(n,...o){if(Ot(n,void 0,"key"),r.nonceLength!==void 0){let u=o[0];Ot(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let i=r.tagLength;i&&o[1]!==void 0&&Ot(o[1],void 0,"AAD");let s=e(n,...o),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");Ot(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ot(u),a(s.encrypt.length,d),s.encrypt(u,d)},decrypt(u,d){if(Ot(u),i&&u.length<i)throw new Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,d),s.decrypt(u,d)}}}return Object.assign(t,r),t};function ih(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(Ot(e,void 0,"output"),e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!fu(e))throw new Error("invalid output, must be aligned");return e}function jI(r,e,t){du(r),du(e),vg(t);let n=new Uint8Array(16),o=FW(n);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(r),t),n}function fu(r){return r.byteOffset%4===0}function hu(r){return Uint8Array.from(Ot(r))}var XI=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),HW=qi(Zo(XI("expand 16-byte k"))),qW=qi(Zo(XI("expand 32-byte k")));function Te(r,e){return r<<e|r>>>32-e}var sh=64,VW=16,v7=2**32-1,YI=Uint32Array.of();function KW(r,e,t,n,o,i,s,a){let c=o.length,l=new Uint8Array(sh),u=Zo(l),d=pc&&fu(o)&&fu(i),f=d?Zo(o):YI,h=d?Zo(i):YI;if(!pc){for(let p=0;p<c;s++){if(r(e,t,n,u,s,a),qi(u),s>=v7)throw new Error("arx: counter overflow");let y=Math.min(sh,c-p);for(let g=0,m;g<y;g++)m=p+g,i[m]=o[m]^l[g];p+=y}return}for(let p=0;p<c;s++){if(r(e,t,n,u,s,a),s>=v7)throw new Error("arx: counter overflow");let y=Math.min(sh,c-p);if(d&&y===sh){let g=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let m=0,b;m<VW;m++)b=g+m,h[b]=f[b]^u[m];p+=sh;continue}for(let g=0,m;g<y;g++)m=p+g,i[m]=o[m]^l[g];p+=y}}function QI(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:i,rounds:s}=KI({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return du(o),du(s),vg(i),vg(t),(a,c,l,u,d=0)=>{Ot(a,void 0,"key"),Ot(c,void 0,"nonce"),Ot(l,void 0,"data");let f=l.length;if(u=ih(f,u,!1),du(d),d<0||d>=v7)throw new Error("arx: counter overflow");let h=[],p=a.length,y,g;if(p===32)h.push(y=hu(a)),g=qW;else if(p===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),g=HW,h.push(y);else throw Ot(a,32,"arx key"),new Error("invalid key size");(!pc||!fu(c))&&h.push(c=hu(c));let m=Zo(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let R=c.subarray(0,16);if(pc)n(g,m,Zo(R),m);else{let D=qi(Uint32Array.from(g));n(D,m,Zo(R),m),xo(D),qi(m)}c=c.subarray(16)}else pc||qi(m);let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let R=new Uint8Array(12);R.set(c,i?0:12-c.length),c=R,h.push(c)}let _=qi(Zo(c));try{return KW(r,g,m,_,l,u,d,s),u}finally{xo(...h)}}}function ir(r,e){return r[e++]&255|(r[e++]&255)<<8}var S7=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=hu(Ot(e,32,"key"));let t=ir(e,0),n=ir(e,2),o=ir(e,4),i=ir(e,6),s=ir(e,8),a=ir(e,10),c=ir(e,12),l=ir(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=ir(e,16+2*u)}process(e,t,n=!1){let o=n?0:2048,{h:i,r:s}=this,a=s[0],c=s[1],l=s[2],u=s[3],d=s[4],f=s[5],h=s[6],p=s[7],y=s[8],g=s[9],m=ir(e,t+0),b=ir(e,t+2),_=ir(e,t+4),R=ir(e,t+6),D=ir(e,t+8),O=ir(e,t+10),U=ir(e,t+12),C=ir(e,t+14),L=i[0]+(m&8191),H=i[1]+((m>>>13|b<<3)&8191),M=i[2]+((b>>>10|_<<6)&8191),x=i[3]+((_>>>7|R<<9)&8191),A=i[4]+((R>>>4|D<<12)&8191),T=i[5]+(D>>>1&8191),v=i[6]+((D>>>14|O<<2)&8191),S=i[7]+((O>>>11|U<<5)&8191),P=i[8]+((U>>>8|C<<8)&8191),B=i[9]+(C>>>5|o),I=0,q=I+L*a+H*(5*g)+M*(5*y)+x*(5*p)+A*(5*h);I=q>>>13,q&=8191,q+=T*(5*f)+v*(5*d)+S*(5*u)+P*(5*l)+B*(5*c),I+=q>>>13,q&=8191;let V=I+L*c+H*a+M*(5*g)+x*(5*y)+A*(5*p);I=V>>>13,V&=8191,V+=T*(5*h)+v*(5*f)+S*(5*d)+P*(5*u)+B*(5*l),I+=V>>>13,V&=8191;let Z=I+L*l+H*c+M*a+x*(5*g)+A*(5*y);I=Z>>>13,Z&=8191,Z+=T*(5*p)+v*(5*h)+S*(5*f)+P*(5*d)+B*(5*u),I+=Z>>>13,Z&=8191;let fe=I+L*u+H*l+M*c+x*a+A*(5*g);I=fe>>>13,fe&=8191,fe+=T*(5*y)+v*(5*p)+S*(5*h)+P*(5*f)+B*(5*d),I+=fe>>>13,fe&=8191;let ce=I+L*d+H*u+M*l+x*c+A*a;I=ce>>>13,ce&=8191,ce+=T*(5*g)+v*(5*y)+S*(5*p)+P*(5*h)+B*(5*f),I+=ce>>>13,ce&=8191;let Fe=I+L*f+H*d+M*u+x*l+A*c;I=Fe>>>13,Fe&=8191,Fe+=T*a+v*(5*g)+S*(5*y)+P*(5*p)+B*(5*h),I+=Fe>>>13,Fe&=8191;let Ue=I+L*h+H*f+M*d+x*u+A*l;I=Ue>>>13,Ue&=8191,Ue+=T*c+v*a+S*(5*g)+P*(5*y)+B*(5*p),I+=Ue>>>13,Ue&=8191;let $e=I+L*p+H*h+M*f+x*d+A*u;I=$e>>>13,$e&=8191,$e+=T*l+v*c+S*a+P*(5*g)+B*(5*y),I+=$e>>>13,$e&=8191;let _e=I+L*y+H*p+M*h+x*f+A*d;I=_e>>>13,_e&=8191,_e+=T*u+v*l+S*c+P*a+B*(5*g),I+=_e>>>13,_e&=8191;let tt=I+L*g+H*y+M*p+x*h+A*f;I=tt>>>13,tt&=8191,tt+=T*d+v*u+S*l+P*c+B*a,I+=tt>>>13,tt&=8191,I=(I<<2)+I|0,I=I+q|0,q=I&8191,I=I>>>13,V+=I,i[0]=q,i[1]=V,i[2]=Z,i[3]=fe,i[4]=ce,i[5]=Fe,i[6]=Ue,i[7]=$e,i[8]=_e,i[9]=tt}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let i=(o^1)-1;for(let a=0;a<10;a++)n[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let s=e[0]+t[0];e[0]=s&65535;for(let a=1;a<8;a++)s=(e[a]+t[a]|0)+(s>>>16)|0,e[a]=s&65535;xo(n)}update(e){E7(this),Ot(e),e=hu(e);let{buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);if(s===n){for(;n<=o-i;i+=n)this.process(e,i);continue}t.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,xo(this.h,this.r,this.buffer,this.pad)}digestInto(e){E7(this),VI(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let s=0;s<8;s++)e[i++]=n[s]>>>0,e[i++]=n[s]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},ZI=GI(32,r=>new S7(r));function zW(r,e,t,n,o,i=20){let s=r[0],a=r[1],c=r[2],l=r[3],u=e[0],d=e[1],f=e[2],h=e[3],p=e[4],y=e[5],g=e[6],m=e[7],b=o,_=t[0],R=t[1],D=t[2],O=s,U=a,C=c,L=l,H=u,M=d,x=f,A=h,T=p,v=y,S=g,P=m,B=b,I=_,q=R,V=D;for(let fe=0;fe<i;fe+=2)O=O+H|0,B=Te(B^O,16),T=T+B|0,H=Te(H^T,12),O=O+H|0,B=Te(B^O,8),T=T+B|0,H=Te(H^T,7),U=U+M|0,I=Te(I^U,16),v=v+I|0,M=Te(M^v,12),U=U+M|0,I=Te(I^U,8),v=v+I|0,M=Te(M^v,7),C=C+x|0,q=Te(q^C,16),S=S+q|0,x=Te(x^S,12),C=C+x|0,q=Te(q^C,8),S=S+q|0,x=Te(x^S,7),L=L+A|0,V=Te(V^L,16),P=P+V|0,A=Te(A^P,12),L=L+A|0,V=Te(V^L,8),P=P+V|0,A=Te(A^P,7),O=O+M|0,V=Te(V^O,16),S=S+V|0,M=Te(M^S,12),O=O+M|0,V=Te(V^O,8),S=S+V|0,M=Te(M^S,7),U=U+x|0,B=Te(B^U,16),P=P+B|0,x=Te(x^P,12),U=U+x|0,B=Te(B^U,8),P=P+B|0,x=Te(x^P,7),C=C+A|0,I=Te(I^C,16),T=T+I|0,A=Te(A^T,12),C=C+A|0,I=Te(I^C,8),T=T+I|0,A=Te(A^T,7),L=L+H|0,q=Te(q^L,16),v=v+q|0,H=Te(H^v,12),L=L+H|0,q=Te(q^L,8),v=v+q|0,H=Te(H^v,7);let Z=0;n[Z++]=s+O|0,n[Z++]=a+U|0,n[Z++]=c+C|0,n[Z++]=l+L|0,n[Z++]=u+H|0,n[Z++]=d+M|0,n[Z++]=f+x|0,n[Z++]=h+A|0,n[Z++]=p+T|0,n[Z++]=y+v|0,n[Z++]=g+S|0,n[Z++]=m+P|0,n[Z++]=b+B|0,n[Z++]=_+I|0,n[Z++]=R+q|0,n[Z++]=D+V|0}var GW=QI(zW,{counterRight:!1,counterLength:4,allowShortKeys:!1});var WW=new Uint8Array(16),JI=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(WW.subarray(t))},jW=new Uint8Array(32);function ek(r,e,t,n,o){o!==void 0&&Ot(o,void 0,"AAD");let i=r(e,t,jW),s=jI(n.length,o?o.length:0,!0),a=ZI.create(i);o&&JI(a,o),JI(a,n),a.update(s);let c=a.digest();return xo(i,s),c}var YW=r=>(e,t,n)=>({encrypt(i,s){let a=i.length;s=ih(a+16,s,!1),s.set(i);let c=s.subarray(0,-16);r(e,t,c,c,1);let l=ek(r,e,t,c,n);return s.set(l,a),xo(l),s},decrypt(i,s){s=ih(i.length-16,s,!1);let a=i.subarray(0,-16),c=i.subarray(-16),l=ek(r,e,t,a,n);if(!zI(c,l))throw xo(l),new Error("invalid tag");return s.set(i.subarray(0,-16)),r(e,t,s,s,1),xo(l),s}}),A7=WI({blockSize:64,nonceLength:12,tagLength:16},YW(GW));function rk(r,e,t){return di(r),t===void 0&&(t=new Uint8Array(r.outputLen)),Ca(r,t,e)}var T7=Uint8Array.of(0),tk=Uint8Array.of();function nk(r,e,t,n=32){di(r),Ur(n,"length"),Xt(e,void 0,"prk");let o=r.outputLen;if(e.length<o)throw new Error('"prk" must be at least HashLen octets');if(n>255*o)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(n/o);t===void 0?t=tk:Xt(t,void 0,"info");let s=new Uint8Array(i*o),a=Ca.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<i;u++)T7[0]=u+1,c.update(u===0?tk:l).update(t).update(T7).digestInto(l),s.set(l,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),cr(l,T7),s.slice(0,n)}var _7={hashSHA256(r){return Bn(r.subarray())},getHKDF(r,e){let t=rk(Bn,e,r),o=nk(Bn,t,void 0,96),i=o.subarray(0,32),s=o.subarray(32,64),a=o.subarray(64,96);return[i,s,a]},generateX25519KeyPair(){let r=_d.utils.randomSecretKey();return{publicKey:_d.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:_d.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return _d.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return A7(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return A7(n,e,t).decrypt(r.subarray(),o)}};var ok=_7;function ik(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var pu=r=>{let e=nt(2);return e[0]=r>>8,e[1]=r,e};pu.bytes=2;var mu=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};mu.bytes=2;function sk(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function C7(r,e){!e.enabled||!uu||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${de(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${de(r.privateKey,"hex")}`)):e("Missing local static keys."))}function I7(r,e){!e.enabled||!uu||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${de(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${de(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function ak(r,e){!e.enabled||!uu||e(r?`REMOTE_STATIC_PUBLIC_KEY ${de(r.subarray(),"hex")}`:"Missing remote static public key.")}function k7(r,e){!e.enabled||!uu||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${de(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function R7(r,e,t){!t.enabled||!uu||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&de(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&de(e.k,"hex")}`))}var gu=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var QW=0,ZW=4294967295,JW="Cipherstate has reached maximum n, a new handshake must be performed",Sg=class{n;bytes;view;constructor(e=QW){this.n=e,this.bytes=rt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>ZW)throw new Error(JW)}};var mc=rt(0),yu=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new Sg(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let o=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},P7=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=K(t,"utf-8");this.h=ej(e,n),this.ck=this.h,this.cs=new yu(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new yu(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new G(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,mc);return[new yu(this.crypto,e),new yu(this.crypto,t)]}},D7=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:o,initiator:i,s,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new P7(t,n),this.ss.mixHash(o),this.initiator=i,this.s=s,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let o=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},ah=class extends D7{writeMessageA(e){return new G(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new G(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new G(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new gu(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new gu(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new gu(`handshake stage 2 validation fail: ${t.message}`)}}};function ej(r,e){if(e.length<=32){let t=rt(32);return t.set(e),t}else return r.hash(e)}var L7=new Float32Array([-0]),Ds=new Uint8Array(L7.buffer);function ck(r,e,t){L7[0]=r,e[t]=Ds[0],e[t+1]=Ds[1],e[t+2]=Ds[2],e[t+3]=Ds[3]}function lk(r,e){return Ds[0]=r[e],Ds[1]=r[e+1],Ds[2]=r[e+2],Ds[3]=r[e+3],L7[0]}var N7=new Float64Array([-0]),wr=new Uint8Array(N7.buffer);function uk(r,e,t){N7[0]=r,e[t]=wr[0],e[t+1]=wr[1],e[t+2]=wr[2],e[t+3]=wr[3],e[t+4]=wr[4],e[t+5]=wr[5],e[t+6]=wr[6],e[t+7]=wr[7]}function dk(r,e){return wr[0]=r[e],wr[1]=r[e+1],wr[2]=r[e+2],wr[3]=r[e+3],wr[4]=r[e+4],wr[5]=r[e+5],wr[6]=r[e+6],wr[7]=r[e+7],N7[0]}var tj=BigInt(Number.MAX_SAFE_INTEGER),rj=BigInt(Number.MIN_SAFE_INTEGER),wn=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 gc;if(e<tj&&e>rj)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>fk&&(o=0n,++n>fk&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return gc;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):gc}},gc=new wn(0,0);gc.toBigInt=function(){return 0n};gc.zzEncode=gc.zzDecode=function(){return this};gc.length=function(){return 1};var fk=4294967296n;function hk(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 pk(r,e,t){if(t-e<1)return"";let o,i=[],s=0,a;for(;e<t;)a=r[e++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(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,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function O7(r,e,t){let n=t,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,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 Eo(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ag(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var B7=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,Eo(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 Eo(this,4);return Ag(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Eo(this,4);return Ag(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Eo(this,4);let e=lk(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Eo(this,4);let e=dk(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 Eo(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return pk(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Eo(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Eo(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 wn(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 Eo(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 Eo(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 Eo(this,8);let e=Ag(this.buf,this.pos+=4),t=Ag(this.buf,this.pos+=4);return new wn(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=kd(this.buf,this.pos);return this.pos+=ye(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 M7(r){return new B7(r instanceof Uint8Array?r:r.subarray())}function Tg(r,e,t){let n=M7(r);return e.decode(n,void 0,t)}function F7(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return nt(s);o+s>e&&(n=nt(e),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var yc=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function U7(){}var H7=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},nj=F7();function oj(r){return globalThis.Buffer!=null?nt(r):nj(r)}var lh=class{len;head;tail;states;constructor(){this.len=0,this.head=new yc(U7,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new yc(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new q7((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(_g,10,wn.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=wn.fromBigInt(e);return this._push(_g,t.length(),t)}uint64Number(e){return this._push(Id,ye(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=wn.fromBigInt(e).zzEncode();return this._push(_g,t.length(),t)}sint64Number(e){let t=wn.fromNumber(e).zzEncode();return this._push(_g,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push($7,1,e?1:0)}fixed32(e){return this._push(ch,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=wn.fromBigInt(e);return this._push(ch,4,t.lo)._push(ch,4,t.hi)}fixed64Number(e){let t=wn.fromNumber(e);return this._push(ch,4,t.lo)._push(ch,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(ck,4,e)}double(e){return this._push(uk,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push($7,1,0):this.uint32(t)._push(sj,t,e)}string(e){let t=hk(e);return t!==0?this.uint32(t)._push(O7,t,e):this._push($7,1,0)}fork(){return this.states=new H7(this),this.head=this.tail=new yc(U7,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 yc(U7,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=oj(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function $7(r,e,t){e[t]=r&255}function ij(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var q7=class extends yc{next;constructor(e,t){super(ij,e,t),this.next=void 0}};function _g(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 ch(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 sj(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(lh.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(aj,e,r),this},lh.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(cj,e,r),this});function aj(r,e,t){e.set(r,t)}function cj(r,e,t){r.length<40?O7(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(K(r),t)}function V7(){return new lh}function Cg(r,e){let t=V7();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var uh;(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"})(uh||(uh={}));function K7(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Ig(r,e){return K7("message",uh.LENGTH_DELIMITED,r,e)}var dh=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var kg;(function(r){let e;r.codec=()=>(e==null&&(e=Ig((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let i of t.webtransportCerthashes)n.uint32(10),n.bytes(i);if(t.streamMuxers!=null)for(let i of t.streamMuxers)n.uint32(18),n.string(i);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={webtransportCerthashes:[],streamMuxers:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&i.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new dh('Decode error - map field "webtransportCerthashes" had too many elements');i.webtransportCerthashes.push(t.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&i.streamMuxers.length===o.limits.streamMuxers)throw new dh('Decode error - map field "streamMuxers" had too many elements');i.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Cg(t,r.codec()),r.decode=(t,n)=>Tg(t,r.codec(),n)})(kg||(kg={}));var fh;(function(r){let e;r.codec=()=>(e==null&&(e=Ig((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),kg.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={identityKey:rt(0),identitySig:rt(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.identityKey=t.bytes();break}case 2:{i.identitySig=t.bytes();break}case 4:{i.extensions=kg.codec().decode(t,t.uint32(),{limits:o.limits?.extensions});break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Cg(t,r.codec()),r.decode=(t,n)=>Tg(t,r.codec(),n)})(fh||(fh={}));async function G7(r,e,t){let n=await r.sign(yk(e));return fh.encode({identityKey:Ht(r.publicKey),identitySig:n,extensions:t})}async function W7(r,e,t){try{let n=fh.decode(r),o=Et(n.identityKey);if(t?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let i=yk(e);if(!await o.verify(i,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Ap(n.message)}}function yk(r){let e=K("noise-libp2p-static-key:");return r instanceof Uint8Array?Ln([e,r],e.length+r.length):(r.prepend(e),r)}var z7=class extends hs{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new Gm({lengthDecoder:mu,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);let i=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",i);let s=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",s);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let t=new G;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let i;e instanceof Uint8Array?i=this.handshake.encrypt(e.subarray(n,o)):i=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),t.append(pu(i.byteLength)),t.append(i)}return t}decrypt(e){let t=new G;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-x7<n)throw new Error("Invalid chunk");let i;e instanceof Uint8Array?i=e.subarray(n,o):i=e.sublist(n,o);let s=e.subarray(n,o-x7);try{let a=this.handshake.decrypt(i,s);this.metrics?.decryptedPackets.increment(),t.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function j7(r,e,t){return new z7(r,e,t)}async function wk(r,e){let{log:t,connection:n,crypto:o,privateKey:i,prologue:s,s:a,remoteIdentityKey:c,extensions:l}=r,u=await G7(i,a.publicKey,l),d=new ah({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:s,s:a});C7(d.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(d.writeMessageA(mc),e),t.trace("Stage 0 - Initiator finished sending first message."),I7(d.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let f=d.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),k7(d.re,t),ak(d.rs,t),t.trace("Initiator going to check remote's signature...");let h=await W7(f,d.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(d.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[p,y]=d.ss.split();return R7(p,y,t),{payload:h,encrypt:g=>p.encryptWithAd(mc,g),decrypt:(g,m)=>y.decryptWithAd(mc,g,m)}}async function bk(r,e){let{log:t,connection:n,crypto:o,privateKey:i,prologue:s,s:a,remoteIdentityKey:c,extensions:l}=r,u=await G7(i,a.publicKey,l),d=new ah({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:s,s:a});C7(d.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),k7(d.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(d.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),I7(d.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let f=d.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let h=await W7(f,d.rs,c),[p,y]=d.ss.split();return R7(p,y,t),{payload:h,encrypt:g=>y.encryptWithAd(mc,g),decrypt:(g,m)=>p.decryptWithAd(mc,g,m)}}var Rg=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){let{staticNoiseKey:n,extensions:o,crypto:i,prologueBytes:s}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=i??ok;this.crypto=ik(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?sk(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=s??rt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[be]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,o=ws(e,{lengthEncoder:pu,lengthDecoder:mu,maxDataLength:65535}),i=await this.performHandshakeInitiator(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Et(i.payload.identityKey);return{connection:j7(o.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:zo(s),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let o=t.get(n);if(o!=null)return o}if(e.length)throw new Tp("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=e.log?.newScope("noise")??this.log,o=ws(e,{lengthEncoder:pu,lengthDecoder:mu,maxDataLength:65535}),i=await this.performHandshakeResponder(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Et(i.payload.identityKey);return{connection:j7(o.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:zo(s),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,o,i){let s,a=i?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await wk({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return s}async performHandshakeResponder(e,t,n,o,i){let s,a=i?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await bk({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return s}};function Pg(r={}){return e=>new Rg(e,r)}var dt;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(dt||(dt={}));var Pe;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(Pe||(Pe={}));var lSe=Object.values(Pe).filter(r=>typeof r!="string"),xk=0,Bt;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(Bt||(Bt={}));var Jo=12;var Vi=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function Ek(r){return r?.reason!==null}var bn=class extends Vi{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,Bt.ProtocolError),this.name="InvalidFrameError"}},wu=class extends Vi{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,Bt.ProtocolError),this.name="UnRequestedPingError"}},bu=class extends Vi{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,Bt.ProtocolError),this.name="NotMatchingPingError"}};var Dg=class extends Vi{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,Bt.ProtocolError),this.name="StreamAlreadyExistsError"}},Lg=class extends Vi{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,Bt.ProtocolError),this.name="DecodeInvalidVersionError"}},Ng=class extends Vi{static name="BothClientsError";constructor(e="Both clients"){super(e,Bt.ProtocolError),this.name="BothClientsError"}},xu=class extends Vi{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,Bt.ProtocolError),this.name="ReceiveWindowExceededError"}};var pSe=new Set([bn.name,wu.name,bu.name,Dg.name,Lg.name,Ng.name,xu.name]),ph=256*1024,Og=16*1024*1024;var mh={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:ph,maxStreamWindowSize:Og,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function vk(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new E("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new E("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new E("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new E("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<ph)throw new E("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new E("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new E("MaxStreamWindowSize must be less than equal MAX_UINT32")}function Ak(r){return r.header.type===dt.Data&&r.data!==null}var Sk=2**24;function lj(r){if(r[0]!==xk)throw new bn("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*Sk+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*Sk+(r[9]<<16)+(r[10]<<8)+r[11]}}var Bg=class{buffer;constructor(){this.buffer=new G}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=Jo;if(this.buffer.byteLength<Jo)return;let t=lj(this.buffer.subarray(0,Jo));if(t.type===dt.Data){if(e+=t.length,this.buffer.byteLength<e)return;let n=this.buffer.sublist(Jo,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}};function Y7(r){let e=new Uint8Array(Jo);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}var Mr;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(Mr||(Mr={}));var Mg=class extends ys{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??ph;super({...e,maxMessageSize:t-Jo}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??Og,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let n=()=>{this.state=Mr.Finished};this.addEventListener("close",n)}sendData(e){let t=e.byteLength,n=0,o=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){o=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}let i=Math.min(this.sendWindowCapacity,e.byteLength),s=this.getSendFlags(),a=e.sublist(0,i);e.consume(i);let c=this.sendFrame({type:dt.Data,flag:s,streamID:this.streamId,length:i},a);if(this.sendWindowCapacity-=i,n+=i,!c){o=c,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:o}}sendReset(){this.sendFrame({type:dt.WindowUpdate,flag:Pe.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|Pe.FIN;this.sendFrame({type:dt.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=Mr.Paused}sendResume(){this.state=Mr.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-Jo,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!Ak(e))throw new bn("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new xu("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&Pe.ACK)===Pe.ACK&&this.state===Mr.SYNSent&&(this.state=Mr.Established),(e&Pe.FIN)===Pe.FIN&&this.onRemoteCloseWrite(),(e&Pe.RST)===Pe.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case Mr.Init:return this.state=Mr.SYNSent,Pe.SYN;case Mr.SYNReceived:return this.state=Mr.Established,Pe.ACK;default:return 0}}sendWindowUpdate(){if(this.state===Mr.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>-1&&t-this.epochStart<=n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let o=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:dt.WindowUpdate,flag:e,streamID:this.streamId,length:o})}};function Tk(r){return{type:dt[r.type],flags:[(r.flag&Pe.SYN)===Pe.SYN?"SYN":void 0,(r.flag&Pe.ACK)===Pe.ACK?"ACK":void 0,(r.flag&Pe.FIN)===Pe.FIN?"FIN":void 0,(r.flag&Pe.RST)===Pe.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var _k="/yamux/1.0.0",Fg=class{protocol=_k;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[be]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new X7(e,{...this._init})}},X7=class extends gs{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:_k,name:"yamux"}),this.client=e.direction==="outbound",vk(t),this.enableKeepAlive=t.enableKeepAlive??mh.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??mh.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??mh.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??mh.maxOutboundStreams,this.decoder=new Bg,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=Ml(async n=>{try{await this.ping(n)}catch(o){this.log.error("ping error: %s",o)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new Xn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Xn("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new Kc("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,Mr.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new Xn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Xn("Muxer closed locally");if(this.activePing!=null)return Me(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await Me(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??Bt.NormalTermination;this.log.trace("muxer close reason=%s",Bt[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=Bt.InternalError;Ek(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(this.streams.find(i=>i.streamId===e)!=null)throw new E("Stream already exists with that id");let o=new Mg({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return o.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),o}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:n,length:o}=e.header;if(this.log.trace("received frame %o",Tk(e.header)),t===0)switch(n){case dt.Ping:{this.handlePing(e.header);return}case dt.GoAway:{this.handleGoAway(o);return}default:throw new bn("Invalid frame type")}else switch(e.header.type){case dt.Data:case dt.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new bn("Invalid frame type")}}handlePing(e){if(e.flag===Pe.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,Pe.ACK);else if(e.flag===Pe.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new bn("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new wu("ping not requested");if(this.activePing.id!==e)throw new bu("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",Bt[e]??"unknown"),this.remoteGoAway=e,e===Bt.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:n,type:o}=e.header;(n&Pe.SYN)===Pe.SYN&&this.incomingStream(t);let i=this.streams.find(s=>s.streamId===t);if(i===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(o){case dt.WindowUpdate:{i.handleWindowUpdate(e);return}case dt.Data:{i.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new E("Both endpoints are clients");if(this.streams.find(n=>n.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:dt.WindowUpdate,flag:Pe.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:dt.WindowUpdate,flag:Pe.RST,streamID:e,length:0});return}let t=this._newStream(e,Mr.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===dt.Data){if(t==null)throw new bn("Invalid frame");n=new G(Y7(e),t)}else n=Y7(e);return this.log.trace("sending frame %o",Tk(e)),this.send(n)}sendPing(e,t=Pe.SYN){t===Pe.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:dt.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=Bt.NormalTermination){this.log("sending GoAway reason=%s",Bt[e]),this.localGoAway=e,this.sendFrame({type:dt.GoAway,flag:0,streamID:0,length:e})}};function Ck(r={}){return()=>new Fg(r)}var Ik="libp2p",kk="autonat",Rk="1.0.0";var Je;(function(r){let e;(function(f){f.DIAL="DIAL",f.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(f){f[f.DIAL=0]="DIAL",f[f.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),(function(f){f.codec=()=>Ye(t)})(e=r.MessageType||(r.MessageType={}));let n;(function(f){f.OK="OK",f.E_DIAL_ERROR="E_DIAL_ERROR",f.E_DIAL_REFUSED="E_DIAL_REFUSED",f.E_BAD_REQUEST="E_BAD_REQUEST",f.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let o;(function(f){f[f.OK=0]="OK",f[f.E_DIAL_ERROR=100]="E_DIAL_ERROR",f[f.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",f[f.E_BAD_REQUEST=200]="E_BAD_REQUEST",f[f.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(o||(o={})),(function(f){f.codec=()=>Ye(o)})(n=r.ResponseStatus||(r.ResponseStatus={}));let i;(function(f){let h;f.codec=()=>(h==null&&(h=re((m,b,_={})=>{if(_.lengthDelimited!==!1&&b.fork(),m.id!=null&&(b.uint32(10),b.bytes(m.id)),m.addrs!=null&&m.addrs.length>0)for(let R of m.addrs)b.uint32(18),b.bytes(R);_.lengthDelimited!==!1&&b.ldelim()},(m,b,_={})=>{let R={addrs:[]},D=b==null?m.len:m.pos+b;for(;m.pos<D;){let O=m.uint32();switch(O>>>3){case 1:{R.id=m.bytes();break}case 2:{if(_.limits?.addrs!=null&&R.addrs.length===_.limits.addrs)throw new le('Decode error - repeated field "addrs" had too many elements');R.addrs.push(m.bytes());break}default:{m.skipType(O&7);break}}}return R},function*(m,b,_,R={}){let D={addrs:0},O=b==null?m.len:m.pos+b;for(;m.pos<O;){let U=m.uint32();switch(U>>>3){case 1:{yield{field:`${_}.id`,value:m.bytes()};break}case 2:{if(R.limits?.addrs!=null&&D.addrs===R.limits.addrs)throw new le('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${_}.addrs[]`,index:D.addrs,value:m.bytes()},D.addrs++;break}default:{m.skipType(U&7);break}}}})),h);function p(m){return ee(m,f.codec())}f.encode=p;function y(m,b){return J(m,f.codec(),b)}f.decode=y;function g(m,b){return te(m,f.codec(),b)}f.stream=g})(i=r.PeerInfo||(r.PeerInfo={}));let s;(function(f){let h;f.codec=()=>(h==null&&(h=re((m,b,_={})=>{_.lengthDelimited!==!1&&b.fork(),m.peer!=null&&(b.uint32(10),r.PeerInfo.codec().encode(m.peer,b)),_.lengthDelimited!==!1&&b.ldelim()},(m,b,_={})=>{let R={},D=b==null?m.len:m.pos+b;for(;m.pos<D;){let O=m.uint32();O>>>3===1?R.peer=r.PeerInfo.codec().decode(m,m.uint32(),{limits:_.limits?.peer}):m.skipType(O&7)}return R},function*(m,b,_,R={}){let D=b==null?m.len:m.pos+b;for(;m.pos<D;){let O=m.uint32();O>>>3===1?yield*r.PeerInfo.codec().stream(m,m.uint32(),`${_}.peer`,{limits:R.limits?.peer}):m.skipType(O&7)}})),h);function p(m){return ee(m,f.codec())}f.encode=p;function y(m,b){return J(m,f.codec(),b)}f.decode=y;function g(m,b){return te(m,f.codec(),b)}f.stream=g})(s=r.Dial||(r.Dial={}));let a;(function(f){let h;f.codec=()=>(h==null&&(h=re((m,b,_={})=>{_.lengthDelimited!==!1&&b.fork(),m.status!=null&&(b.uint32(8),r.ResponseStatus.codec().encode(m.status,b)),m.statusText!=null&&(b.uint32(18),b.string(m.statusText)),m.addr!=null&&(b.uint32(26),b.bytes(m.addr)),_.lengthDelimited!==!1&&b.ldelim()},(m,b,_={})=>{let R={},D=b==null?m.len:m.pos+b;for(;m.pos<D;){let O=m.uint32();switch(O>>>3){case 1:{R.status=r.ResponseStatus.codec().decode(m);break}case 2:{R.statusText=m.string();break}case 3:{R.addr=m.bytes();break}default:{m.skipType(O&7);break}}}return R},function*(m,b,_,R={}){let D=b==null?m.len:m.pos+b;for(;m.pos<D;){let O=m.uint32();switch(O>>>3){case 1:{yield{field:`${_}.status`,value:r.ResponseStatus.codec().decode(m)};break}case 2:{yield{field:`${_}.statusText`,value:m.string()};break}case 3:{yield{field:`${_}.addr`,value:m.bytes()};break}default:{m.skipType(O&7);break}}}})),h);function p(m){return ee(m,f.codec())}f.encode=p;function y(m,b){return J(m,f.codec(),b)}f.decode=y;function g(m,b){return te(m,f.codec(),b)}f.stream=g})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=re((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.type!=null&&(h.uint32(8),r.MessageType.codec().encode(f.type,h)),f.dial!=null&&(h.uint32(18),r.Dial.codec().encode(f.dial,h)),f.dialResponse!=null&&(h.uint32(26),r.DialResponse.codec().encode(f.dialResponse,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={},g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{y.type=r.MessageType.codec().decode(f);break}case 2:{y.dial=r.Dial.codec().decode(f,f.uint32(),{limits:p.limits?.dial});break}case 3:{y.dialResponse=r.DialResponse.codec().decode(f,f.uint32(),{limits:p.limits?.dialResponse});break}default:{f.skipType(m&7);break}}}return y},function*(f,h,p,y={}){let g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.type`,value:r.MessageType.codec().decode(f)};break}case 2:{yield*r.Dial.codec().stream(f,f.uint32(),`${p}.dial`,{limits:y.limits?.dial});break}case 3:{yield*r.DialResponse.codec().stream(f,f.uint32(),`${p}.dialResponse`,{limits:y.limits?.dialResponse});break}default:{f.skipType(m&7);break}}}})),c);function l(f){return ee(f,r.codec())}r.encode=l;function u(f,h){return J(f,r.codec(),h)}r.decode=u;function d(f,h){return te(f,r.codec(),h)}r.stream=d})(Je||(Je={}));var mj=4,gj=8,Ug=class{components;protocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;started;log;topologyId;dialResults;findPeers;addressFilter;connectionThreshold;constructor(e,t){this.components=e,this.log=e.logger.forComponent("libp2p:auto-nat"),this.started=!1,this.protocol=`/${t.protocolPrefix??Ik}/${kk}/${Rk}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??20,this.connectionThreshold=t.connectionThreshold??80,this.maxMessageSize=t.maxMessageSize??8192,this.dialResults=_t({name:"libp2p_autonat_dial_results",metrics:e.metrics}),this.findPeers=Ml(this.findRandomPeers.bind(this),6e4),this.addressFilter=Lt(1024)}[Symbol.toStringTag]="@libp2p/autonat";[be]=["@libp2p/autonat"];get[Zr](){return["@libp2p/identify"]}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,(e,t)=>{this.handleIncomingAutonatStream(e,t).catch(n=>{this.log.error("error handling incoming autonat stream - %e",n)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.topologyId=await this.components.registrar.register(this.protocol,{onConnect:(e,t)=>{this.verifyExternalAddresses(t).catch(n=>{this.log.error("could not verify addresses - %e",n)})}}),this.findPeers.start(),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.topologyId!=null&&await this.components.registrar.unhandle(this.topologyId),this.dialResults.clear(),this.findPeers.stop(),this.started=!1}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every(e=>e.expires>Date.now()?!0:e.verified)}async findRandomPeers(e){if(this.allAddressesAreVerified())return;let t=ae([AbortSignal.timeout(1e4),e?.signal]);try{this.log("starting random walk to find peers to run AutoNAT");for await(let n of this.components.randomWalk.walk({signal:t})){if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable %s",n.id,n.multiaddrs.map(o=>o.toString()).join(", "));continue}try{this.log.trace("dial random peer %p",n.id),await this.components.connectionManager.openConnection(n.multiaddrs,{signal:t})}catch{}if(this.allAddressesAreVerified()){this.log("stopping random walk, all addresses are verified");return}if(!this.hasConnectionCapacity()){this.log("stopping random walk, too close to max connections");return}}}catch{}}async handleIncomingAutonatStream(e,t){let n=AbortSignal.timeout(this.timeout);try{let o=Xe(e,{maxDataLength:this.maxMessageSize}).pb(Je),i=await o.read({signal:n}),s=await this.handleAutonatMessage(i,t,{signal:n});await o.write(s,{signal:n}),await e.close({signal:n})}catch(o){this.log.error("error handling incoming autonat stream - %e",o),e.abort(o)}}async handleAutonatMessage(e,t,n){let o=this.components.addressManager.getAddresses().map(d=>ie(d).host),i=e.dial;if(i==null)return this.log.error("dial was missing from message"),{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}};let s,a=i.peer;if(a?.id==null)return this.log.error("peerId missing from message"),{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}};try{let d=xe(a.id);s=bt(d)}catch(d){return this.log.error("invalid PeerId - %e",d),{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}}}if(this.log("incoming request from %p",s),!t.remotePeer.equals(s))return this.log("target peer %p did not equal sending peer %p",s,t.remotePeer),{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}};let c=a.addrs.map(d=>j(d)).filter(d=>{try{let f=ie(d);return wt(d)?!1:f.host!==ie(t.remoteAddr).host?(this.log.trace("not dialing %a - target host did not match remote host %a",d,t.remoteAddr),!1):o.includes(f.host)?!1:this.components.transportManager.dialTransportForMultiaddr(d)==null?(this.log.trace("not dialing %a - transport unsupported",d),!1):!0}catch{return!1}}).map(d=>(d.getComponents().find(f=>f.code===421)?.value==null&&(d=d.encapsulate(`/p2p/${s.toString()}`)),d));if(c.length===0)return this.log("refused to dial all multiaddrs for %p from message",s),{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}};this.log("dial multiaddrs %s for peer %p",c.map(d=>d.toString()).join(", "),s);let l="",u=c[0];for(let d of c){let f;u=d;try{if(f=await this.components.connectionManager.openConnection(d,n),!f.remoteAddr.equals(d))throw this.log.error("tried to dial %a but dialed %a",d,f.remoteAddr),new Error("Unexpected remote address");return this.log("successfully dialed %p via %a",s,d),{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.OK,addr:f.remoteAddr.decapsulateCode(421).bytes}}}catch(h){this.log.error("could not dial %p - %e",s,h),l=h.message}finally{f!=null&&await f.close()}}return{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.E_DIAL_ERROR,statusText:l,addr:u.bytes}}}getFirstUnverifiedMultiaddr(e,t){let n=this.components.addressManager.getAddressesWithMetadata().sort((o,i)=>o.type==="observed"&&i.type!=="observed"?1:i.type==="observed"&&o.type!=="observed"?-1:0).filter(o=>!(!(o.expires<Date.now())||ie(o.multiaddr).type==="ip6"&&(!t||!ym(o.multiaddr))||wt(o.multiaddr)));for(let o of n){let i=o.multiaddr.toString(),s=this.dialResults.get(i);if(s!=null){if(s.networkSegments.includes(e)){this.log.trace("%a already has a network segment result from %s",s.multiaddr,e);continue}if(s.queue.size>10){this.log.trace("%a already has enough peers queued",s.multiaddr);continue}}if(s==null){let a=o.expires<Date.now();if(a&&this.addressFilter.remove?.(i),this.addressFilter.has(i))continue;this.addressFilter.add(i),this.log.trace("creating dial result %s %s",a?"to revalidate":"for",i),s={multiaddr:o.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:q5(),queue:new Gt({concurrency:3,maxSize:50}),type:o.type,lastVerified:o.lastVerified},this.dialResults.set(i,s)}return s}}removeOutdatedMultiaddrResults(){let e=new Set(this.components.addressManager.getAddressesWithMetadata().filter(({expires:t})=>t<Date.now()).map(({multiaddr:t})=>t.toString()));for(let t of this.dialResults.keys())e.has(t)||(this.log.trace("remove results for %a",t),this.dialResults.delete(t))}async verifyExternalAddresses(e){if(!this.isStarted())return;this.removeOutdatedMultiaddrResults();let n=(await this.components.peerStore.get(e.remotePeer)).addresses.some(({multiaddr:s})=>ie(s).type==="ip6"),o=this.getNetworkSegment(e.remoteAddr),i=this.getFirstUnverifiedMultiaddr(o,n);if(i==null){this.log.trace("no unverified public addresses found for peer %p to verify, not requesting verification",e.remotePeer);return}if(!this.hasConnectionCapacity()){i.lastVerified!=null?(this.log("automatically re-verifying %a because we are too close to the connection limit",i.multiaddr),this.confirmAddress(i)):this.log("skipping verifying %a because we are too close to the connection limit",i.multiaddr);return}i.queue.add(async s=>{await this.askPeerToVerify(e,o,s)},{peerId:e.remotePeer,multiaddr:i.multiaddr}).catch(s=>{i?.result==null&&this.log.error("error from %p verifying address %a - %e",e.remotePeer,i?.multiaddr,s)})}async askPeerToVerify(e,t,n){let o=this.dialResults.get(n.multiaddr.toString());if(o==null){this.log("%a was verified while %p was queued",n.multiaddr,e.remotePeer);return}let i=AbortSignal.timeout(this.timeout);this.log.trace("asking %a to verify multiaddr %s",e.remoteAddr,n.multiaddr);let s=await e.newStream(this.protocol,{signal:i});try{let a=Xe(s).pb(Je),[,c]=await Promise.all([a.write({type:Je.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toMultihash().bytes,addrs:[n.multiaddr.bytes]}}},{signal:i}),a.read({signal:i})]);if(c.type!==Je.MessageType.DIAL_RESPONSE||c.dialResponse==null){this.log("invalid autonat response from %p - %j",e.remotePeer,c);return}let l=c.dialResponse.status;if(this.log.trace("autonat response from %p for %a is %s",e.remotePeer,n.multiaddr,l),l!==Je.ResponseStatus.OK&&l!==Je.ResponseStatus.E_DIAL_ERROR)return;if(o=this.dialResults.get(n.multiaddr.toString()),o==null){this.log.trace("peer reported %a as %s but there is no result object",n.multiaddr,c.dialResponse.status);return}if(o.networkSegments.includes(t)){this.log.trace("%a results included network segment %s",n.multiaddr,t);return}if(o.result!=null){this.log.trace("already resolved result for %a, ignoring response from",n.multiaddr,e.remotePeer);return}if(o.verifyingPeers.has(e.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",e.remotePeer,n.multiaddr);return}if(o.verifyingPeers.add(e.remotePeer),o.networkSegments.push(t),l===Je.ResponseStatus.OK){if(o.success++,o.type!=="observed"){this.confirmAddress(o);return}}else l===Je.ResponseStatus.E_DIAL_ERROR&&o.failure++;this.log("%a success %d failure %d",o.multiaddr,o.success,o.failure),o.success===mj&&this.confirmAddress(o),o.failure===gj&&this.unconfirmAddress(o)}finally{try{await s.close({signal:i})}catch(a){s.abort(a)}}}hasConnectionCapacity(){let t=this.components.connectionManager.getConnections().length,n=this.components.connectionManager.getMaxConnections();return t/n*100<this.connectionThreshold}confirmAddress(e){this.log("%s address %a is externally dialable",e.type,e.multiaddr),this.components.addressManager.confirmObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!0,e.queue.abort()}unconfirmAddress(e){this.log("%s address %a is not externally dialable",e.type,e.multiaddr),this.components.addressManager.removeObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!1,e.queue.abort()}getNetworkSegment(e){let t=ie(e);switch(t.type){case"ip4":return t.host.split(".")[0].padStart(3,"0");case"ip6":return t.host.split(":")[0].padStart(4,"0");default:throw new E(`Remote address ${e} was not an IPv4 or Ipv6 address`)}}};function Pk(r={}){return e=>new Ug(e,r)}var yj="bootstrap",wj=50,bj=1e3,Q7=class extends se{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??bj,this.list=t.list.map(n=>j(n)).filter(n=>Tl.matches(n)?n.getComponents().findLast(i=>i.code===421)?.value==null?(this.log.error("invalid bootstrap multiaddr without peer id"),!1):!0:(this.log.error("invalid multiaddr %a",n),!1)).map(n=>({id:Ee(n.getComponents().findLast(o=>o.code===421)?.value??""),multiaddrs:[n]})),this._init=t}[aa]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[be]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??yj]:{value:this._init.tagValue??wj,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function Dk(r){return e=>new Q7(e,r)}var Z7=1e3,Lk=60*Z7;var pAe=120*Lk,Nk=1,$g=5e3,Ok=100;var gh=`${ca}-circuit-relay`,mAe=2*Lk,gAe=BigInt(1<<17),wc="/libp2p/circuit/relay/0.2.0/hop",J7="/libp2p/circuit/relay/0.2.0/stop",yAe=30*Z7,wAe=30*Z7,eb=300,Bk=4096,Mk=.001;function bc(r=0){return new Uint8Array(r)}function Fk(r=0){return new Uint8Array(r)}var Os;(function(r){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(t||(t={})),(function(a){a.codec=()=>Ye(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=re((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Ls.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),yh.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),Ns.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),Mt.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=Ls.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.reservation=yh.codec().decode(a,a.uint32(),{limits:l.limits?.reservation});break}case 4:{u.limit=Ns.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 5:{u.status=Mt.codec().decode(a);break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*Ls.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*yh.codec().stream(a,a.uint32(),`${l}.reservation`,{limits:u.limits?.reservation});break}case 4:{yield*Ns.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 5:{yield{field:`${l}.status`,value:Mt.codec().decode(a)};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return ee(a,r.codec())}r.encode=o;function i(a,c){return J(a,r.codec(),c)}r.decode=i;function s(a,c){return te(a,r.codec(),c)}r.stream=s})(Os||(Os={}));var ei;(function(r){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(t||(t={})),(function(a){a.codec=()=>Ye(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=re((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Ls.codec().encode(a.peer,c)),a.limit!=null&&(c.uint32(26),Ns.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(32),Mt.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=Ls.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.limit=Ns.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 4:{u.status=Mt.codec().decode(a);break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*Ls.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*Ns.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 4:{yield{field:`${l}.status`,value:Mt.codec().decode(a)};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return ee(a,r.codec())}r.encode=o;function i(a,c){return J(a,r.codec(),c)}r.decode=i;function s(a,c){return te(a,r.codec(),c)}r.stream=s})(ei||(ei={}));var Ls;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.id!=null&&i.id.byteLength>0&&(s.uint32(10),s.bytes(i.id)),i.addrs!=null&&i.addrs.length>0)for(let c of i.addrs)s.uint32(18),s.bytes(c);a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={id:bc(0),addrs:[]},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.id=i.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new le('Decode error - repeated field "addrs" had too many elements');c.addrs.push(i.bytes());break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={addrs:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${a}.id`,value:i.bytes()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new le('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:i.bytes()},l.addrs++;break}default:{i.skipType(d&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Ls||(Ls={}));var yh;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.expire!=null&&i.expire!==0n&&(s.uint32(8),s.uint64(i.expire)),i.addrs!=null&&i.addrs.length>0)for(let c of i.addrs)s.uint32(18),s.bytes(c);i.voucher!=null&&(s.uint32(26),bh.codec().encode(i.voucher,s)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={expire:0n,addrs:[]},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.expire=i.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new le('Decode error - repeated field "addrs" had too many elements');c.addrs.push(i.bytes());break}case 3:{c.voucher=bh.codec().decode(i,i.uint32(),{limits:a.limits?.voucher});break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={addrs:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${a}.expire`,value:i.uint64()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new le('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:i.bytes()},l.addrs++;break}case 3:{yield*bh.codec().stream(i,i.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{i.skipType(d&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(yh||(yh={}));var Ns;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.duration!=null&&(s.uint32(8),s.uint32(i.duration)),i.data!=null&&(s.uint32(16),s.uint64(i.data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.duration=i.uint32();break}case 2:{c.data=i.uint64();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.duration`,value:i.uint32()};break}case 2:{yield{field:`${a}.data`,value:i.uint64()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Ns||(Ns={}));var Mt;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(Mt||(Mt={}));var tb;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(tb||(tb={}));(function(r){r.codec=()=>Ye(tb)})(Mt||(Mt={}));var wh;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.relay!=null&&i.relay.byteLength>0&&(s.uint32(10),s.bytes(i.relay)),i.peer!=null&&i.peer.byteLength>0&&(s.uint32(18),s.bytes(i.peer)),i.expiration!=null&&i.expiration!==0n&&(s.uint32(24),s.uint64(i.expiration)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={relay:bc(0),peer:bc(0),expiration:0n},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.relay=i.bytes();break}case 2:{c.peer=i.bytes();break}case 3:{c.expiration=i.uint64();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.relay`,value:i.bytes()};break}case 2:{yield{field:`${a}.peer`,value:i.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:i.uint64()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(wh||(wh={}));var bh;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.publicKey!=null&&i.publicKey.byteLength>0&&(s.uint32(10),s.bytes(i.publicKey)),i.payloadType!=null&&i.payloadType.byteLength>0&&(s.uint32(18),s.bytes(i.payloadType)),i.payload!=null&&(s.uint32(26),wh.codec().encode(i.payload,s)),i.signature!=null&&i.signature.byteLength>0&&(s.uint32(42),s.bytes(i.signature)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={publicKey:bc(0),payloadType:bc(0),signature:bc(0)},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.publicKey=i.bytes();break}case 2:{c.payloadType=i.bytes();break}case 3:{c.payload=wh.codec().decode(i,i.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:i.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:i.bytes()};break}case 3:{yield*wh.codec().stream(i,i.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(bh||(bh={}));var xh=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Hg=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},qg=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function rb(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var Eh=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},Vg=Be(Ae(Tl.matchers[0],Oe(290))),Kg=Be(Oe(290));function $k(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Uk=$k("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),nb=$k("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=Fk(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),xj={utf8:Uk,"utf-8":Uk,hex:oe.base16,latin1:nb,ascii:nb,binary:nb,...oe},Hk=xj;function qk(r,e="utf8"){let t=Hk[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var zg=class extends se{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(wc,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(wc)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let i=Vk(n),s=Vk(o);return i>s?-1:s>i?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Gt({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p - %e",n.id,o)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,o)})}async dialPeer({peerId:e,signal:t}){let n=ae([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function Vk(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(qk(e)).getTime()}var ob=class extends se{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??$g,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(Kg.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(Vg.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let i=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(i)}}else throw new sa(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>j(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function Kk(r){return new ob(r)}var zk="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Gk=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=zk[t[r]&63];return e};var Ej=60*1e3*10,vj=60*1e3*5,Sj=30*1e3,Gg=class extends se{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new mr,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??Ok,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??$g,this.started=!1,this.relayFilter=Lt(100),this.reserveQueue=new Gt({concurrency:t?.reservationConcurrency??Nk,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(i=>i.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(i=>{this.log("could not remove relay %p - %e",n.detail,i)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(gh)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[gh]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=Gk();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new sa("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new qg("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new sa("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let o=Date.now();try{let i=this.reservations.get(e);if(i!=null){let p=this.connectionManager.getConnections(e),y=!1;if(p.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),p.map(g=>g.id).includes(i.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),y=!0),y&&rb(i.reservation.expire)>Ej)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:i};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new xh("Not making reservation on discovered relay because we do not need any more relays");let s=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(e,{signal:s});if(Kt.matches(a.remoteAddr))throw new Hg("not creating reservation over relayed connection");let c=await this.#e(a,{signal:s}),l=rb(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-vj,Sj),Math.pow(2,31)-1),d=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async p=>{this.log.error("could not refresh reservation to relay %p - %e",e,p),await this.#t(e)}).catch(p=>{this.log.error("could not remove expired reservation to relay %p - %e",e,p)})},u),f;if(t==="discovered"){let p=this.pendingReservations.pop();if(p==null)throw new xh("Made reservation on relay but did not need any more discovered relays");f={timeout:d,reservation:c,type:t,connection:a.id,id:p}}else f={timeout:d,reservation:c,type:t,connection:a.id};this.reservations.set(e,f),await this.peerStore.merge(e,{tags:{[gh]:{value:1,ttl:l}}}),this.#r();let h={relay:e,details:f};return this.safeDispatchEvent("relay:created-reservation",{detail:h}),h}catch(i){throw t==="discovered"&&i.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-o,i),(i.name==="DialError"||i.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(s=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,s)}),i}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(wc,t),i=Xe(n).pb(Os);this.log.trace("send RESERVE to %p",e.remotePeer),await i.write({type:Os.Type.RESERVE},t);let s;try{this.log.trace("reading response from %p",e.remotePeer),s=await i.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",s.status),s.status===Mt.OK&&s.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of s.reservation.addrs){let u=j(l);u.getComponents().find(d=>d.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=j(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return s.reservation.addrs=[...c].map(l=>j(l).bytes),s.reservation}let a=`reservation failed with status ${s.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[gh]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=Lt(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var ib=class extends ps{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function sb(r){return new ib(r)}var Aj=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(j)}catch{return!1}return!0},Wk={maxInboundStopStreams:eb,maxOutboundStopStreams:eb,stopTimeout:3e4},Wg=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??Wk.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Wk.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new zg(e,{filter:t.discoveryFilter??V5(Bk,Mk)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,o)})}),this.reservationStore=new Gg(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[be]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Zr](){return this.discovery!=null?["@libp2p/identify"]:[]}[Xi]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(J7,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await Rt(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Ut(this.discovery,this.reservationStore),await this.components.registrar.unhandle(J7),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),o=j(n[0]),i=j(n[n.length-1]),s=o.getComponents().find(h=>h.code===421)?.value,a=i.getComponents().find(h=>h.code===421)?.value;if(s==null||a==null){let h=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${h}`),new ji(`C${h}`)}let c=Ee(s),l=Ee(a),d=this.components.connectionManager.getConnections(c)[0];d==null?(await this.components.peerStore.merge(c,{multiaddrs:[o]}),t.onProgress?.(new k("circuit-relay:open-connection")),d=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new k("circuit-relay:reuse-connection"));let f;try{t.onProgress?.(new k("circuit-relay:open-hop-stream")),f=await d.newStream(wc,t);let h=Xe(f).pb(Os);t.onProgress?.(new k("circuit-relay:write-connect-message")),await h.write({type:Os.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[j(i).bytes]}},t),t.onProgress?.(new k("circuit-relay:read-connect-response"));let p=await h.read(t);if(p.status!==Mt.OK)throw new he(`failed to connect via relay with status ${p?.status?.toString()??"undefined"}`);let y=new Eh(p.limit),g=sb({stream:h.unwrap().unwrap(),remoteAddr:e,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:y.onData,onDataWrite:y.onData,log:f.log.newScope("circuit-relay:connection")}),m=await this.components.upgrader.upgradeOutbound(g,{...t,limits:y.getLimits()});return m.log("outbound relayed connection established to %p with limits %o, over connection %s",m.remotePeer,p.limit??"none",d.id),m}catch(h){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,h),f?.abort(h),h}}createListener(e){return Kk({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>Vg.exactMatch(t)||Kg.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>Kt.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(d){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",d)}let o=Xe(e).pb(ei),i=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,i.type),i?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:ei.Type.STATUS,status:Mt.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(i.type!==ei.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:ei.Type.STATUS,status:Mt.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!Aj(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:ei.Type.STATUS,status:Mt.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let s=bt(xe(i.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,s)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:ei.Type.STATUS,status:Mt.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:ei.Type.STATUS,status:Mt.OK},{signal:n});let a=new Eh(i.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),l=this.components.addressManager.getAddresses()[0],u=sb({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",s,i.limit??"none",t.id)}finally{n?.clear()}}};function jk(r={}){return e=>new Wg(e,r)}var vo;(function(r){let e;(function(a){a.UNUSED="UNUSED",a.CONNECT="CONNECT",a.SYNC="SYNC"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.UNUSED=0]="UNUSED",a[a.CONNECT=100]="CONNECT",a[a.SYNC=300]="SYNC"})(t||(t={})),(function(a){a.codec=()=>Ye(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=re((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.observedAddresses!=null&&a.observedAddresses.length>0)for(let u of a.observedAddresses)c.uint32(18),c.bytes(u);l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={observedAddresses:[]},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{if(l.limits?.observedAddresses!=null&&u.observedAddresses.length===l.limits.observedAddresses)throw new le('Decode error - repeated field "observedAddresses" had too many elements');u.observedAddresses.push(a.bytes());break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={observedAddresses:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{if(u.limits?.observedAddresses!=null&&d.observedAddresses===u.limits.observedAddresses)throw new le('Streaming decode error - repeated field "observedAddresses" had too many elements');yield{field:`${l}.observedAddresses[]`,index:d.observedAddresses,value:a.bytes()},d.observedAddresses++;break}default:{a.skipType(h&7);break}}}})),n);function o(a){return ee(a,r.codec())}r.encode=o;function i(a,c){return J(a,r.codec(),c)}r.decode=i;function s(a,c){return te(a,r.codec(),c)}r.stream=s})(vo||(vo={}));function ab(r,e){return Kt.matches(r)||e.dialTransportForMultiaddr(r)==null?!1:Dm.matches(r)?!0:YS.matches(r)?!wt(r):!1}var Yk=1024*4,Xk=100,jg={timeout:5e3,retries:3,maxInboundStreams:1,maxOutboundStreams:1},Yg=class{started;timeout;retries;maxInboundStreams;maxOutboundStreams;peerStore;registrar;connectionManager;addressManager;transportManager;topologyId;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:dcutr"),this.started=!1,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.timeout=t.timeout??jg.timeout,this.retries=t.retries??jg.retries,this.maxInboundStreams=t.maxInboundStreams??jg.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??jg.maxOutboundStreams,this.handleIncomingUpgrade=this.handleIncomingUpgrade.bind(this)}[Symbol.toStringTag]="@libp2p/dcutr";[Zr]=["@libp2p/identify"];isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.registrar.register(vh,{notifyOnLimitedConnection:!0,onConnect:(e,t)=>{Kt.exactMatch(t.remoteAddr)&&t.direction==="inbound"&&this.upgradeInbound(t).catch(n=>{this.log.error("error during outgoing DCUtR attempt - %e",n)})}}),await this.registrar.handle(vh,this.handleIncomingUpgrade,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){await this.registrar.unhandle(vh),this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async upgradeInbound(e){if(await this.attemptUnilateralConnectionUpgrade(e))return;let t;for(let n=0;n<this.retries;n++){let o={signal:AbortSignal.timeout(this.timeout)};try{t=await e.newStream([vh],{signal:o.signal,runOnLimitedConnection:!0});let i=Xe(t,{maxDataLength:Yk}).pb(vo);this.log("B sending connect to %p",e.remotePeer);let s=Date.now();await i.write({type:vo.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(d=>d.bytes)},o),this.log("B receiving connect from %p",e.remotePeer);let a=await i.read(o);if(a.type!==vo.Type.CONNECT)throw this.log("A sent wrong message type"),new he("DCUtR message type was incorrect");let c=this.getDialableMultiaddrs(a.observedAddresses);if(c.length===0)throw this.log("A did not have any dialable multiaddrs"),new he("DCUtR connect message had no multiaddrs");let l=Date.now()-s;this.log("A sending sync, rtt %dms",l),await i.write({type:vo.Type.SYNC,observedAddresses:[]},o),this.log("A waiting for half RTT"),await ST(l/2),this.log("B dialing",c);let u=await this.connectionManager.openConnection(c,{signal:o.signal,priority:Xk,force:!0,initiator:!1});this.log("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,u.remoteAddr),await e.close(o);break}catch(i){if(this.log.error("error while attempting DCUtR on attempt %d of %d - %e",n+1,this.retries,i),t?.abort(i),n===this.retries)throw i}finally{t!=null&&await t.close(o)}}}async attemptUnilateralConnectionUpgrade(e){let n=(await this.peerStore.get(e.remotePeer)).addresses.map(o=>{let i=o.multiaddr;return i.getComponents().find(s=>s.code===421)?.value==null?i.encapsulate(`/p2p/${e.remotePeer}`):i}).filter(o=>ab(o,this.transportManager));if(n.length>0){let o=AbortSignal.timeout(this.timeout);try{this.log("attempting unilateral connection upgrade to %a",n);let i=await this.connectionManager.openConnection(n,{signal:o,force:!0});if(Kt.exactMatch(i.remoteAddr))throw new Error("Could not open a new, non-limited, connection");return this.log("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,i.remoteAddr),await e.close({signal:o}),!0}catch(i){this.log.error("unilateral connection upgrade to %p on addresses %a failed - %e",e.remotePeer,n,i)}}else this.log("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}async handleIncomingUpgrade(e,t){let n={signal:AbortSignal.timeout(this.timeout)},o=Xe(e,{maxDataLength:Yk}).pb(vo);this.log("A receiving connect");let i=await o.read(n);if(i.type!==vo.Type.CONNECT)throw this.log("B sent wrong message type"),new he("DCUtR message type was incorrect");if(i.observedAddresses.length===0)throw this.log("B sent no multiaddrs"),new he("DCUtR connect message had no multiaddrs");let s=this.getDialableMultiaddrs(i.observedAddresses);if(s.length===0)throw this.log("B had no dialable multiaddrs in %o",i.observedAddresses.map(l=>j(l))),new he("DCUtR connect message had no dialable multiaddrs");if(this.log("A sending connect"),await o.write({type:vo.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(l=>l.bytes)}),this.log("A receiving sync"),(await o.read(n)).type!==vo.Type.SYNC)throw new he("DCUtR message type was incorrect");this.log("A dialing",s);let c=await this.connectionManager.openConnection(s,{signal:n.signal,priority:Xk,force:!0});this.log("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,c.remoteAddr),await t.close(n),await e.close(n)}getDialableMultiaddrs(e){let t=[];for(let n of e)if(!(n==null||n.length===0))try{let o=j(n);if(!ab(o,this.transportManager))continue;t.push(o)}catch{}return t}};var vh="/libp2p/dcutr";function Qk(r={}){return e=>new Yg(e,r)}function X(r){if(r!==void 0&&r!==X.REQUEST&&r!==X.RESPONSE)throw new Error("type must be REQUEST or RESPONSE");r===void 0||this.initialize(r),this.maxHeaderSize=X.maxHeaderSize}X.prototype.initialize=function(r,e){if(r!==X.REQUEST&&r!==X.RESPONSE)throw new Error("type must be REQUEST or RESPONSE");this.type=r,this.state=r+"_LINE",this.info={headers:[],upgrade:!1},this.trailers=[],this.line="",this.isChunked=!1,this.connection="",this.headerSize=0,this.body_bytes=null,this.isUserCall=!1,this.hadError=!1};X.encoding="ascii";X.maxHeaderSize=80*1024;X.REQUEST="REQUEST";X.RESPONSE="RESPONSE";var Zk=X.kOnHeaders=1,cb=X.kOnHeadersComplete=2,Xg=X.kOnBody=3,lb=X.kOnMessageComplete=4;X.prototype[Zk]=X.prototype[cb]=X.prototype[Xg]=X.prototype[lb]=function(){};var Jk=!0;Object.defineProperty(X,"kOnExecute",{get:function(){return Jk=!1,99}});var eR=X.methods=["DELETE","GET","HEAD","POST","PUT","CONNECT","OPTIONS","TRACE","COPY","LOCK","MKCOL","MOVE","PROPFIND","PROPPATCH","SEARCH","UNLOCK","BIND","REBIND","UNBIND","ACL","REPORT","MKACTIVITY","CHECKOUT","MERGE","M-SEARCH","NOTIFY","SUBSCRIBE","UNSUBSCRIBE","PATCH","PURGE","MKCALENDAR","LINK","UNLINK","SOURCE"],tR=eR.indexOf("CONNECT");X.prototype.reinitialize=X;X.prototype.close=X.prototype.pause=X.prototype.resume=X.prototype.remove=X.prototype.free=function(){};X.prototype._compatMode0_11=!1;X.prototype.getAsyncId=function(){return 0};var Tj={REQUEST_LINE:!0,RESPONSE_LINE:!0,HEADER:!0};X.prototype.execute=function(r,e,t){if(!(this instanceof X))throw new TypeError("not a HTTPParser");e=e||0,t=typeof t=="number"?t:r.length,this.chunk=r,this.offset=e;var n=this.end=e+t;try{for(;this.offset<n&&!this[this.state](););}catch(o){if(this.isUserCall)throw o;return this.hadError=!0,o}return this.chunk=null,t=this.offset-e,Tj[this.state]&&(this.headerSize+=t,this.headerSize>(this.maxHeaderSize||X.maxHeaderSize))?new Error("max header size exceeded"):t};var _j={REQUEST_LINE:!0,RESPONSE_LINE:!0,BODY_RAW:!0};X.prototype.finish=function(){if(!this.hadError){if(!_j[this.state])return new Error("invalid state for EOF");this.state==="BODY_RAW"&&this.userCall()(this[lb]())}};X.prototype.consume=X.prototype.unconsume=X.prototype.getCurrentBuffer=function(){};X.prototype.userCall=function(){this.isUserCall=!0;var r=this;return function(e){return r.isUserCall=!1,e}};X.prototype.nextRequest=function(){this.userCall()(this[lb]()),this.reinitialize(this.type)};X.prototype.consumeLine=function(){for(var r=this.end,e=this.chunk,t=this.offset;t<r;t++)if(e[t]===10){var n=this.line+de(e.subarray(this.offset,t),X.encoding);return n.charAt(n.length-1)==="\r"&&(n=n.substr(0,n.length-1)),this.line="",this.offset=t+1,n}this.line+=de(e.subarray(this.offset,this.end),X.encoding),this.offset=this.end};var Cj=/^([^: \t]+):[ \t]*((?:.*[^ \t])|)/,Ij=/^[ \t]+(.*[^ \t])/;X.prototype.parseHeader=function(r,e){if(r.indexOf("\r")!==-1)throw Qg("HPE_LF_EXPECTED");var t=Cj.exec(r),n=t&&t[1];if(n)e.push(n),e.push(t[2]);else{var o=Ij.exec(r);o&&e.length&&(e[e.length-1]&&(e[e.length-1]+=" "),e[e.length-1]+=o[1])}};var kj=/^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/;X.prototype.REQUEST_LINE=function(){var r=this.consumeLine();if(r){var e=kj.exec(r);if(e===null)throw Qg("HPE_INVALID_CONSTANT");if(this.info.method=this._compatMode0_11?e[1]:eR.indexOf(e[1]),this.info.method===-1)throw new Error("invalid request method");this.info.url=e[2],this.info.versionMajor=+e[3],this.info.versionMinor=+e[4],this.body_bytes=0,this.state="HEADER"}};var Rj=/^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/;X.prototype.RESPONSE_LINE=function(){var r=this.consumeLine();if(r){var e=Rj.exec(r);if(e===null)throw Qg("HPE_INVALID_CONSTANT");this.info.versionMajor=+e[1],this.info.versionMinor=+e[2];var t=this.info.statusCode=+e[3];this.info.statusMessage=e[4],((t/100|0)===1||t===204||t===304)&&(this.body_bytes=0),this.state="HEADER"}};X.prototype.shouldKeepAlive=function(){if(this.info.versionMajor>0&&this.info.versionMinor>0){if(this.connection.indexOf("close")!==-1)return!1}else if(this.connection.indexOf("keep-alive")===-1)return!1;return!!(this.body_bytes!==null||this.isChunked)};X.prototype.HEADER=function(){var r=this.consumeLine();if(r!==void 0){var e=this.info;if(r)this.parseHeader(r,e.headers);else{for(var t=e.headers,n=!1,o,i=!1,s=0;s<t.length;s+=2)switch(t[s].toLowerCase()){case"transfer-encoding":this.isChunked=t[s+1].toLowerCase()==="chunked";break;case"content-length":if(o=+t[s+1],n){if(o!==this.body_bytes)throw Qg("HPE_UNEXPECTED_CONTENT_LENGTH")}else n=!0,this.body_bytes=o;break;case"connection":this.connection+=t[s+1].toLowerCase();break;case"upgrade":i=!0;break}this.isChunked&&n&&(n=!1,this.body_bytes=null),i&&this.connection.indexOf("upgrade")!=-1?e.upgrade=this.type===X.REQUEST||e.statusCode===101:e.upgrade=e.method===tR,this.isChunked&&e.upgrade&&(this.isChunked=!1),e.shouldKeepAlive=this.shouldKeepAlive();var a;if(Jk?a=this.userCall()(this[cb](e)):a=this.userCall()(this[cb](e.versionMajor,e.versionMinor,e.headers,e.method,e.url,e.statusCode,e.statusMessage,e.upgrade,e.shouldKeepAlive)),a===2)return this.nextRequest(),!0;if(this.isChunked&&!a)this.state="BODY_CHUNKHEAD";else{if(a||this.body_bytes===0)return this.nextRequest(),e.upgrade;this.body_bytes===null?this.state="BODY_RAW":this.state="BODY_SIZED"}}}};X.prototype.BODY_CHUNKHEAD=function(){var r=this.consumeLine();r!==void 0&&(this.body_bytes=parseInt(r,16),this.body_bytes?this.state="BODY_CHUNK":this.state="BODY_CHUNKTRAILERS")};X.prototype.BODY_CHUNK=function(){var r=Math.min(this.end-this.offset,this.body_bytes);this.userCall()(this[Xg](this.chunk.slice(this.offset,this.offset+r),0,r)),this.offset+=r,this.body_bytes-=r,this.body_bytes||(this.state="BODY_CHUNKEMPTYLINE")};X.prototype.BODY_CHUNKEMPTYLINE=function(){var r=this.consumeLine();if(r!==void 0){if(r!=="")throw new Error("Expected empty line");this.state="BODY_CHUNKHEAD"}};X.prototype.BODY_CHUNKTRAILERS=function(){var r=this.consumeLine();r!==void 0&&(r?this.parseHeader(r,this.trailers):(this.trailers.length&&this.userCall()(this[Zk](this.trailers,"")),this.nextRequest()))};X.prototype.BODY_RAW=function(){this.userCall()(this[Xg](this.chunk.slice(this.offset,this.end),0,this.end-this.offset)),this.offset=this.end};X.prototype.BODY_SIZED=function(){var r=Math.min(this.end-this.offset,this.body_bytes);this.userCall()(this[Xg](this.chunk.slice(this.offset,this.offset+r),0,r)),this.offset+=r,this.body_bytes-=r,this.body_bytes||this.nextRequest()};["Headers","HeadersComplete","Body","MessageComplete"].forEach(function(r){var e=X["kOn"+r];Object.defineProperty(X.prototype,"on"+r,{get:function(){return this[e]},set:function(t){return this._compatMode0_11=!0,tR="CONNECT",this[e]=t}})});function Qg(r){var e=new Error("Parse Error");return e.code=r,e}function rR(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function Kn(r,e={}){let t=rR(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(o){try{let{value:i,done:s}=await t.next();if(this._cancelled)return;if(s===!0){o.close();return}o.enqueue(i)}catch(i){o.error(i)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}var Pj=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),nR=li({name:"sha-1",code:17,encode:Pj("SHA-1")});var Zg=class extends globalThis.Request{constructor(e,t={}){let n=t.method??"GET",o=ti(t),i=t.body;Jg(n,o)&&(t.method="UPGRADE"),super(e,t),Object.defineProperties(this,{body:{value:i,writable:!1},method:{value:n,writable:!1},headers:{value:o,writable:!1}})}};var oR={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};var ri=class extends globalThis.Response{constructor(e,t={}){let n=ti(t),o=t.status??200;(o<200||o>599)&&(t.status=200),super(e,t),Object.defineProperties(this,{status:{value:o,writable:!1},statusText:{value:oR[o],writable:!1},headers:{value:n,writable:!1}})}};var Dj=["dns","dns4","dns6","dnsaddr"];function Ah(r,e){if(r instanceof URL)return r;let t=t3(r,e),{httpPath:n}=r3(r);return new URL(`http://${t}${n}`)}function Th(r){return r instanceof Uint8Array?r:r instanceof DataView?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r,0,r.byteLength)}function sR(r,e){let t={method:r.method,headers:r.headers};if((t.method!=="GET"||r.upgrade)&&t.method!=="HEAD"){let n=e;r.upgrade||(n=Nj(e,r.headers.get("content-length"))),t.body=Kn(n),t.duplex="half"}return new Zg(ub(r).toString(),t)}async function aR(r,e){if(e.send(K([`HTTP/1.1 ${r.status} ${r.statusText}`,...e3(r.headers),"",""].join(`\r
51
+ `)}async function y7(r,e){try{let t=await DW(r,e);return tS(t)}catch{}if(!r.includes("BEGIN"))throw new E("Encrypted key was not a libp2p-key or a PEM file");return LW(r,e)}async function DW(r,e){let t=Tt.decode(r);return iu.create().decrypt(t,e)}async function LW(r,e){let t=At.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let i=Ni(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=wg(i),{iv:a,salt:c,iterations:l,keySize:u,cipherText:d}=NW(s),f=await fm(Lo,e,c,{c:l,dkLen:u}),h=await t.subtle.importKey("raw",Ps(f),"AES-CBC",!1,["decrypt"]),p=nh(await t.subtle.decrypt({name:"AES-CBC",iv:Ps(a)},h,Ps(d))),{result:y}=wg(p);n=HI(y)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let i=Ni(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=wg(i);n=HI(s)}else throw new E("Could not parse private key from PEM data");let o=rS(n);if(o.type!=="RSA")throw new E("Could not parse RSA private key from PEM data");return o}function NW(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new E("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 E("Only pkcs5PBKDF2 key derivation functions are supported");let i=n.valueBlock.value[1],s=nh(i.valueBlock.value[0].getValue()),a=1e4,c=32;if(i.valueBlock.value.length===3)a=Number(i.valueBlock.value[1].toBigInt()),c=Number(i.valueBlock.value[2].toBigInt());else if(i.valueBlock.value.length===2)throw new E("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 E("Only AES-CBC encryption schemes are supported")}}}}let d=nh(l.valueBlock.value[1].getValue());return{cipherText:nh(r.valueBlock.value[1].getValue()),salt:s,iterations:a,keySize:c,iv:d}}function HI(r){return nh(r.valueBlock.value[2].getValue())}function nh(r){return new Uint8Array(r,0,r.byteLength)}var OW="/pkcs8/",w7="/info/",oh=new WeakMap,fc={minKeyLength:112/8,minSaltLength:128/8,minIterationCount:1e3};function cu(r){return r==null||typeof r!="string"?!1:r===(0,qI.default)(r.trim())&&r.length>0}async function or(){let t=Math.random()*800+200;await new Promise(n=>setTimeout(n,t))}function hc(r){return new He(OW+r)}function lu(r){return new He(w7+r)}async function BW(r){let e=Ia(r),t=await ct.digest(e);return Ce.encode(t.bytes).substring(1)}var xg=class{components;init;log;self;constructor(e,t){if(this.components=e,this.log=e.logger.forComponent("libp2p:keychain"),this.init={...t,dek:{...l7,...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<fc.minKeyLength)throw new Error(`dek.keyLength must be least ${fc.minKeyLength} bytes`);if(this.init.dek?.salt?.length!=null&&this.init.dek.salt.length<fc.minSaltLength)throw new Error(`dek.saltLength must be least ${fc.minSaltLength} bytes`);if(this.init.dek?.iterationCount!=null&&this.init.dek.iterationCount<fc.minIterationCount)throw new Error(`dek.iterationCount must be least ${fc.minIterationCount}`);let n=this.init.pass!=null&&this.init.dek?.salt!=null?$d(this.init.pass,this.init.dek?.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";oh.set(this,{dek:n})}[Symbol.toStringTag]="@libp2p/keychain";[be]=["@libp2p/keychain"];static generateOptions(){let e=Object.assign({},this.options),t=Math.ceil(fc.minSaltLength/3)*3;return e.dek!=null&&(e.dek.salt=jo(kr(t),"base64")),e}static get options(){return{dek:{...l7}}}async findKeyByName(e){if(!cu(e))throw await or(),new E(`Invalid key name '${e}'`);let t=lu(e);try{let n=await this.components.datastore.get(t);return JSON.parse(jo(n))}catch(n){throw await or(),this.log.error("could not read key from datastore - %e",n),new qe(`Key '${e}' does not exist.`)}}async findKeyById(e){try{let t={prefix:w7};for await(let n of this.components.datastore.query(t)){let o=JSON.parse(jo(n.value));if(o.id===e)return o}throw new E(`Key with id '${e}' does not exist.`)}catch(t){throw await or(),t}}async importKey(e,t){if(!cu(e))throw await or(),new E(`Invalid key name '${e}'`);if(t==null)throw await or(),new E("Key is required");let n=hc(e);if(await this.components.datastore.has(n))throw await or(),new E(`Key '${e}' already exists`);let i,s;try{i=await BW(t);let l=oh.get(this);if(l==null)throw new E("dek missing");let u=l.dek;s=await g7(t,u,t.type==="RSA"?"pkcs-8":"libp2p-key")}catch(l){throw await or(),l}let a={name:e,id:i},c=this.components.datastore.batch();return c.put(n,Ni(s)),c.put(lu(e),Ni(JSON.stringify(a))),await c.commit(),a}async exportKey(e){if(!cu(e))throw await or(),new E(`Invalid key name '${e}'`);let t=hc(e);try{let n=await this.components.datastore.get(t),o=jo(n),i=oh.get(this);if(i==null)throw new E("dek missing");let s=i.dek;return await y7(o,s)}catch(n){throw await or(),n}}async removeKey(e){if(!cu(e)||e===this.self)throw await or(),new E(`Invalid key name '${e}'`);let t=hc(e),n=await this.findKeyByName(e),o=this.components.datastore.batch();return o.delete(t),o.delete(lu(e)),await o.commit(),n}async listKeys(){let e={prefix:w7},t=[];for await(let n of this.components.datastore.query(e))t.push(JSON.parse(jo(n.value)));return t}async renameKey(e,t){if(!cu(e)||e===this.self)throw await or(),new E(`Invalid old key name '${e}'`);if(!cu(t)||t===this.self)throw await or(),new E(`Invalid new key name '${t}'`);let n=hc(e),o=hc(t),i=lu(e),s=lu(t);if(await this.components.datastore.has(o))throw await or(),new E(`Key '${t}' already exists`);try{let c=await this.components.datastore.get(n),l=await this.components.datastore.get(i),u=JSON.parse(jo(l));u.name=t;let d=this.components.datastore.batch();return d.put(o,c),d.put(s,Ni(JSON.stringify(u))),d.delete(n),d.delete(i),await d.commit(),u}catch(c){throw await or(),c}}async rotateKeychainPass(e,t){if(typeof e!="string")throw await or(),new E(`Invalid old pass type '${typeof e}'`);if(typeof t!="string")throw await or(),new E(`Invalid new pass type '${typeof t}'`);if(t.length<20)throw await or(),new E(`Invalid pass length ${t.length}`);this.log("recreating keychain");let n=oh.get(this);if(n==null)throw new E("dek missing");let o=n.dek;this.init.pass=t;let i=t!=null&&this.init.dek?.salt!=null?$d(t,this.init.dek.salt,this.init.dek?.iterationCount,this.init.dek?.keyLength,this.init.dek?.hash):"";oh.set(this,{dek:i});let s=await this.listKeys();for(let a of s){let c=await this.components.datastore.get(hc(a.name)),l=jo(c),u=await y7(l,o),d=i.toString(),f=await g7(u,d,u.type==="RSA"?"pkcs-8":"libp2p-key"),h=this.components.datastore.batch(),p={name:a.name,id:a.id};h.put(hc(a.name),Ni(f)),h.put(lu(a.name),Ni(JSON.stringify(p))),await h.commit()}this.log("keychain reconstructed")}};function Eg(r={}){return e=>new xg(e,r)}async function b7(r,e={}){let t=e.selfKey??"self",n=Eg(e)({datastore:r,logger:Ol()}),o;return await r.has(new He(`/pkcs8/${t}`))?o=await n.exportKey(t):(o=await um(e.keyType??"Ed25519"),await n.importKey(t,o)),o}var uu=!!globalThis.process?.env?.DUMP_SESSION_KEYS,x7=16;function MW(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function vg(r){if(typeof r!="boolean")throw new TypeError(`boolean expected, not ${r}`)}function du(r){if(typeof r!="number")throw new TypeError("number expected, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError("positive integer expected, got "+r)}function Ot(r,e,t=""){let n=MW(r),o=r?.length,i=e!==void 0;if(!n||i&&o!==e){let s=t&&`"${t}" `,a=i?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`,l=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function E7(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 VI(r,e,t=!1){Ot(r,void 0,"output");let n=e.outputLen;if(r.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(t&&!fu(r))throw new Error("invalid output, must be aligned")}function Zo(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function xo(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function FW(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var pc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,UW=r=>r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255;var $W=r=>{for(let e=0;e<r.length;e++)r[e]=UW(r[e]);return r},qi=pc?r=>r:$W;function KI(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function zI(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 GI(r,e,t){let n=e,o=t||(()=>[]),i=(a,c)=>n(c,...o(a)).update(a).digest(),s=n(new Uint8Array(r),...o(new Uint8Array(0)));return i.outputLen=s.outputLen,i.blockLen=s.blockLen,i.create=(a,...c)=>n(a,...c),i}var WI=(r,e)=>{function t(n,...o){if(Ot(n,void 0,"key"),r.nonceLength!==void 0){let u=o[0];Ot(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let i=r.tagLength;i&&o[1]!==void 0&&Ot(o[1],void 0,"AAD");let s=e(n,...o),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");Ot(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ot(u),a(s.encrypt.length,d),s.encrypt(u,d)},decrypt(u,d){if(Ot(u),i&&u.length<i)throw new Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,d),s.decrypt(u,d)}}}return Object.assign(t,r),t};function ih(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(Ot(e,void 0,"output"),e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!fu(e))throw new Error("invalid output, must be aligned");return e}function jI(r,e,t){du(r),du(e),vg(t);let n=new Uint8Array(16),o=FW(n);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(r),t),n}function fu(r){return r.byteOffset%4===0}function hu(r){return Uint8Array.from(Ot(r))}var XI=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),HW=qi(Zo(XI("expand 16-byte k"))),qW=qi(Zo(XI("expand 32-byte k")));function Te(r,e){return r<<e|r>>>32-e}var sh=64,VW=16,v7=2**32-1,YI=Uint32Array.of();function KW(r,e,t,n,o,i,s,a){let c=o.length,l=new Uint8Array(sh),u=Zo(l),d=pc&&fu(o)&&fu(i),f=d?Zo(o):YI,h=d?Zo(i):YI;if(!pc){for(let p=0;p<c;s++){if(r(e,t,n,u,s,a),qi(u),s>=v7)throw new Error("arx: counter overflow");let y=Math.min(sh,c-p);for(let g=0,m;g<y;g++)m=p+g,i[m]=o[m]^l[g];p+=y}return}for(let p=0;p<c;s++){if(r(e,t,n,u,s,a),s>=v7)throw new Error("arx: counter overflow");let y=Math.min(sh,c-p);if(d&&y===sh){let g=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let m=0,b;m<VW;m++)b=g+m,h[b]=f[b]^u[m];p+=sh;continue}for(let g=0,m;g<y;g++)m=p+g,i[m]=o[m]^l[g];p+=y}}function QI(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:i,rounds:s}=KI({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return du(o),du(s),vg(i),vg(t),(a,c,l,u,d=0)=>{Ot(a,void 0,"key"),Ot(c,void 0,"nonce"),Ot(l,void 0,"data");let f=l.length;if(u=ih(f,u,!1),du(d),d<0||d>=v7)throw new Error("arx: counter overflow");let h=[],p=a.length,y,g;if(p===32)h.push(y=hu(a)),g=qW;else if(p===16&&t)y=new Uint8Array(32),y.set(a),y.set(a,16),g=HW,h.push(y);else throw Ot(a,32,"arx key"),new Error("invalid key size");(!pc||!fu(c))&&h.push(c=hu(c));let m=Zo(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let R=c.subarray(0,16);if(pc)n(g,m,Zo(R),m);else{let D=qi(Uint32Array.from(g));n(D,m,Zo(R),m),xo(D),qi(m)}c=c.subarray(16)}else pc||qi(m);let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let R=new Uint8Array(12);R.set(c,i?0:12-c.length),c=R,h.push(c)}let T=qi(Zo(c));try{return KW(r,g,m,T,l,u,d,s),u}finally{xo(...h)}}}function ir(r,e){return r[e++]&255|(r[e++]&255)<<8}var S7=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=hu(Ot(e,32,"key"));let t=ir(e,0),n=ir(e,2),o=ir(e,4),i=ir(e,6),s=ir(e,8),a=ir(e,10),c=ir(e,12),l=ir(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=ir(e,16+2*u)}process(e,t,n=!1){let o=n?0:2048,{h:i,r:s}=this,a=s[0],c=s[1],l=s[2],u=s[3],d=s[4],f=s[5],h=s[6],p=s[7],y=s[8],g=s[9],m=ir(e,t+0),b=ir(e,t+2),T=ir(e,t+4),R=ir(e,t+6),D=ir(e,t+8),O=ir(e,t+10),U=ir(e,t+12),C=ir(e,t+14),L=i[0]+(m&8191),H=i[1]+((m>>>13|b<<3)&8191),M=i[2]+((b>>>10|T<<6)&8191),x=i[3]+((T>>>7|R<<9)&8191),A=i[4]+((R>>>4|D<<12)&8191),_=i[5]+(D>>>1&8191),v=i[6]+((D>>>14|O<<2)&8191),S=i[7]+((O>>>11|U<<5)&8191),P=i[8]+((U>>>8|C<<8)&8191),B=i[9]+(C>>>5|o),I=0,q=I+L*a+H*(5*g)+M*(5*y)+x*(5*p)+A*(5*h);I=q>>>13,q&=8191,q+=_*(5*f)+v*(5*d)+S*(5*u)+P*(5*l)+B*(5*c),I+=q>>>13,q&=8191;let V=I+L*c+H*a+M*(5*g)+x*(5*y)+A*(5*p);I=V>>>13,V&=8191,V+=_*(5*h)+v*(5*f)+S*(5*d)+P*(5*u)+B*(5*l),I+=V>>>13,V&=8191;let Z=I+L*l+H*c+M*a+x*(5*g)+A*(5*y);I=Z>>>13,Z&=8191,Z+=_*(5*p)+v*(5*h)+S*(5*f)+P*(5*d)+B*(5*u),I+=Z>>>13,Z&=8191;let fe=I+L*u+H*l+M*c+x*a+A*(5*g);I=fe>>>13,fe&=8191,fe+=_*(5*y)+v*(5*p)+S*(5*h)+P*(5*f)+B*(5*d),I+=fe>>>13,fe&=8191;let ce=I+L*d+H*u+M*l+x*c+A*a;I=ce>>>13,ce&=8191,ce+=_*(5*g)+v*(5*y)+S*(5*p)+P*(5*h)+B*(5*f),I+=ce>>>13,ce&=8191;let Fe=I+L*f+H*d+M*u+x*l+A*c;I=Fe>>>13,Fe&=8191,Fe+=_*a+v*(5*g)+S*(5*y)+P*(5*p)+B*(5*h),I+=Fe>>>13,Fe&=8191;let Ue=I+L*h+H*f+M*d+x*u+A*l;I=Ue>>>13,Ue&=8191,Ue+=_*c+v*a+S*(5*g)+P*(5*y)+B*(5*p),I+=Ue>>>13,Ue&=8191;let $e=I+L*p+H*h+M*f+x*d+A*u;I=$e>>>13,$e&=8191,$e+=_*l+v*c+S*a+P*(5*g)+B*(5*y),I+=$e>>>13,$e&=8191;let _e=I+L*y+H*p+M*h+x*f+A*d;I=_e>>>13,_e&=8191,_e+=_*u+v*l+S*c+P*a+B*(5*g),I+=_e>>>13,_e&=8191;let tt=I+L*g+H*y+M*p+x*h+A*f;I=tt>>>13,tt&=8191,tt+=_*d+v*u+S*l+P*c+B*a,I+=tt>>>13,tt&=8191,I=(I<<2)+I|0,I=I+q|0,q=I&8191,I=I>>>13,V+=I,i[0]=q,i[1]=V,i[2]=Z,i[3]=fe,i[4]=ce,i[5]=Fe,i[6]=Ue,i[7]=$e,i[8]=_e,i[9]=tt}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let i=(o^1)-1;for(let a=0;a<10;a++)n[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let s=e[0]+t[0];e[0]=s&65535;for(let a=1;a<8;a++)s=(e[a]+t[a]|0)+(s>>>16)|0,e[a]=s&65535;xo(n)}update(e){E7(this),Ot(e),e=hu(e);let{buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);if(s===n){for(;n<=o-i;i+=n)this.process(e,i);continue}t.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,xo(this.h,this.r,this.buffer,this.pad)}digestInto(e){E7(this),VI(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let s=0;s<8;s++)e[i++]=n[s]>>>0,e[i++]=n[s]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}},ZI=GI(32,r=>new S7(r));function zW(r,e,t,n,o,i=20){let s=r[0],a=r[1],c=r[2],l=r[3],u=e[0],d=e[1],f=e[2],h=e[3],p=e[4],y=e[5],g=e[6],m=e[7],b=o,T=t[0],R=t[1],D=t[2],O=s,U=a,C=c,L=l,H=u,M=d,x=f,A=h,_=p,v=y,S=g,P=m,B=b,I=T,q=R,V=D;for(let fe=0;fe<i;fe+=2)O=O+H|0,B=Te(B^O,16),_=_+B|0,H=Te(H^_,12),O=O+H|0,B=Te(B^O,8),_=_+B|0,H=Te(H^_,7),U=U+M|0,I=Te(I^U,16),v=v+I|0,M=Te(M^v,12),U=U+M|0,I=Te(I^U,8),v=v+I|0,M=Te(M^v,7),C=C+x|0,q=Te(q^C,16),S=S+q|0,x=Te(x^S,12),C=C+x|0,q=Te(q^C,8),S=S+q|0,x=Te(x^S,7),L=L+A|0,V=Te(V^L,16),P=P+V|0,A=Te(A^P,12),L=L+A|0,V=Te(V^L,8),P=P+V|0,A=Te(A^P,7),O=O+M|0,V=Te(V^O,16),S=S+V|0,M=Te(M^S,12),O=O+M|0,V=Te(V^O,8),S=S+V|0,M=Te(M^S,7),U=U+x|0,B=Te(B^U,16),P=P+B|0,x=Te(x^P,12),U=U+x|0,B=Te(B^U,8),P=P+B|0,x=Te(x^P,7),C=C+A|0,I=Te(I^C,16),_=_+I|0,A=Te(A^_,12),C=C+A|0,I=Te(I^C,8),_=_+I|0,A=Te(A^_,7),L=L+H|0,q=Te(q^L,16),v=v+q|0,H=Te(H^v,12),L=L+H|0,q=Te(q^L,8),v=v+q|0,H=Te(H^v,7);let Z=0;n[Z++]=s+O|0,n[Z++]=a+U|0,n[Z++]=c+C|0,n[Z++]=l+L|0,n[Z++]=u+H|0,n[Z++]=d+M|0,n[Z++]=f+x|0,n[Z++]=h+A|0,n[Z++]=p+_|0,n[Z++]=y+v|0,n[Z++]=g+S|0,n[Z++]=m+P|0,n[Z++]=b+B|0,n[Z++]=T+I|0,n[Z++]=R+q|0,n[Z++]=D+V|0}var GW=QI(zW,{counterRight:!1,counterLength:4,allowShortKeys:!1});var WW=new Uint8Array(16),JI=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(WW.subarray(t))},jW=new Uint8Array(32);function ek(r,e,t,n,o){o!==void 0&&Ot(o,void 0,"AAD");let i=r(e,t,jW),s=jI(n.length,o?o.length:0,!0),a=ZI.create(i);o&&JI(a,o),JI(a,n),a.update(s);let c=a.digest();return xo(i,s),c}var YW=r=>(e,t,n)=>({encrypt(i,s){let a=i.length;s=ih(a+16,s,!1),s.set(i);let c=s.subarray(0,-16);r(e,t,c,c,1);let l=ek(r,e,t,c,n);return s.set(l,a),xo(l),s},decrypt(i,s){s=ih(i.length-16,s,!1);let a=i.subarray(0,-16),c=i.subarray(-16),l=ek(r,e,t,a,n);if(!zI(c,l))throw xo(l),new Error("invalid tag");return s.set(i.subarray(0,-16)),r(e,t,s,s,1),xo(l),s}}),A7=WI({blockSize:64,nonceLength:12,tagLength:16},YW(GW));function rk(r,e,t){return di(r),t===void 0&&(t=new Uint8Array(r.outputLen)),Ca(r,t,e)}var T7=Uint8Array.of(0),tk=Uint8Array.of();function nk(r,e,t,n=32){di(r),Ur(n,"length"),Xt(e,void 0,"prk");let o=r.outputLen;if(e.length<o)throw new Error('"prk" must be at least HashLen octets');if(n>255*o)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(n/o);t===void 0?t=tk:Xt(t,void 0,"info");let s=new Uint8Array(i*o),a=Ca.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<i;u++)T7[0]=u+1,c.update(u===0?tk:l).update(t).update(T7).digestInto(l),s.set(l,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),cr(l,T7),s.slice(0,n)}var _7={hashSHA256(r){return Bn(r.subarray())},getHKDF(r,e){let t=rk(Bn,e,r),o=nk(Bn,t,void 0,96),i=o.subarray(0,32),s=o.subarray(32,64),a=o.subarray(64,96);return[i,s,a]},generateX25519KeyPair(){let r=_d.utils.randomSecretKey();return{publicKey:_d.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:_d.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return _d.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return A7(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return A7(n,e,t).decrypt(r.subarray(),o)}};var ok=_7;function ik(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var pu=r=>{let e=nt(2);return e[0]=r>>8,e[1]=r,e};pu.bytes=2;var mu=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};mu.bytes=2;function sk(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function C7(r,e){!e.enabled||!uu||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${de(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${de(r.privateKey,"hex")}`)):e("Missing local static keys."))}function I7(r,e){!e.enabled||!uu||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${de(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${de(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function ak(r,e){!e.enabled||!uu||e(r?`REMOTE_STATIC_PUBLIC_KEY ${de(r.subarray(),"hex")}`:"Missing remote static public key.")}function k7(r,e){!e.enabled||!uu||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${de(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function R7(r,e,t){!t.enabled||!uu||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&de(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&de(e.k,"hex")}`))}var gu=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var QW=0,ZW=4294967295,JW="Cipherstate has reached maximum n, a new handshake must be performed",Sg=class{n;bytes;view;constructor(e=QW){this.n=e,this.bytes=rt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>ZW)throw new Error(JW)}};var mc=rt(0),yu=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new Sg(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let o=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},P7=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=K(t,"utf-8");this.h=ej(e,n),this.ck=this.h,this.cs=new yu(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new yu(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new G(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,mc);return[new yu(this.crypto,e),new yu(this.crypto,t)]}},D7=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:o,initiator:i,s,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new P7(t,n),this.ss.mixHash(o),this.initiator=i,this.s=s,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let o=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},ah=class extends D7{writeMessageA(e){return new G(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new G(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new G(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new gu(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new gu(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new gu(`handshake stage 2 validation fail: ${t.message}`)}}};function ej(r,e){if(e.length<=32){let t=rt(32);return t.set(e),t}else return r.hash(e)}var L7=new Float32Array([-0]),Ds=new Uint8Array(L7.buffer);function ck(r,e,t){L7[0]=r,e[t]=Ds[0],e[t+1]=Ds[1],e[t+2]=Ds[2],e[t+3]=Ds[3]}function lk(r,e){return Ds[0]=r[e],Ds[1]=r[e+1],Ds[2]=r[e+2],Ds[3]=r[e+3],L7[0]}var N7=new Float64Array([-0]),wr=new Uint8Array(N7.buffer);function uk(r,e,t){N7[0]=r,e[t]=wr[0],e[t+1]=wr[1],e[t+2]=wr[2],e[t+3]=wr[3],e[t+4]=wr[4],e[t+5]=wr[5],e[t+6]=wr[6],e[t+7]=wr[7]}function dk(r,e){return wr[0]=r[e],wr[1]=r[e+1],wr[2]=r[e+2],wr[3]=r[e+3],wr[4]=r[e+4],wr[5]=r[e+5],wr[6]=r[e+6],wr[7]=r[e+7],N7[0]}var tj=BigInt(Number.MAX_SAFE_INTEGER),rj=BigInt(Number.MIN_SAFE_INTEGER),wn=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 gc;if(e<tj&&e>rj)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>fk&&(o=0n,++n>fk&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return gc;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):gc}},gc=new wn(0,0);gc.toBigInt=function(){return 0n};gc.zzEncode=gc.zzDecode=function(){return this};gc.length=function(){return 1};var fk=4294967296n;function hk(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 pk(r,e,t){if(t-e<1)return"";let o,i=[],s=0,a;for(;e<t;)a=r[e++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(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,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function O7(r,e,t){let n=t,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,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 Eo(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ag(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var B7=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,Eo(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 Eo(this,4);return Ag(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Eo(this,4);return Ag(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Eo(this,4);let e=lk(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Eo(this,4);let e=dk(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 Eo(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return pk(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Eo(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Eo(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 wn(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 Eo(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 Eo(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 Eo(this,8);let e=Ag(this.buf,this.pos+=4),t=Ag(this.buf,this.pos+=4);return new wn(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=kd(this.buf,this.pos);return this.pos+=ye(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 M7(r){return new B7(r instanceof Uint8Array?r:r.subarray())}function Tg(r,e,t){let n=M7(r);return e.decode(n,void 0,t)}function F7(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return nt(s);o+s>e&&(n=nt(e),o=0);let a=n.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}var yc=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function U7(){}var H7=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},nj=F7();function oj(r){return globalThis.Buffer!=null?nt(r):nj(r)}var lh=class{len;head;tail;states;constructor(){this.len=0,this.head=new yc(U7,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new yc(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new q7((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(_g,10,wn.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=wn.fromBigInt(e);return this._push(_g,t.length(),t)}uint64Number(e){return this._push(Id,ye(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=wn.fromBigInt(e).zzEncode();return this._push(_g,t.length(),t)}sint64Number(e){let t=wn.fromNumber(e).zzEncode();return this._push(_g,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push($7,1,e?1:0)}fixed32(e){return this._push(ch,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=wn.fromBigInt(e);return this._push(ch,4,t.lo)._push(ch,4,t.hi)}fixed64Number(e){let t=wn.fromNumber(e);return this._push(ch,4,t.lo)._push(ch,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(ck,4,e)}double(e){return this._push(uk,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push($7,1,0):this.uint32(t)._push(sj,t,e)}string(e){let t=hk(e);return t!==0?this.uint32(t)._push(O7,t,e):this._push($7,1,0)}fork(){return this.states=new H7(this),this.head=this.tail=new yc(U7,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 yc(U7,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=oj(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function $7(r,e,t){e[t]=r&255}function ij(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var q7=class extends yc{next;constructor(e,t){super(ij,e,t),this.next=void 0}};function _g(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 ch(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 sj(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(lh.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(aj,e,r),this},lh.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(cj,e,r),this});function aj(r,e,t){e.set(r,t)}function cj(r,e,t){r.length<40?O7(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(K(r),t)}function V7(){return new lh}function Cg(r,e){let t=V7();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var uh;(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"})(uh||(uh={}));function K7(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Ig(r,e){return K7("message",uh.LENGTH_DELIMITED,r,e)}var dh=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var kg;(function(r){let e;r.codec=()=>(e==null&&(e=Ig((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let i of t.webtransportCerthashes)n.uint32(10),n.bytes(i);if(t.streamMuxers!=null)for(let i of t.streamMuxers)n.uint32(18),n.string(i);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={webtransportCerthashes:[],streamMuxers:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&i.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new dh('Decode error - map field "webtransportCerthashes" had too many elements');i.webtransportCerthashes.push(t.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&i.streamMuxers.length===o.limits.streamMuxers)throw new dh('Decode error - map field "streamMuxers" had too many elements');i.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Cg(t,r.codec()),r.decode=(t,n)=>Tg(t,r.codec(),n)})(kg||(kg={}));var fh;(function(r){let e;r.codec=()=>(e==null&&(e=Ig((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),kg.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={identityKey:rt(0),identitySig:rt(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.identityKey=t.bytes();break}case 2:{i.identitySig=t.bytes();break}case 4:{i.extensions=kg.codec().decode(t,t.uint32(),{limits:o.limits?.extensions});break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>Cg(t,r.codec()),r.decode=(t,n)=>Tg(t,r.codec(),n)})(fh||(fh={}));async function G7(r,e,t){let n=await r.sign(yk(e));return fh.encode({identityKey:Ht(r.publicKey),identitySig:n,extensions:t})}async function W7(r,e,t){try{let n=fh.decode(r),o=Et(n.identityKey);if(t?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let i=yk(e);if(!await o.verify(i,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Ap(n.message)}}function yk(r){let e=K("noise-libp2p-static-key:");return r instanceof Uint8Array?Ln([e,r],e.length+r.length):(r.prepend(e),r)}var z7=class extends hs{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new Gm({lengthDecoder:mu,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);let i=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",i);let s=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",s);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let t=new G;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let i;e instanceof Uint8Array?i=this.handshake.encrypt(e.subarray(n,o)):i=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),t.append(pu(i.byteLength)),t.append(i)}return t}decrypt(e){let t=new G;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-x7<n)throw new Error("Invalid chunk");let i;e instanceof Uint8Array?i=e.subarray(n,o):i=e.sublist(n,o);let s=e.subarray(n,o-x7);try{let a=this.handshake.decrypt(i,s);this.metrics?.decryptedPackets.increment(),t.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function j7(r,e,t){return new z7(r,e,t)}async function wk(r,e){let{log:t,connection:n,crypto:o,privateKey:i,prologue:s,s:a,remoteIdentityKey:c,extensions:l}=r,u=await G7(i,a.publicKey,l),d=new ah({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:s,s:a});C7(d.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(d.writeMessageA(mc),e),t.trace("Stage 0 - Initiator finished sending first message."),I7(d.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let f=d.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),k7(d.re,t),ak(d.rs,t),t.trace("Initiator going to check remote's signature...");let h=await W7(f,d.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(d.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[p,y]=d.ss.split();return R7(p,y,t),{payload:h,encrypt:g=>p.encryptWithAd(mc,g),decrypt:(g,m)=>y.decryptWithAd(mc,g,m)}}async function bk(r,e){let{log:t,connection:n,crypto:o,privateKey:i,prologue:s,s:a,remoteIdentityKey:c,extensions:l}=r,u=await G7(i,a.publicKey,l),d=new ah({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:s,s:a});C7(d.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),k7(d.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(d.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),I7(d.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let f=d.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let h=await W7(f,d.rs,c),[p,y]=d.ss.split();return R7(p,y,t),{payload:h,encrypt:g=>y.encryptWithAd(mc,g),decrypt:(g,m)=>p.decryptWithAd(mc,g,m)}}var Rg=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){let{staticNoiseKey:n,extensions:o,crypto:i,prologueBytes:s}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=i??ok;this.crypto=ik(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?sk(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=s??rt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[be]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,o=ws(e,{lengthEncoder:pu,lengthDecoder:mu,maxDataLength:65535}),i=await this.performHandshakeInitiator(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Et(i.payload.identityKey);return{connection:j7(o.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:zo(s),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let o=t.get(n);if(o!=null)return o}if(e.length)throw new Tp("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=e.log?.newScope("noise")??this.log,o=ws(e,{lengthEncoder:pu,lengthDecoder:mu,maxDataLength:65535}),i=await this.performHandshakeResponder(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),s=Et(i.payload.identityKey);return{connection:j7(o.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:zo(s),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,o,i){let s,a=i?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await wk({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return s}async performHandshakeResponder(e,t,n,o,i){let s,a=i?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await bk({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return s}};function Pg(r={}){return e=>new Rg(e,r)}var dt;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(dt||(dt={}));var Pe;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(Pe||(Pe={}));var lSe=Object.values(Pe).filter(r=>typeof r!="string"),xk=0,Bt;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(Bt||(Bt={}));var Jo=12;var Vi=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function Ek(r){return r?.reason!==null}var bn=class extends Vi{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,Bt.ProtocolError),this.name="InvalidFrameError"}},wu=class extends Vi{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,Bt.ProtocolError),this.name="UnRequestedPingError"}},bu=class extends Vi{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,Bt.ProtocolError),this.name="NotMatchingPingError"}};var Dg=class extends Vi{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,Bt.ProtocolError),this.name="StreamAlreadyExistsError"}},Lg=class extends Vi{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,Bt.ProtocolError),this.name="DecodeInvalidVersionError"}},Ng=class extends Vi{static name="BothClientsError";constructor(e="Both clients"){super(e,Bt.ProtocolError),this.name="BothClientsError"}},xu=class extends Vi{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,Bt.ProtocolError),this.name="ReceiveWindowExceededError"}};var pSe=new Set([bn.name,wu.name,bu.name,Dg.name,Lg.name,Ng.name,xu.name]),ph=256*1024,Og=16*1024*1024;var mh={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:ph,maxStreamWindowSize:Og,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function vk(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new E("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new E("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new E("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new E("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<ph)throw new E("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new E("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new E("MaxStreamWindowSize must be less than equal MAX_UINT32")}function Ak(r){return r.header.type===dt.Data&&r.data!==null}var Sk=2**24;function lj(r){if(r[0]!==xk)throw new bn("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*Sk+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*Sk+(r[9]<<16)+(r[10]<<8)+r[11]}}var Bg=class{buffer;constructor(){this.buffer=new G}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=Jo;if(this.buffer.byteLength<Jo)return;let t=lj(this.buffer.subarray(0,Jo));if(t.type===dt.Data){if(e+=t.length,this.buffer.byteLength<e)return;let n=this.buffer.sublist(Jo,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}};function Y7(r){let e=new Uint8Array(Jo);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}var Mr;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(Mr||(Mr={}));var Mg=class extends ys{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??ph;super({...e,maxMessageSize:t-Jo}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??Og,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let n=()=>{this.state=Mr.Finished};this.addEventListener("close",n)}sendData(e){let t=e.byteLength,n=0,o=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){o=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}let i=Math.min(this.sendWindowCapacity,e.byteLength),s=this.getSendFlags(),a=e.sublist(0,i);e.consume(i);let c=this.sendFrame({type:dt.Data,flag:s,streamID:this.streamId,length:i},a);if(this.sendWindowCapacity-=i,n+=i,!c){o=c,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:o}}sendReset(){this.sendFrame({type:dt.WindowUpdate,flag:Pe.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|Pe.FIN;this.sendFrame({type:dt.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=Mr.Paused}sendResume(){this.state=Mr.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-Jo,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!Ak(e))throw new bn("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new xu("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&Pe.ACK)===Pe.ACK&&this.state===Mr.SYNSent&&(this.state=Mr.Established),(e&Pe.FIN)===Pe.FIN&&this.onRemoteCloseWrite(),(e&Pe.RST)===Pe.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case Mr.Init:return this.state=Mr.SYNSent,Pe.SYN;case Mr.SYNReceived:return this.state=Mr.Established,Pe.ACK;default:return 0}}sendWindowUpdate(){if(this.state===Mr.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>-1&&t-this.epochStart<=n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let o=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:dt.WindowUpdate,flag:e,streamID:this.streamId,length:o})}};function Tk(r){return{type:dt[r.type],flags:[(r.flag&Pe.SYN)===Pe.SYN?"SYN":void 0,(r.flag&Pe.ACK)===Pe.ACK?"ACK":void 0,(r.flag&Pe.FIN)===Pe.FIN?"FIN":void 0,(r.flag&Pe.RST)===Pe.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var _k="/yamux/1.0.0",Fg=class{protocol=_k;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[be]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new X7(e,{...this._init})}},X7=class extends gs{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:_k,name:"yamux"}),this.client=e.direction==="outbound",vk(t),this.enableKeepAlive=t.enableKeepAlive??mh.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??mh.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??mh.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??mh.maxOutboundStreams,this.decoder=new Bg,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=Ml(async n=>{try{await this.ping(n)}catch(o){this.log.error("ping error: %s",o)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new Xn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Xn("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new Kc("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,Mr.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new Xn("Muxer closed remotely");if(this.localGoAway!==void 0)throw new Xn("Muxer closed locally");if(this.activePing!=null)return Me(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await Me(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??Bt.NormalTermination;this.log.trace("muxer close reason=%s",Bt[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=Bt.InternalError;Ek(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(this.streams.find(i=>i.streamId===e)!=null)throw new E("Stream already exists with that id");let o=new Mg({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return o.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),o}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:n,length:o}=e.header;if(this.log.trace("received frame %o",Tk(e.header)),t===0)switch(n){case dt.Ping:{this.handlePing(e.header);return}case dt.GoAway:{this.handleGoAway(o);return}default:throw new bn("Invalid frame type")}else switch(e.header.type){case dt.Data:case dt.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new bn("Invalid frame type")}}handlePing(e){if(e.flag===Pe.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,Pe.ACK);else if(e.flag===Pe.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new bn("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new wu("ping not requested");if(this.activePing.id!==e)throw new bu("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",Bt[e]??"unknown"),this.remoteGoAway=e,e===Bt.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:n,type:o}=e.header;(n&Pe.SYN)===Pe.SYN&&this.incomingStream(t);let i=this.streams.find(s=>s.streamId===t);if(i===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(o){case dt.WindowUpdate:{i.handleWindowUpdate(e);return}case dt.Data:{i.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new E("Both endpoints are clients");if(this.streams.find(n=>n.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:dt.WindowUpdate,flag:Pe.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:dt.WindowUpdate,flag:Pe.RST,streamID:e,length:0});return}let t=this._newStream(e,Mr.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===dt.Data){if(t==null)throw new bn("Invalid frame");n=new G(Y7(e),t)}else n=Y7(e);return this.log.trace("sending frame %o",Tk(e)),this.send(n)}sendPing(e,t=Pe.SYN){t===Pe.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:dt.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=Bt.NormalTermination){this.log("sending GoAway reason=%s",Bt[e]),this.localGoAway=e,this.sendFrame({type:dt.GoAway,flag:0,streamID:0,length:e})}};function Ck(r={}){return()=>new Fg(r)}var Ik="libp2p",kk="autonat",Rk="1.0.0";var Je;(function(r){let e;(function(f){f.DIAL="DIAL",f.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(f){f[f.DIAL=0]="DIAL",f[f.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),(function(f){f.codec=()=>Ye(t)})(e=r.MessageType||(r.MessageType={}));let n;(function(f){f.OK="OK",f.E_DIAL_ERROR="E_DIAL_ERROR",f.E_DIAL_REFUSED="E_DIAL_REFUSED",f.E_BAD_REQUEST="E_BAD_REQUEST",f.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let o;(function(f){f[f.OK=0]="OK",f[f.E_DIAL_ERROR=100]="E_DIAL_ERROR",f[f.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",f[f.E_BAD_REQUEST=200]="E_BAD_REQUEST",f[f.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(o||(o={})),(function(f){f.codec=()=>Ye(o)})(n=r.ResponseStatus||(r.ResponseStatus={}));let i;(function(f){let h;f.codec=()=>(h==null&&(h=re((m,b,T={})=>{if(T.lengthDelimited!==!1&&b.fork(),m.id!=null&&(b.uint32(10),b.bytes(m.id)),m.addrs!=null&&m.addrs.length>0)for(let R of m.addrs)b.uint32(18),b.bytes(R);T.lengthDelimited!==!1&&b.ldelim()},(m,b,T={})=>{let R={addrs:[]},D=b==null?m.len:m.pos+b;for(;m.pos<D;){let O=m.uint32();switch(O>>>3){case 1:{R.id=m.bytes();break}case 2:{if(T.limits?.addrs!=null&&R.addrs.length===T.limits.addrs)throw new le('Decode error - repeated field "addrs" had too many elements');R.addrs.push(m.bytes());break}default:{m.skipType(O&7);break}}}return R},function*(m,b,T,R={}){let D={addrs:0},O=b==null?m.len:m.pos+b;for(;m.pos<O;){let U=m.uint32();switch(U>>>3){case 1:{yield{field:`${T}.id`,value:m.bytes()};break}case 2:{if(R.limits?.addrs!=null&&D.addrs===R.limits.addrs)throw new le('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${T}.addrs[]`,index:D.addrs,value:m.bytes()},D.addrs++;break}default:{m.skipType(U&7);break}}}})),h);function p(m){return ee(m,f.codec())}f.encode=p;function y(m,b){return J(m,f.codec(),b)}f.decode=y;function g(m,b){return te(m,f.codec(),b)}f.stream=g})(i=r.PeerInfo||(r.PeerInfo={}));let s;(function(f){let h;f.codec=()=>(h==null&&(h=re((m,b,T={})=>{T.lengthDelimited!==!1&&b.fork(),m.peer!=null&&(b.uint32(10),r.PeerInfo.codec().encode(m.peer,b)),T.lengthDelimited!==!1&&b.ldelim()},(m,b,T={})=>{let R={},D=b==null?m.len:m.pos+b;for(;m.pos<D;){let O=m.uint32();O>>>3===1?R.peer=r.PeerInfo.codec().decode(m,m.uint32(),{limits:T.limits?.peer}):m.skipType(O&7)}return R},function*(m,b,T,R={}){let D=b==null?m.len:m.pos+b;for(;m.pos<D;){let O=m.uint32();O>>>3===1?yield*r.PeerInfo.codec().stream(m,m.uint32(),`${T}.peer`,{limits:R.limits?.peer}):m.skipType(O&7)}})),h);function p(m){return ee(m,f.codec())}f.encode=p;function y(m,b){return J(m,f.codec(),b)}f.decode=y;function g(m,b){return te(m,f.codec(),b)}f.stream=g})(s=r.Dial||(r.Dial={}));let a;(function(f){let h;f.codec=()=>(h==null&&(h=re((m,b,T={})=>{T.lengthDelimited!==!1&&b.fork(),m.status!=null&&(b.uint32(8),r.ResponseStatus.codec().encode(m.status,b)),m.statusText!=null&&(b.uint32(18),b.string(m.statusText)),m.addr!=null&&(b.uint32(26),b.bytes(m.addr)),T.lengthDelimited!==!1&&b.ldelim()},(m,b,T={})=>{let R={},D=b==null?m.len:m.pos+b;for(;m.pos<D;){let O=m.uint32();switch(O>>>3){case 1:{R.status=r.ResponseStatus.codec().decode(m);break}case 2:{R.statusText=m.string();break}case 3:{R.addr=m.bytes();break}default:{m.skipType(O&7);break}}}return R},function*(m,b,T,R={}){let D=b==null?m.len:m.pos+b;for(;m.pos<D;){let O=m.uint32();switch(O>>>3){case 1:{yield{field:`${T}.status`,value:r.ResponseStatus.codec().decode(m)};break}case 2:{yield{field:`${T}.statusText`,value:m.string()};break}case 3:{yield{field:`${T}.addr`,value:m.bytes()};break}default:{m.skipType(O&7);break}}}})),h);function p(m){return ee(m,f.codec())}f.encode=p;function y(m,b){return J(m,f.codec(),b)}f.decode=y;function g(m,b){return te(m,f.codec(),b)}f.stream=g})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=re((f,h,p={})=>{p.lengthDelimited!==!1&&h.fork(),f.type!=null&&(h.uint32(8),r.MessageType.codec().encode(f.type,h)),f.dial!=null&&(h.uint32(18),r.Dial.codec().encode(f.dial,h)),f.dialResponse!=null&&(h.uint32(26),r.DialResponse.codec().encode(f.dialResponse,h)),p.lengthDelimited!==!1&&h.ldelim()},(f,h,p={})=>{let y={},g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{y.type=r.MessageType.codec().decode(f);break}case 2:{y.dial=r.Dial.codec().decode(f,f.uint32(),{limits:p.limits?.dial});break}case 3:{y.dialResponse=r.DialResponse.codec().decode(f,f.uint32(),{limits:p.limits?.dialResponse});break}default:{f.skipType(m&7);break}}}return y},function*(f,h,p,y={}){let g=h==null?f.len:f.pos+h;for(;f.pos<g;){let m=f.uint32();switch(m>>>3){case 1:{yield{field:`${p}.type`,value:r.MessageType.codec().decode(f)};break}case 2:{yield*r.Dial.codec().stream(f,f.uint32(),`${p}.dial`,{limits:y.limits?.dial});break}case 3:{yield*r.DialResponse.codec().stream(f,f.uint32(),`${p}.dialResponse`,{limits:y.limits?.dialResponse});break}default:{f.skipType(m&7);break}}}})),c);function l(f){return ee(f,r.codec())}r.encode=l;function u(f,h){return J(f,r.codec(),h)}r.decode=u;function d(f,h){return te(f,r.codec(),h)}r.stream=d})(Je||(Je={}));var mj=4,gj=8,Ug=class{components;protocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;started;log;topologyId;dialResults;findPeers;addressFilter;connectionThreshold;constructor(e,t){this.components=e,this.log=e.logger.forComponent("libp2p:auto-nat"),this.started=!1,this.protocol=`/${t.protocolPrefix??Ik}/${kk}/${Rk}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??20,this.connectionThreshold=t.connectionThreshold??80,this.maxMessageSize=t.maxMessageSize??8192,this.dialResults=_t({name:"libp2p_autonat_dial_results",metrics:e.metrics}),this.findPeers=Ml(this.findRandomPeers.bind(this),6e4),this.addressFilter=Lt(1024)}[Symbol.toStringTag]="@libp2p/autonat";[be]=["@libp2p/autonat"];get[Zr](){return["@libp2p/identify"]}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,(e,t)=>{this.handleIncomingAutonatStream(e,t).catch(n=>{this.log.error("error handling incoming autonat stream - %e",n)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.topologyId=await this.components.registrar.register(this.protocol,{onConnect:(e,t)=>{this.verifyExternalAddresses(t).catch(n=>{this.log.error("could not verify addresses - %e",n)})}}),this.findPeers.start(),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.topologyId!=null&&await this.components.registrar.unhandle(this.topologyId),this.dialResults.clear(),this.findPeers.stop(),this.started=!1}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every(e=>e.expires>Date.now()?!0:e.verified)}async findRandomPeers(e){if(this.allAddressesAreVerified())return;let t=ae([AbortSignal.timeout(1e4),e?.signal]);try{this.log("starting random walk to find peers to run AutoNAT");for await(let n of this.components.randomWalk.walk({signal:t})){if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable %s",n.id,n.multiaddrs.map(o=>o.toString()).join(", "));continue}try{this.log.trace("dial random peer %p",n.id),await this.components.connectionManager.openConnection(n.multiaddrs,{signal:t})}catch{}if(this.allAddressesAreVerified()){this.log("stopping random walk, all addresses are verified");return}if(!this.hasConnectionCapacity()){this.log("stopping random walk, too close to max connections");return}}}catch{}}async handleIncomingAutonatStream(e,t){let n=AbortSignal.timeout(this.timeout);try{let o=Xe(e,{maxDataLength:this.maxMessageSize}).pb(Je),i=await o.read({signal:n}),s=await this.handleAutonatMessage(i,t,{signal:n});await o.write(s,{signal:n}),await e.close({signal:n})}catch(o){this.log.error("error handling incoming autonat stream - %e",o),e.abort(o)}}async handleAutonatMessage(e,t,n){let o=this.components.addressManager.getAddresses().map(d=>ie(d).host),i=e.dial;if(i==null)return this.log.error("dial was missing from message"),{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}};let s,a=i.peer;if(a?.id==null)return this.log.error("peerId missing from message"),{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}};try{let d=xe(a.id);s=bt(d)}catch(d){return this.log.error("invalid PeerId - %e",d),{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}}}if(this.log("incoming request from %p",s),!t.remotePeer.equals(s))return this.log("target peer %p did not equal sending peer %p",s,t.remotePeer),{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}};let c=a.addrs.map(d=>j(d)).filter(d=>{try{let f=ie(d);return wt(d)?!1:f.host!==ie(t.remoteAddr).host?(this.log.trace("not dialing %a - target host did not match remote host %a",d,t.remoteAddr),!1):o.includes(f.host)?!1:this.components.transportManager.dialTransportForMultiaddr(d)==null?(this.log.trace("not dialing %a - transport unsupported",d),!1):!0}catch{return!1}}).map(d=>(d.getComponents().find(f=>f.code===421)?.value==null&&(d=d.encapsulate(`/p2p/${s.toString()}`)),d));if(c.length===0)return this.log("refused to dial all multiaddrs for %p from message",s),{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}};this.log("dial multiaddrs %s for peer %p",c.map(d=>d.toString()).join(", "),s);let l="",u=c[0];for(let d of c){let f;u=d;try{if(f=await this.components.connectionManager.openConnection(d,n),!f.remoteAddr.equals(d))throw this.log.error("tried to dial %a but dialed %a",d,f.remoteAddr),new Error("Unexpected remote address");return this.log("successfully dialed %p via %a",s,d),{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.OK,addr:f.remoteAddr.decapsulateCode(421).bytes}}}catch(h){this.log.error("could not dial %p - %e",s,h),l=h.message}finally{f!=null&&await f.close()}}return{type:Je.MessageType.DIAL_RESPONSE,dialResponse:{status:Je.ResponseStatus.E_DIAL_ERROR,statusText:l,addr:u.bytes}}}getFirstUnverifiedMultiaddr(e,t){let n=this.components.addressManager.getAddressesWithMetadata().sort((o,i)=>o.type==="observed"&&i.type!=="observed"?1:i.type==="observed"&&o.type!=="observed"?-1:0).filter(o=>!(!(o.expires<Date.now())||ie(o.multiaddr).type==="ip6"&&(!t||!ym(o.multiaddr))||wt(o.multiaddr)));for(let o of n){let i=o.multiaddr.toString(),s=this.dialResults.get(i);if(s!=null){if(s.networkSegments.includes(e)){this.log.trace("%a already has a network segment result from %s",s.multiaddr,e);continue}if(s.queue.size>10){this.log.trace("%a already has enough peers queued",s.multiaddr);continue}}if(s==null){let a=o.expires<Date.now();if(a&&this.addressFilter.remove?.(i),this.addressFilter.has(i))continue;this.addressFilter.add(i),this.log.trace("creating dial result %s %s",a?"to revalidate":"for",i),s={multiaddr:o.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:q5(),queue:new Gt({concurrency:3,maxSize:50}),type:o.type,lastVerified:o.lastVerified},this.dialResults.set(i,s)}return s}}removeOutdatedMultiaddrResults(){let e=new Set(this.components.addressManager.getAddressesWithMetadata().filter(({expires:t})=>t<Date.now()).map(({multiaddr:t})=>t.toString()));for(let t of this.dialResults.keys())e.has(t)||(this.log.trace("remove results for %a",t),this.dialResults.delete(t))}async verifyExternalAddresses(e){if(!this.isStarted())return;this.removeOutdatedMultiaddrResults();let n=(await this.components.peerStore.get(e.remotePeer)).addresses.some(({multiaddr:s})=>ie(s).type==="ip6"),o=this.getNetworkSegment(e.remoteAddr),i=this.getFirstUnverifiedMultiaddr(o,n);if(i==null){this.log.trace("no unverified public addresses found for peer %p to verify, not requesting verification",e.remotePeer);return}if(!this.hasConnectionCapacity()){i.lastVerified!=null?(this.log("automatically re-verifying %a because we are too close to the connection limit",i.multiaddr),this.confirmAddress(i)):this.log("skipping verifying %a because we are too close to the connection limit",i.multiaddr);return}i.queue.add(async s=>{await this.askPeerToVerify(e,o,s)},{peerId:e.remotePeer,multiaddr:i.multiaddr}).catch(s=>{i?.result==null&&this.log.error("error from %p verifying address %a - %e",e.remotePeer,i?.multiaddr,s)})}async askPeerToVerify(e,t,n){let o=this.dialResults.get(n.multiaddr.toString());if(o==null){this.log("%a was verified while %p was queued",n.multiaddr,e.remotePeer);return}let i=AbortSignal.timeout(this.timeout);this.log.trace("asking %a to verify multiaddr %s",e.remoteAddr,n.multiaddr);let s=await e.newStream(this.protocol,{signal:i});try{let a=Xe(s).pb(Je),[,c]=await Promise.all([a.write({type:Je.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toMultihash().bytes,addrs:[n.multiaddr.bytes]}}},{signal:i}),a.read({signal:i})]);if(c.type!==Je.MessageType.DIAL_RESPONSE||c.dialResponse==null){this.log("invalid autonat response from %p - %j",e.remotePeer,c);return}let l=c.dialResponse.status;if(this.log.trace("autonat response from %p for %a is %s",e.remotePeer,n.multiaddr,l),l!==Je.ResponseStatus.OK&&l!==Je.ResponseStatus.E_DIAL_ERROR)return;if(o=this.dialResults.get(n.multiaddr.toString()),o==null){this.log.trace("peer reported %a as %s but there is no result object",n.multiaddr,c.dialResponse.status);return}if(o.networkSegments.includes(t)){this.log.trace("%a results included network segment %s",n.multiaddr,t);return}if(o.result!=null){this.log.trace("already resolved result for %a, ignoring response from",n.multiaddr,e.remotePeer);return}if(o.verifyingPeers.has(e.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",e.remotePeer,n.multiaddr);return}if(o.verifyingPeers.add(e.remotePeer),o.networkSegments.push(t),l===Je.ResponseStatus.OK){if(o.success++,o.type!=="observed"){this.confirmAddress(o);return}}else l===Je.ResponseStatus.E_DIAL_ERROR&&o.failure++;this.log("%a success %d failure %d",o.multiaddr,o.success,o.failure),o.success===mj&&this.confirmAddress(o),o.failure===gj&&this.unconfirmAddress(o)}finally{try{await s.close({signal:i})}catch(a){s.abort(a)}}}hasConnectionCapacity(){let t=this.components.connectionManager.getConnections().length,n=this.components.connectionManager.getMaxConnections();return t/n*100<this.connectionThreshold}confirmAddress(e){this.log("%s address %a is externally dialable",e.type,e.multiaddr),this.components.addressManager.confirmObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!0,e.queue.abort()}unconfirmAddress(e){this.log("%s address %a is not externally dialable",e.type,e.multiaddr),this.components.addressManager.removeObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!1,e.queue.abort()}getNetworkSegment(e){let t=ie(e);switch(t.type){case"ip4":return t.host.split(".")[0].padStart(3,"0");case"ip6":return t.host.split(":")[0].padStart(4,"0");default:throw new E(`Remote address ${e} was not an IPv4 or Ipv6 address`)}}};function Pk(r={}){return e=>new Ug(e,r)}var yj="bootstrap",wj=50,bj=1e3,Q7=class extends se{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??bj,this.list=t.list.map(n=>j(n)).filter(n=>Tl.matches(n)?n.getComponents().findLast(i=>i.code===421)?.value==null?(this.log.error("invalid bootstrap multiaddr without peer id"),!1):!0:(this.log.error("invalid multiaddr %a",n),!1)).map(n=>({id:Ee(n.getComponents().findLast(o=>o.code===421)?.value??""),multiaddrs:[n]})),this._init=t}[aa]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[be]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??yj]:{value:this._init.tagValue??wj,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function Dk(r){return e=>new Q7(e,r)}var Z7=1e3,Lk=60*Z7;var pAe=120*Lk,Nk=1,$g=5e3,Ok=100;var gh=`${ca}-circuit-relay`,mAe=2*Lk,gAe=BigInt(1<<17),wc="/libp2p/circuit/relay/0.2.0/hop",J7="/libp2p/circuit/relay/0.2.0/stop",yAe=30*Z7,wAe=30*Z7,eb=300,Bk=4096,Mk=.001;function bc(r=0){return new Uint8Array(r)}function Fk(r=0){return new Uint8Array(r)}var Os;(function(r){let e;(function(a){a.RESERVE="RESERVE",a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.RESERVE=0]="RESERVE",a[a.CONNECT=1]="CONNECT",a[a.STATUS=2]="STATUS"})(t||(t={})),(function(a){a.codec=()=>Ye(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=re((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Ls.codec().encode(a.peer,c)),a.reservation!=null&&(c.uint32(26),yh.codec().encode(a.reservation,c)),a.limit!=null&&(c.uint32(34),Ns.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(40),Mt.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=Ls.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.reservation=yh.codec().decode(a,a.uint32(),{limits:l.limits?.reservation});break}case 4:{u.limit=Ns.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 5:{u.status=Mt.codec().decode(a);break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*Ls.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*yh.codec().stream(a,a.uint32(),`${l}.reservation`,{limits:u.limits?.reservation});break}case 4:{yield*Ns.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 5:{yield{field:`${l}.status`,value:Mt.codec().decode(a)};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return ee(a,r.codec())}r.encode=o;function i(a,c){return J(a,r.codec(),c)}r.decode=i;function s(a,c){return te(a,r.codec(),c)}r.stream=s})(Os||(Os={}));var ei;(function(r){let e;(function(a){a.CONNECT="CONNECT",a.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.CONNECT=0]="CONNECT",a[a.STATUS=1]="STATUS"})(t||(t={})),(function(a){a.codec=()=>Ye(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=re((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.peer!=null&&(c.uint32(18),Ls.codec().encode(a.peer,c)),a.limit!=null&&(c.uint32(26),Ns.codec().encode(a.limit,c)),a.status!=null&&(c.uint32(32),Mt.codec().encode(a.status,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.peer=Ls.codec().decode(a,a.uint32(),{limits:l.limits?.peer});break}case 3:{u.limit=Ns.codec().decode(a,a.uint32(),{limits:l.limits?.limit});break}case 4:{u.status=Mt.codec().decode(a);break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield*Ls.codec().stream(a,a.uint32(),`${l}.peer`,{limits:u.limits?.peer});break}case 3:{yield*Ns.codec().stream(a,a.uint32(),`${l}.limit`,{limits:u.limits?.limit});break}case 4:{yield{field:`${l}.status`,value:Mt.codec().decode(a)};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return ee(a,r.codec())}r.encode=o;function i(a,c){return J(a,r.codec(),c)}r.decode=i;function s(a,c){return te(a,r.codec(),c)}r.stream=s})(ei||(ei={}));var Ls;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.id!=null&&i.id.byteLength>0&&(s.uint32(10),s.bytes(i.id)),i.addrs!=null&&i.addrs.length>0)for(let c of i.addrs)s.uint32(18),s.bytes(c);a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={id:bc(0),addrs:[]},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.id=i.bytes();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new le('Decode error - repeated field "addrs" had too many elements');c.addrs.push(i.bytes());break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={addrs:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${a}.id`,value:i.bytes()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new le('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:i.bytes()},l.addrs++;break}default:{i.skipType(d&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Ls||(Ls={}));var yh;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.expire!=null&&i.expire!==0n&&(s.uint32(8),s.uint64(i.expire)),i.addrs!=null&&i.addrs.length>0)for(let c of i.addrs)s.uint32(18),s.bytes(c);i.voucher!=null&&(s.uint32(26),bh.codec().encode(i.voucher,s)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={expire:0n,addrs:[]},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.expire=i.uint64();break}case 2:{if(a.limits?.addrs!=null&&c.addrs.length===a.limits.addrs)throw new le('Decode error - repeated field "addrs" had too many elements');c.addrs.push(i.bytes());break}case 3:{c.voucher=bh.codec().decode(i,i.uint32(),{limits:a.limits?.voucher});break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={addrs:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${a}.expire`,value:i.uint64()};break}case 2:{if(c.limits?.addrs!=null&&l.addrs===c.limits.addrs)throw new le('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${a}.addrs[]`,index:l.addrs,value:i.bytes()},l.addrs++;break}case 3:{yield*bh.codec().stream(i,i.uint32(),`${a}.voucher`,{limits:c.limits?.voucher});break}default:{i.skipType(d&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(yh||(yh={}));var Ns;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.duration!=null&&(s.uint32(8),s.uint32(i.duration)),i.data!=null&&(s.uint32(16),s.uint64(i.data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.duration=i.uint32();break}case 2:{c.data=i.uint64();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.duration`,value:i.uint32()};break}case 2:{yield{field:`${a}.data`,value:i.uint64()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Ns||(Ns={}));var Mt;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(Mt||(Mt={}));var tb;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(tb||(tb={}));(function(r){r.codec=()=>Ye(tb)})(Mt||(Mt={}));var wh;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.relay!=null&&i.relay.byteLength>0&&(s.uint32(10),s.bytes(i.relay)),i.peer!=null&&i.peer.byteLength>0&&(s.uint32(18),s.bytes(i.peer)),i.expiration!=null&&i.expiration!==0n&&(s.uint32(24),s.uint64(i.expiration)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={relay:bc(0),peer:bc(0),expiration:0n},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.relay=i.bytes();break}case 2:{c.peer=i.bytes();break}case 3:{c.expiration=i.uint64();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.relay`,value:i.bytes()};break}case 2:{yield{field:`${a}.peer`,value:i.bytes()};break}case 3:{yield{field:`${a}.expiration`,value:i.uint64()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(wh||(wh={}));var bh;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.publicKey!=null&&i.publicKey.byteLength>0&&(s.uint32(10),s.bytes(i.publicKey)),i.payloadType!=null&&i.payloadType.byteLength>0&&(s.uint32(18),s.bytes(i.payloadType)),i.payload!=null&&(s.uint32(26),wh.codec().encode(i.payload,s)),i.signature!=null&&i.signature.byteLength>0&&(s.uint32(42),s.bytes(i.signature)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={publicKey:bc(0),payloadType:bc(0),signature:bc(0)},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.publicKey=i.bytes();break}case 2:{c.payloadType=i.bytes();break}case 3:{c.payload=wh.codec().decode(i,i.uint32(),{limits:a.limits?.payload});break}case 5:{c.signature=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.publicKey`,value:i.bytes()};break}case 2:{yield{field:`${a}.payloadType`,value:i.bytes()};break}case 3:{yield*wh.codec().stream(i,i.uint32(),`${a}.payload`,{limits:c.limits?.payload});break}case 5:{yield{field:`${a}.signature`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(bh||(bh={}));var xh=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},Hg=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},qg=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function rb(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var Eh=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},Vg=Be(Ae(Tl.matchers[0],Oe(290))),Kg=Be(Oe(290));function $k(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Uk=$k("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),nb=$k("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=Fk(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),xj={utf8:Uk,"utf-8":Uk,hex:oe.base16,latin1:nb,ascii:nb,binary:nb,...oe},Hk=xj;function qk(r,e="utf8"){let t=Hk[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var zg=class extends se{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(wc,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(wc)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let i=Vk(n),s=Vk(o);return i>s?-1:s>i?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new Gt({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p - %e",n.id,o)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,o)})}async dialPeer({peerId:e,signal:t}){let n=ae([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function Vk(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(qk(e)).getTime()}var ob=class extends se{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??$g,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(Kg.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(Vg.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let i=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(i)}}else throw new sa(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>j(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function Kk(r){return new ob(r)}var zk="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Gk=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=zk[t[r]&63];return e};var Ej=60*1e3*10,vj=60*1e3*5,Sj=30*1e3,Gg=class extends se{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new mr,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??Ok,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??$g,this.started=!1,this.relayFilter=Lt(100),this.reserveQueue=new Gt({concurrency:t?.reservationConcurrency??Nk,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(i=>i.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(i=>{this.log("could not remove relay %p - %e",n.detail,i)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(gh)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[gh]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=Gk();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new sa("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new qg("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new sa("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let o=Date.now();try{let i=this.reservations.get(e);if(i!=null){let p=this.connectionManager.getConnections(e),y=!1;if(p.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),p.map(g=>g.id).includes(i.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),y=!0),y&&rb(i.reservation.expire)>Ej)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:i};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new xh("Not making reservation on discovered relay because we do not need any more relays");let s=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(e,{signal:s});if(Kt.matches(a.remoteAddr))throw new Hg("not creating reservation over relayed connection");let c=await this.#e(a,{signal:s}),l=rb(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-vj,Sj),Math.pow(2,31)-1),d=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async p=>{this.log.error("could not refresh reservation to relay %p - %e",e,p),await this.#t(e)}).catch(p=>{this.log.error("could not remove expired reservation to relay %p - %e",e,p)})},u),f;if(t==="discovered"){let p=this.pendingReservations.pop();if(p==null)throw new xh("Made reservation on relay but did not need any more discovered relays");f={timeout:d,reservation:c,type:t,connection:a.id,id:p}}else f={timeout:d,reservation:c,type:t,connection:a.id};this.reservations.set(e,f),await this.peerStore.merge(e,{tags:{[gh]:{value:1,ttl:l}}}),this.#r();let h={relay:e,details:f};return this.safeDispatchEvent("relay:created-reservation",{detail:h}),h}catch(i){throw t==="discovered"&&i.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-o,i),(i.name==="DialError"||i.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(s=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,s)}),i}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(wc,t),i=Xe(n).pb(Os);this.log.trace("send RESERVE to %p",e.remotePeer),await i.write({type:Os.Type.RESERVE},t);let s;try{this.log.trace("reading response from %p",e.remotePeer),s=await i.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",s.status),s.status===Mt.OK&&s.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of s.reservation.addrs){let u=j(l);u.getComponents().find(d=>d.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=j(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return s.reservation.addrs=[...c].map(l=>j(l).bytes),s.reservation}let a=`reservation failed with status ${s.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[gh]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=Lt(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var ib=class extends ps{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function sb(r){return new ib(r)}var Aj=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(j)}catch{return!1}return!0},Wk={maxInboundStopStreams:eb,maxOutboundStopStreams:eb,stopTimeout:3e4},Wg=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??Wk.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Wk.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new zg(e,{filter:t.discoveryFilter??V5(Bk,Mk)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,o)})}),this.reservationStore=new Gg(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[be]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[Zr](){return this.discovery!=null?["@libp2p/identify"]:[]}[Xi]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(J7,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await Rt(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await Ut(this.discovery,this.reservationStore),await this.components.registrar.unhandle(J7),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),o=j(n[0]),i=j(n[n.length-1]),s=o.getComponents().find(h=>h.code===421)?.value,a=i.getComponents().find(h=>h.code===421)?.value;if(s==null||a==null){let h=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${h}`),new ji(`C${h}`)}let c=Ee(s),l=Ee(a),d=this.components.connectionManager.getConnections(c)[0];d==null?(await this.components.peerStore.merge(c,{multiaddrs:[o]}),t.onProgress?.(new k("circuit-relay:open-connection")),d=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new k("circuit-relay:reuse-connection"));let f;try{t.onProgress?.(new k("circuit-relay:open-hop-stream")),f=await d.newStream(wc,t);let h=Xe(f).pb(Os);t.onProgress?.(new k("circuit-relay:write-connect-message")),await h.write({type:Os.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[j(i).bytes]}},t),t.onProgress?.(new k("circuit-relay:read-connect-response"));let p=await h.read(t);if(p.status!==Mt.OK)throw new he(`failed to connect via relay with status ${p?.status?.toString()??"undefined"}`);let y=new Eh(p.limit),g=sb({stream:h.unwrap().unwrap(),remoteAddr:e,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:y.onData,onDataWrite:y.onData,log:f.log.newScope("circuit-relay:connection")}),m=await this.components.upgrader.upgradeOutbound(g,{...t,limits:y.getLimits()});return m.log("outbound relayed connection established to %p with limits %o, over connection %s",m.remotePeer,p.limit??"none",d.id),m}catch(h){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,h),f?.abort(h),h}}createListener(e){return Kk({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>Vg.exactMatch(t)||Kg.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>Kt.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(d){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",d)}let o=Xe(e).pb(ei),i=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,i.type),i?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:ei.Type.STATUS,status:Mt.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(i.type!==ei.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:ei.Type.STATUS,status:Mt.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!Aj(i)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:ei.Type.STATUS,status:Mt.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let s=bt(xe(i.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,s)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:ei.Type.STATUS,status:Mt.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:ei.Type.STATUS,status:Mt.OK},{signal:n});let a=new Eh(i.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${s.toString()}`),l=this.components.addressManager.getAddresses()[0],u=sb({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",s,i.limit??"none",t.id)}finally{n?.clear()}}};function jk(r={}){return e=>new Wg(e,r)}var vo;(function(r){let e;(function(a){a.UNUSED="UNUSED",a.CONNECT="CONNECT",a.SYNC="SYNC"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.UNUSED=0]="UNUSED",a[a.CONNECT=100]="CONNECT",a[a.SYNC=300]="SYNC"})(t||(t={})),(function(a){a.codec=()=>Ye(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=re((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.observedAddresses!=null&&a.observedAddresses.length>0)for(let u of a.observedAddresses)c.uint32(18),c.bytes(u);l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={observedAddresses:[]},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{if(l.limits?.observedAddresses!=null&&u.observedAddresses.length===l.limits.observedAddresses)throw new le('Decode error - repeated field "observedAddresses" had too many elements');u.observedAddresses.push(a.bytes());break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={observedAddresses:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{if(u.limits?.observedAddresses!=null&&d.observedAddresses===u.limits.observedAddresses)throw new le('Streaming decode error - repeated field "observedAddresses" had too many elements');yield{field:`${l}.observedAddresses[]`,index:d.observedAddresses,value:a.bytes()},d.observedAddresses++;break}default:{a.skipType(h&7);break}}}})),n);function o(a){return ee(a,r.codec())}r.encode=o;function i(a,c){return J(a,r.codec(),c)}r.decode=i;function s(a,c){return te(a,r.codec(),c)}r.stream=s})(vo||(vo={}));function ab(r,e){return Kt.matches(r)||e.dialTransportForMultiaddr(r)==null?!1:Dm.matches(r)?!0:YS.matches(r)?!wt(r):!1}var Yk=1024*4,Xk=100,jg={timeout:5e3,retries:3,maxInboundStreams:1,maxOutboundStreams:1},Yg=class{started;timeout;retries;maxInboundStreams;maxOutboundStreams;peerStore;registrar;connectionManager;addressManager;transportManager;topologyId;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:dcutr"),this.started=!1,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.timeout=t.timeout??jg.timeout,this.retries=t.retries??jg.retries,this.maxInboundStreams=t.maxInboundStreams??jg.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??jg.maxOutboundStreams,this.handleIncomingUpgrade=this.handleIncomingUpgrade.bind(this)}[Symbol.toStringTag]="@libp2p/dcutr";[Zr]=["@libp2p/identify"];isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.registrar.register(vh,{notifyOnLimitedConnection:!0,onConnect:(e,t)=>{Kt.exactMatch(t.remoteAddr)&&t.direction==="inbound"&&this.upgradeInbound(t).catch(n=>{this.log.error("error during outgoing DCUtR attempt - %e",n)})}}),await this.registrar.handle(vh,this.handleIncomingUpgrade,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){await this.registrar.unhandle(vh),this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async upgradeInbound(e){if(await this.attemptUnilateralConnectionUpgrade(e))return;let t;for(let n=0;n<this.retries;n++){let o={signal:AbortSignal.timeout(this.timeout)};try{t=await e.newStream([vh],{signal:o.signal,runOnLimitedConnection:!0});let i=Xe(t,{maxDataLength:Yk}).pb(vo);this.log("B sending connect to %p",e.remotePeer);let s=Date.now();await i.write({type:vo.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(d=>d.bytes)},o),this.log("B receiving connect from %p",e.remotePeer);let a=await i.read(o);if(a.type!==vo.Type.CONNECT)throw this.log("A sent wrong message type"),new he("DCUtR message type was incorrect");let c=this.getDialableMultiaddrs(a.observedAddresses);if(c.length===0)throw this.log("A did not have any dialable multiaddrs"),new he("DCUtR connect message had no multiaddrs");let l=Date.now()-s;this.log("A sending sync, rtt %dms",l),await i.write({type:vo.Type.SYNC,observedAddresses:[]},o),this.log("A waiting for half RTT"),await ST(l/2),this.log("B dialing",c);let u=await this.connectionManager.openConnection(c,{signal:o.signal,priority:Xk,force:!0,initiator:!1});this.log("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,u.remoteAddr),await e.close(o);break}catch(i){if(this.log.error("error while attempting DCUtR on attempt %d of %d - %e",n+1,this.retries,i),t?.abort(i),n===this.retries)throw i}finally{t!=null&&await t.close(o)}}}async attemptUnilateralConnectionUpgrade(e){let n=(await this.peerStore.get(e.remotePeer)).addresses.map(o=>{let i=o.multiaddr;return i.getComponents().find(s=>s.code===421)?.value==null?i.encapsulate(`/p2p/${e.remotePeer}`):i}).filter(o=>ab(o,this.transportManager));if(n.length>0){let o=AbortSignal.timeout(this.timeout);try{this.log("attempting unilateral connection upgrade to %a",n);let i=await this.connectionManager.openConnection(n,{signal:o,force:!0});if(Kt.exactMatch(i.remoteAddr))throw new Error("Could not open a new, non-limited, connection");return this.log("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,i.remoteAddr),await e.close({signal:o}),!0}catch(i){this.log.error("unilateral connection upgrade to %p on addresses %a failed - %e",e.remotePeer,n,i)}}else this.log("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}async handleIncomingUpgrade(e,t){let n={signal:AbortSignal.timeout(this.timeout)},o=Xe(e,{maxDataLength:Yk}).pb(vo);this.log("A receiving connect");let i=await o.read(n);if(i.type!==vo.Type.CONNECT)throw this.log("B sent wrong message type"),new he("DCUtR message type was incorrect");if(i.observedAddresses.length===0)throw this.log("B sent no multiaddrs"),new he("DCUtR connect message had no multiaddrs");let s=this.getDialableMultiaddrs(i.observedAddresses);if(s.length===0)throw this.log("B had no dialable multiaddrs in %o",i.observedAddresses.map(l=>j(l))),new he("DCUtR connect message had no dialable multiaddrs");if(this.log("A sending connect"),await o.write({type:vo.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(l=>l.bytes)}),this.log("A receiving sync"),(await o.read(n)).type!==vo.Type.SYNC)throw new he("DCUtR message type was incorrect");this.log("A dialing",s);let c=await this.connectionManager.openConnection(s,{signal:n.signal,priority:Xk,force:!0});this.log("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,c.remoteAddr),await t.close(n),await e.close(n)}getDialableMultiaddrs(e){let t=[];for(let n of e)if(!(n==null||n.length===0))try{let o=j(n);if(!ab(o,this.transportManager))continue;t.push(o)}catch{}return t}};var vh="/libp2p/dcutr";function Qk(r={}){return e=>new Yg(e,r)}function X(r){if(r!==void 0&&r!==X.REQUEST&&r!==X.RESPONSE)throw new Error("type must be REQUEST or RESPONSE");r===void 0||this.initialize(r),this.maxHeaderSize=X.maxHeaderSize}X.prototype.initialize=function(r,e){if(r!==X.REQUEST&&r!==X.RESPONSE)throw new Error("type must be REQUEST or RESPONSE");this.type=r,this.state=r+"_LINE",this.info={headers:[],upgrade:!1},this.trailers=[],this.line="",this.isChunked=!1,this.connection="",this.headerSize=0,this.body_bytes=null,this.isUserCall=!1,this.hadError=!1};X.encoding="ascii";X.maxHeaderSize=80*1024;X.REQUEST="REQUEST";X.RESPONSE="RESPONSE";var Zk=X.kOnHeaders=1,cb=X.kOnHeadersComplete=2,Xg=X.kOnBody=3,lb=X.kOnMessageComplete=4;X.prototype[Zk]=X.prototype[cb]=X.prototype[Xg]=X.prototype[lb]=function(){};var Jk=!0;Object.defineProperty(X,"kOnExecute",{get:function(){return Jk=!1,99}});var eR=X.methods=["DELETE","GET","HEAD","POST","PUT","CONNECT","OPTIONS","TRACE","COPY","LOCK","MKCOL","MOVE","PROPFIND","PROPPATCH","SEARCH","UNLOCK","BIND","REBIND","UNBIND","ACL","REPORT","MKACTIVITY","CHECKOUT","MERGE","M-SEARCH","NOTIFY","SUBSCRIBE","UNSUBSCRIBE","PATCH","PURGE","MKCALENDAR","LINK","UNLINK","SOURCE"],tR=eR.indexOf("CONNECT");X.prototype.reinitialize=X;X.prototype.close=X.prototype.pause=X.prototype.resume=X.prototype.remove=X.prototype.free=function(){};X.prototype._compatMode0_11=!1;X.prototype.getAsyncId=function(){return 0};var Tj={REQUEST_LINE:!0,RESPONSE_LINE:!0,HEADER:!0};X.prototype.execute=function(r,e,t){if(!(this instanceof X))throw new TypeError("not a HTTPParser");e=e||0,t=typeof t=="number"?t:r.length,this.chunk=r,this.offset=e;var n=this.end=e+t;try{for(;this.offset<n&&!this[this.state](););}catch(o){if(this.isUserCall)throw o;return this.hadError=!0,o}return this.chunk=null,t=this.offset-e,Tj[this.state]&&(this.headerSize+=t,this.headerSize>(this.maxHeaderSize||X.maxHeaderSize))?new Error("max header size exceeded"):t};var _j={REQUEST_LINE:!0,RESPONSE_LINE:!0,BODY_RAW:!0};X.prototype.finish=function(){if(!this.hadError){if(!_j[this.state])return new Error("invalid state for EOF");this.state==="BODY_RAW"&&this.userCall()(this[lb]())}};X.prototype.consume=X.prototype.unconsume=X.prototype.getCurrentBuffer=function(){};X.prototype.userCall=function(){this.isUserCall=!0;var r=this;return function(e){return r.isUserCall=!1,e}};X.prototype.nextRequest=function(){this.userCall()(this[lb]()),this.reinitialize(this.type)};X.prototype.consumeLine=function(){for(var r=this.end,e=this.chunk,t=this.offset;t<r;t++)if(e[t]===10){var n=this.line+de(e.subarray(this.offset,t),X.encoding);return n.charAt(n.length-1)==="\r"&&(n=n.substr(0,n.length-1)),this.line="",this.offset=t+1,n}this.line+=de(e.subarray(this.offset,this.end),X.encoding),this.offset=this.end};var Cj=/^([^: \t]+):[ \t]*((?:.*[^ \t])|)/,Ij=/^[ \t]+(.*[^ \t])/;X.prototype.parseHeader=function(r,e){if(r.indexOf("\r")!==-1)throw Qg("HPE_LF_EXPECTED");var t=Cj.exec(r),n=t&&t[1];if(n)e.push(n),e.push(t[2]);else{var o=Ij.exec(r);o&&e.length&&(e[e.length-1]&&(e[e.length-1]+=" "),e[e.length-1]+=o[1])}};var kj=/^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/;X.prototype.REQUEST_LINE=function(){var r=this.consumeLine();if(r){var e=kj.exec(r);if(e===null)throw Qg("HPE_INVALID_CONSTANT");if(this.info.method=this._compatMode0_11?e[1]:eR.indexOf(e[1]),this.info.method===-1)throw new Error("invalid request method");this.info.url=e[2],this.info.versionMajor=+e[3],this.info.versionMinor=+e[4],this.body_bytes=0,this.state="HEADER"}};var Rj=/^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/;X.prototype.RESPONSE_LINE=function(){var r=this.consumeLine();if(r){var e=Rj.exec(r);if(e===null)throw Qg("HPE_INVALID_CONSTANT");this.info.versionMajor=+e[1],this.info.versionMinor=+e[2];var t=this.info.statusCode=+e[3];this.info.statusMessage=e[4],((t/100|0)===1||t===204||t===304)&&(this.body_bytes=0),this.state="HEADER"}};X.prototype.shouldKeepAlive=function(){if(this.info.versionMajor>0&&this.info.versionMinor>0){if(this.connection.indexOf("close")!==-1)return!1}else if(this.connection.indexOf("keep-alive")===-1)return!1;return!!(this.body_bytes!==null||this.isChunked)};X.prototype.HEADER=function(){var r=this.consumeLine();if(r!==void 0){var e=this.info;if(r)this.parseHeader(r,e.headers);else{for(var t=e.headers,n=!1,o,i=!1,s=0;s<t.length;s+=2)switch(t[s].toLowerCase()){case"transfer-encoding":this.isChunked=t[s+1].toLowerCase()==="chunked";break;case"content-length":if(o=+t[s+1],n){if(o!==this.body_bytes)throw Qg("HPE_UNEXPECTED_CONTENT_LENGTH")}else n=!0,this.body_bytes=o;break;case"connection":this.connection+=t[s+1].toLowerCase();break;case"upgrade":i=!0;break}this.isChunked&&n&&(n=!1,this.body_bytes=null),i&&this.connection.indexOf("upgrade")!=-1?e.upgrade=this.type===X.REQUEST||e.statusCode===101:e.upgrade=e.method===tR,this.isChunked&&e.upgrade&&(this.isChunked=!1),e.shouldKeepAlive=this.shouldKeepAlive();var a;if(Jk?a=this.userCall()(this[cb](e)):a=this.userCall()(this[cb](e.versionMajor,e.versionMinor,e.headers,e.method,e.url,e.statusCode,e.statusMessage,e.upgrade,e.shouldKeepAlive)),a===2)return this.nextRequest(),!0;if(this.isChunked&&!a)this.state="BODY_CHUNKHEAD";else{if(a||this.body_bytes===0)return this.nextRequest(),e.upgrade;this.body_bytes===null?this.state="BODY_RAW":this.state="BODY_SIZED"}}}};X.prototype.BODY_CHUNKHEAD=function(){var r=this.consumeLine();r!==void 0&&(this.body_bytes=parseInt(r,16),this.body_bytes?this.state="BODY_CHUNK":this.state="BODY_CHUNKTRAILERS")};X.prototype.BODY_CHUNK=function(){var r=Math.min(this.end-this.offset,this.body_bytes);this.userCall()(this[Xg](this.chunk.slice(this.offset,this.offset+r),0,r)),this.offset+=r,this.body_bytes-=r,this.body_bytes||(this.state="BODY_CHUNKEMPTYLINE")};X.prototype.BODY_CHUNKEMPTYLINE=function(){var r=this.consumeLine();if(r!==void 0){if(r!=="")throw new Error("Expected empty line");this.state="BODY_CHUNKHEAD"}};X.prototype.BODY_CHUNKTRAILERS=function(){var r=this.consumeLine();r!==void 0&&(r?this.parseHeader(r,this.trailers):(this.trailers.length&&this.userCall()(this[Zk](this.trailers,"")),this.nextRequest()))};X.prototype.BODY_RAW=function(){this.userCall()(this[Xg](this.chunk.slice(this.offset,this.end),0,this.end-this.offset)),this.offset=this.end};X.prototype.BODY_SIZED=function(){var r=Math.min(this.end-this.offset,this.body_bytes);this.userCall()(this[Xg](this.chunk.slice(this.offset,this.offset+r),0,r)),this.offset+=r,this.body_bytes-=r,this.body_bytes||this.nextRequest()};["Headers","HeadersComplete","Body","MessageComplete"].forEach(function(r){var e=X["kOn"+r];Object.defineProperty(X.prototype,"on"+r,{get:function(){return this[e]},set:function(t){return this._compatMode0_11=!0,tR="CONNECT",this[e]=t}})});function Qg(r){var e=new Error("Parse Error");return e.code=r,e}function rR(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function Kn(r,e={}){let t=rR(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(o){try{let{value:i,done:s}=await t.next();if(this._cancelled)return;if(s===!0){o.close();return}o.enqueue(i)}catch(i){o.error(i)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}var Pj=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),nR=li({name:"sha-1",code:17,encode:Pj("SHA-1")});var Zg=class extends globalThis.Request{constructor(e,t={}){let n=t.method??"GET",o=ti(t),i=t.body;Jg(n,o)&&(t.method="UPGRADE"),super(e,t),Object.defineProperties(this,{body:{value:i,writable:!1},method:{value:n,writable:!1},headers:{value:o,writable:!1}})}};var oR={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};var ri=class extends globalThis.Response{constructor(e,t={}){let n=ti(t),o=t.status??200;(o<200||o>599)&&(t.status=200),super(e,t),Object.defineProperties(this,{status:{value:o,writable:!1},statusText:{value:oR[o],writable:!1},headers:{value:n,writable:!1}})}};var Dj=["dns","dns4","dns6","dnsaddr"];function Ah(r,e){if(r instanceof URL)return r;let t=t3(r,e),{httpPath:n}=r3(r);return new URL(`http://${t}${n}`)}function Th(r){return r instanceof Uint8Array?r:r instanceof DataView?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r,0,r.byteLength)}function sR(r,e){let t={method:r.method,headers:r.headers};if((t.method!=="GET"||r.upgrade)&&t.method!=="HEAD"){let n=e;r.upgrade||(n=Nj(e,r.headers.get("content-length"))),t.body=Kn(n),t.duplex="half"}return new Zg(ub(r).toString(),t)}async function aR(r,e){if(e.send(K([`HTTP/1.1 ${r.status} ${r.statusText}`,...e3(r.headers),"",""].join(`\r
52
52
  `))),r.body==null){await e.close().catch(n=>{e.abort(n)});return}let t=r.body.getReader();for(;;){let n=await t.read();if(n.value!=null&&(e.send(n.value)||await e.onDrain()),n.done)break}await e.close().catch(n=>{e.abort(n)})}var cR=K(["HTTP/1.1 404 Not Found","Connection: close","",""].join(`\r
53
53
  `)),Lj=K(["HTTP/1.1 400 Bad Request","Connection: close","",""].join(`\r
54
54
  `)),E_e=K(["HTTP/1.1 500 Internal Server Error","Connection: close","",""].join(`\r
@@ -62,7 +62,7 @@ ${e.join(`
62
62
  \r
63
63
  `)),n.close())}})}function fb(r,e){return e.set("Content-Length",`${r.length}`),e.set("Content-Type",'text/plain; charset="UTF-8"'),new ReadableStream({start(t){t.enqueue(K(r)),t.close()}})}function mR(r,e){if(r!=null){if(typeof r=="string")return fb(r,e);if(r instanceof Blob)return dR(r,e);if(Fj(r))return fR(r,e);if(r instanceof URLSearchParams)return fb(r.toString(),e);if(r instanceof ReadableStream)return pR(r,e);if(r instanceof FormData)return hR(r,e);throw new Error("Unsupported body type")}}function Fj(r){return r==null?!1:r.byteLength!=null}async function gR(r,e,t){let n=new Headers(t.headers),o=n.get("host")??e.hostname;n.set("host",o),n.get("user-agent")==null&&n.set("user-agent","libp2p/fetch");let i=mR(t.body,n),s=[`${t?.method?.toUpperCase()??"GET"} ${e.pathname??"/"} HTTP/1.1`,...e3(n),"",""];r.send(K(s.join(`\r
64
64
  `)))||await r.onDrain({signal:t.signal??void 0}),i!=null&&(t.log("request sending body"),await Uj(r,i,t))}async function Uj(r,e,t){let n=e.getReader();for(;;){let{done:o,value:i}=await n.read();if(i!=null&&(t.log("request send %d bytes",i.byteLength),r.send(i)||await r.onDrain({signal:t.signal??void 0})),o){t.log("request finished sending body");break}}}async function yR(r,e,t={}){let n=r.log.newScope("http-fetch");e=typeof e=="string"?new URL(e):e;let[o]=await Promise.all([uR(r,e,{...t,log:n}),gR(r,e,{...t,log:n})]);return await r.close({signal:t.signal??void 0}),o}var i3=class extends Event{message;error;filename="";lineno=0;colno=0;constructor(e){super("error"),this.error=e,this.message=e.message}},_h=class extends Event{code;reason;wasClean;constructor(e,t){super(e),this.code=t?.code??0,this.reason=t?.reason??"",this.wasClean=t?.wasClean??!0}};var $j={CONTINUATION:0,TEXT:1,BINARY:2,CONNECTION_CLOSE:8,PING:9,PONG:10},hb={0:"CONTINUATION",1:"TEXT",2:"BINARY",8:"CONNECTION_CLOSE",9:"PING",10:"PONG"};var Ch={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,PROTOCOL_ERROR:1002,UNSUPPORTED_DATA:1003,RESERVED:1004,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,INVALID_FRAME_PAYLOAD_DATA:1007,POLICY_VIOLATION:1008,MESSAGE_TOO_BIG:1009,MANDATORY_EXT:1010,INTERNAL_SERVER_ERROR:1011,TLS_HANDSHAKE:1015};function wR(r){let e=0;if(r.byteLength<e+1)return;let n=r.get(e)&15;if(e++,hb[n]==null)throw new Error(`Unknown opcode: ${n}`);if(r.byteLength<e+1)return;let o=r.get(e),i=(o&128)===128,s=o&127;if(e++,s===126){if(r.byteLength<e+2)return;s=r.getUint16(e),e+=2}else if(s===127){if(r.byteLength<e+8)return;s=r.getUint32(e),e+=8}if(s===0)return r.consume(e),{type:hb[n]};let a;if(i){if(r.byteLength<e+4)return;a=r.subarray(e,e+4),e+=4}if(r.byteLength<e+s)return;let c=r.subarray(e,e+s);return e+=s,a!=null&&(c=bR(c,a)),r.consume(e),{type:hb[n],data:c}}function bR(r,e){let t=0;for(let n=0;n<r.byteLength;n++)r[n]=r[n]^e[t],t++,t===e.byteLength&&(t=0);return r}function xR(r,e,t){let o=new G(Uint8Array.from([128|$j[r]])),i=e?.byteLength??0;if(i<126)o.append(Uint8Array.from([i|(t===!0?128:0)]));else if(i<65535){let s=new G(new Uint8Array(3));s.set(0,126|(t===!0?128:0)),s.setUint16(1,i),o.append(s)}else if(i<18446744073709552e3){let s=new G(new Uint8Array(9));s.set(0,127|(t===!0?128:0)),s.setUint32(1,i),o.append(s)}else throw new Error("Payload too large");if(t===!0&&e!=null){let s=Uint8Array.from([0,0,0,0]);o.append(s),e=bR(e,s)}return e!=null&&o.append(e),o}function ER(r){if(r instanceof Uint8Array||r instanceof ArrayBuffer||r instanceof DataView)return Th(r);if(typeof r=="string")return K(r);if(r instanceof Blob)return r.arrayBuffer().then(e=>Th(e));throw new E("Unsupported data type")}async function vR(r,e){return new Promise((t,n)=>{let o=!1,i=new X("RESPONSE");i[X.kOnHeadersComplete]=s=>{o=!0;let a=[];for(let c=0;c<s.headers.length;c+=2)a.push([s.headers[c],s.headers[c+1]]);t(new ri(null,{status:s.statusCode,statusText:s.statusMessage,headers:new Headers(a)}))},Promise.resolve().then(async()=>{for(;;){let{data:s}=await Dr(r,"message",e.signal),a=s.subarray(),c=i.execute(a,0,a.byteLength);if(c instanceof Error)throw c;if(c<a.byteLength&&r.push(a.subarray(c)),o)break}}).catch(s=>{n(s)})})}async function*SR(r,e=[],t){let n=ld.encode(crypto.getRandomValues(new Uint8Array(16))).substring(1);t.set("host",r.hostname),t.set("connection","upgrade"),t.set("upgrade","websocket"),t.set("pragma","no-cache"),t.set("cache-control","no-cache"),t.set("sec-websocket-version","13"),t.set("sec-websocket-key",n),e.length>0&&t.set("sec-websocket-protocol",e.join(", ")),yield K([`GET ${r.pathname??"/"} HTTP/1.1`,...[...t.entries()].map(([o,i])=>`${o}: ${i}`),"",""].join(`\r
65
- `))}var Hj=["BINARY","TEXT","CONTINUATION"],qj=10485760;var Vj="/http/1.1",s3=class extends se{binaryType="arraybuffer";bufferedAmount=0;extensions="";protocol="";readyState;url;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;_onclose;_onerror;_onmessage;_onopen;sentClose;isClient;buffer;maxMessageSize;_url;closeController;constructor(e,t={}){super(),this.readyState=this.CONNECTING,this.url=e.pathname,this.sentClose=!1,this.isClient=t.isClient??!0,this.buffer=new G,this.closeController=new AbortController,this.maxMessageSize=t.maxMessageSize??qj}send(e){if(this.readyState!==this.OPEN)throw new Error("WebSocket was not open");let t=ER(e);ms(t)?t.then(n=>{this._send("BINARY",n)}).catch(n=>{this._errored(n)}):this._send("BINARY",t)}_send(e,t){if(this.readyState!==this.OPEN)return;let n=xR(e,t,this.isClient),o=n.byteLength;this.bufferedAmount+=o,this._write(n,i=>{this.bufferedAmount-=o,i!=null&&this._errored(i)})}close(e,t){if(this.readyState!==this.OPEN)throw new Error("WebSocket was not open");this.readyState=this.CLOSING,this.sentClose=!0,this._send("CONNECTION_CLOSE")}_errored(e){this.readyState=this.CLOSED,this.dispatchEvent(new i3(e))}set onclose(e){this._onclose=e,this.addEventListener("close",e)}get onclose(){return this._onclose??null}set onerror(e){this._onerror=e,this.addEventListener("error",e)}get onerror(){return this._onerror??null}set onmessage(e){this._onmessage=e,this.addEventListener("message",e)}get onmessage(){return this._onmessage??null}set onopen(e){this._onopen=e,this.addEventListener("open",e)}get onopen(){return this._onopen??null}_push(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxMessageSize){this.close(Ch.MESSAGE_TOO_BIG,"Max message size exceeded");return}for(;;){let t=wR(this.buffer);if(t==null)break;if(Hj.includes(t.type)&&t.data!=null){let n;this.binaryType==="blob"?n=new Blob([t.data]):t.data.byteOffset===0&&t.data.byteLength===t.data.buffer.byteLength?n=t.data.buffer:(n=new ArrayBuffer(t.data.byteLength),new Uint8Array(n,0,n.byteLength).set(t.data)),this.dispatchEvent(new MessageEvent("message",{data:n,origin:this._url?.hostname}))}t.type==="PING"&&this._send("PONG",t.data),t.type==="CONNECTION_CLOSE"&&(this.sentClose||this.close(),this.closeController.abort(),this._close(void 0,()=>{this.readyState=this.CLOSED,this.dispatchEvent(new _h("close"))}))}}_remoteClosed(e){this.readyState=this.CLOSING,this._close(e,()=>{this.readyState=this.CLOSED,this.dispatchEvent(new _h("close"))})}};var Ih=class extends s3{writer;writable;constructor(e,t,n={}){if(super(new URL(e.url),{...n,isClient:!1}),e.body==null)throw new E("Request body cannot be null");this.readyState=this.OPEN,this.writable=t,this.writer=t.getWriter();let o=e.body.getReader();Promise.resolve().then(async()=>{for(this.dispatchEvent(new Event("open"));;){let{value:i,done:s}=await o.read();if(i!=null&&this._push(i),s){this._remoteClosed();break}}}).catch(i=>{this._errored(i)})}_write(e,t){this.writer?.write(e).then(()=>{t()},n=>{t(n)})}_close(e,t){e!=null?this.writable.abort(e).then(()=>{t()},()=>{t()}):this.writable.close().then(()=>{t()},()=>{t()})}},kh=class extends s3{stream;handshakeTimeout;drainTimeout;constructor(e,t,n,o){super(t,{...o,isClient:!0}),this.handshakeTimeout=o.handshakeTimeout??1e4,this.drainTimeout=o.drainTimeout??1e4,Promise.resolve().then(async()=>{let i=AbortSignal.timeout(this.handshakeTimeout);this.stream=await n.openStream(e,Vj,{...o,signal:i});for await(let a of SR(t,o.protocols,ti(o)))this.stream.send(a)||await this.stream.onDrain({signal:i});let s=await vR(this.stream,{signal:i});if(s.status!==101)throw new Error("Invalid WebSocket handshake - response status "+s.status);await o.onHandshakeResponse?.(s,{signal:i}),this.protocol=s.headers.get("Sec-WebSocket-Protocol")??"",this.readyState=this.OPEN,this.dispatchEvent(new Event("open"));for await(let a of this.stream)this._push(a)}).catch(i=>{this._errored(i)})}_write(e,t){if(this.stream==null){t(new Error("WebSocket was not open"));return}this.stream.send(e)?t():this.stream.onDrain({signal:AbortSignal.timeout(this.drainTimeout)}).then(()=>{t()},n=>{t(n)})}_close(e,t){if(this.stream==null){t();return}if(e!=null){this.stream.abort(e),t();return}this.stream.close().catch(n=>{this.stream?.abort(n)}).finally(()=>{t()})}};var Rh="/http/1.1";var a3=Symbol.for("@libp2p/http/websocket-handler");var RR=Yt(IR(),1),l3=class{log;cookies;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:http:cookies"),this.cookies=new Map}async prepareRequest(e,t){if((t.credentials??"same-origin")==="omit")return;let o=t.headers.get("origin");if(o==null||o==="null")return;let i=Ah(e,t.headers),s=(this.cookies.get(i.hostname)??[]).filter(a=>!(a.expires!=null&&a.expires<Date.now()||a.path!=null&&!i.pathname.startsWith(a.path))).map(a=>`${a.name}=${a.value}`).join("; ");s.length>0&&t.headers.set("cookie",s)}async processResponse(e,t,n){if((t.credentials??"same-origin")==="omit"){kR(n);return}let i=t.headers.get("origin");if(i==null||i==="null")return;let s=Ah(e,t.headers);for(let a of n.headers.getSetCookie()){let c=[...this.cookies.get(s.hostname)??[],...Zj(RR.default.parse(a))];this.cookies.set(s.hostname,c)}kR(n)}};function kR(r){return r.headers.has("set-cookie")&&r.headers.delete("set-cookie"),r}function Zj(r){let e={},t=[];return Object.entries(r).forEach(([n,o])=>{n.toLowerCase()==="domain"&&o!=null&&(e.domain=o),n.toLowerCase()==="max-age"&&o!=null&&(e.expires=Date.now()+parseInt(o,10)*1e3),!Jj.includes(n.toLowerCase())&&o!=null&&t.push({name:n,value:o})}),t.map(n=>({...n,...e}))}var Jj=["domain","expires","httponly","max-age","partitioned","path","samesite","secure"];var u3=class{async prepareRequest(e,t){if(t.headers.get("origin")!=null||t.mode==="no-cors")return;let n=Ah(e,t.headers);t.headers.set("origin",`${n.protocol}//${n.host}`)}};function eY(r){return typeof r.init=="function"}function d3(r,e){if(eY(r)){let t=r;return t.handler=r.init(e),delete t.init,t}return r}function PR(r){let e=n3(r.method,["GET"]);if(r.fallback==null&&e.filter(n=>n!=="GET").length>0)throw new E("WebSocket handlers only support the GET HTTP method");let t={...r,init:n=>{let o=d3(r,n);return t[a3]=o.handler,async i=>{if(!Jg(i.method,i.headers))return r?.fallback!=null?r.fallback(i):new ri(null,{status:400});let s=new TransformStream;try{let a=new ri(s.readable,{status:101,headers:await db(i.headers)}),c=new Ih(i,s.writable,r);return o.handler(c),a}catch{return new ri(null,{status:500})}}}};return t}var f3="/.well-known/libp2p/protocols";function DR(r){return PR({path:f3,method:["GET"],cors:!0,handler:e=>{let t=JSON.stringify(r.getProtocolMap());e.send(t),e.close()},fallback:async e=>{let t=JSON.stringify(r.getProtocolMap());return new Response(t,{headers:{"Content-Type":"application/json","Content-Length":`${t.length}`}})}})}var h3=class{log;components;protocols;endpoint;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:http:registrar"),this.protocols=[],this.onStream=this.onStream.bind(this),this.endpoint=t.server,this.handle("",DR(this))}async start(){await this.components.registrar.handle(Rh,this.onStream.bind(this))}async stop(){await this.components.registrar.unhandle(Rh)}async onStream(e,t){let n=await lR(e);if(this.canHandle(n)){this.log("handling incoming request %s %s",n.method,n.url);let o=await this.onRequest(sR(n,e));await aR(o,e),await e.close();return}if(this.endpoint==null){this.log("cannot handle incoming request %s %s and no endpoint configured",n.method,n.url),e.send(cR),await e.close();return}this.log("passing incoming request %s %s to endpoint",n.method,n.url),this.endpoint.inject(n,e,t).catch(o=>{this.log.error("error injecting request to endpoint - %e",o),e.abort(o)})}canHandle(e){let t=ub(e).pathname;return this.protocols.find(n=>n.route.path===t)!=null?(this.log.trace("can handle %s",t),!0):(this.log.trace("cannot handle %s",t),!1)}async onRequest(e){this.log("incoming request %s %s",e.method,e.url);let t=this.findHandler(e.url);if(t==null)return new Response(null,{status:404});let n;return t.route.method.includes(e.method)?n=await t.route.handler(e):e.method==="OPTIONS"?n=new Response(null,{status:204}):n=new Response(null,{status:405}),tY(n,e,t),this.log("%s %s %d %s",e.method,e.url,n.status,n.statusText),n}onWebSocket(e){let t=this.findHandler(e.url);if(t!=null){let n=t.route[a3];if(n!=null){n(e);return}}e.close(Ch.NORMAL_CLOSURE)}findHandler(e){let t=e.startsWith("/")?e:new URL(e).pathname;this.log("search for handler on path %s",t);let n=this.protocols.find(o=>o.route.path===t);return n!=null&&this.log("found handler for HTTP protocol %s on path %s",n.protocol,e),n}handle(e,t){if(t.path=t.path??e,this.protocols.find(n=>n.protocol===e)!=null)throw new E(`HTTP protocol handler for ${e} already registered`);(t.path===""||!t.path.startsWith("/"))&&(t.path=`/${t.path}`),t.cors=t.cors??!0,t.method=n3(t.method),t=d3(t,this.components),this.protocols.push({protocol:e,route:t}),this.protocols.sort(({route:{path:n}},{route:{path:o}})=>o.length-n.length)}unhandle(e){this.protocols=this.protocols.filter(t=>t.protocol===e)}getProtocolMap(){let e={};for(let t of this.protocols)t.protocol!==""&&(e[t.protocol]={path:t.route.path});return e}};function tY(r,e,t){let n=[...new Set(["OPTIONS",...t.route.method])].join(", ");t.route.cors&&(e.headers.get("Access-Control-Request-Method")!=null&&r.headers.set("access-control-allow-methods",n),e.headers.get("Access-Control-Request-Headers")!=null&&r.headers.set("access-control-allow-headers",e.headers.get("Access-Control-Request-Headers")??""),e.headers.get("Origin")!=null&&(r.headers.set("access-control-allow-origin",e.headers.get("Origin")??""),r.headers.set("vary","Origin"))),e.method==="OPTIONS"&&r.headers.set("allow",n)}async function LR(r,e,t){for(let n of e.middleware)await n.prepareRequest?.(r,e);return t()}async function NR(r,e,t){for(let n of e.middleware)await n.prepareRequest?.(r,e);return t()}async function OR(r,e,t){for(let n of e.middleware)await n.processResponse?.(r,e,t);return t}var p3=class{log;components;httpRegistrar;origin;cookies;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:http"),this.httpRegistrar=new h3(e,t),this.origin=new u3,this.cookies=new l3(e,t)}[Symbol.toStringTag]="@libp2p/http";[be]=["@libp2p/http"];async start(){await Rt(this.httpRegistrar)}async stop(){await Ut(this.httpRegistrar)}agent(...e){throw new ed("This method is not supported in browsers")}dispatcher(...e){throw new ed("This method is not supported in browsers")}async connect(e,t={}){let n=Eu(e),o=ti(t),i={...t,headers:o,method:"GET",middleware:t.middleware?.map(s=>s(this.components))??[]};return o.set("connection","upgrade"),o.set("upgrade","websocket"),NR(n,i,async()=>{if(n instanceof URL){let c=new globalThis.WebSocket(n,t.protocols);return c.binaryType="arraybuffer",c}let{addresses:s,httpPath:a}=r3(n);return new kh(s,new URL(`http://${t3(n,i.headers)}${decodeURIComponent(a)}`),this.components.connectionManager,i)})}async fetch(e,t={}){let n=Eu(e),o={...t,headers:ti(t),method:"GET",middleware:[this.origin,this.cookies,...t.middleware?.map(s=>s(this.components))??[]]},i=await LR(n,o,async()=>this.sendRequest(n,t));return OR(n,o,i)}async connectProtocol(e,t,n){let o=await this.getProtocolPath(e,t,n),i=Eu(e,o);return this.connect(i,n)}async fetchProtocol(e,t,n={}){let o=await this.getProtocolPath(e,t,n),i=Eu(e,o);return this.fetch(i,n)}async getSupportedProtocols(e,t={}){let n=Eu(e,f3),o=await this.fetch(n,{method:"GET",headers:{Accept:"application/json"},signal:t.signal});if(o.status!==200)throw new Error(`Unexpected status code: ${o.status}`);return o.json()}async getProtocolPath(e,t,n={}){let o=await this.getSupportedProtocols(e,n);if(o[t]==null)throw new Error(`Peer does not serve protocol: ${t}`);return o[t].path}canHandle(e){return this.httpRegistrar.canHandle(e)}async onRequest(e){return this.httpRegistrar.onRequest(e)}onWebSocket(e){this.httpRegistrar.onWebSocket(e)}handle(e,t){this.httpRegistrar.handle(e,t)}unhandle(e){this.httpRegistrar.unhandle(e)}getProtocolMap(){return this.httpRegistrar.getProtocolMap()}async sendRequest(e,t){if(e instanceof URL)return this.log("making request to %s with global fetch"),globalThis.fetch(e,t);this.log("making request to %s with libp2p fetch",e);let n=t3(e,ti(t)),{addresses:o,httpPath:i}=r3(e),a=await(await this.components.connectionManager.openConnection(o,{signal:t.signal??void 0})).newStream(Rh,{signal:t.signal??void 0});return yR(a,new URL(`http://${n}${decodeURIComponent(i)}`),t)}};function BR(r={}){return e=>new p3(e,r)}function MR(r=0){return new Uint8Array(r)}function UR(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var FR=UR("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),gb=UR("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=MR(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),rY={utf8:FR,"utf-8":FR,hex:oe.base16,latin1:gb,ascii:gb,binary:gb,...oe},m3=rY;function Ms(r,e="utf8"){let t=m3[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function yb(r,e="utf8"){let t=m3[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var $R="0.1.0";var HR="id/push",qR="1.0.0",VR="1.0.0";var Fs;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.protocolVersion!=null&&(s.uint32(42),s.string(i.protocolVersion)),i.agentVersion!=null&&(s.uint32(50),s.string(i.agentVersion)),i.publicKey!=null&&(s.uint32(10),s.bytes(i.publicKey)),i.listenAddrs!=null&&i.listenAddrs.length>0)for(let c of i.listenAddrs)s.uint32(18),s.bytes(c);if(i.observedAddr!=null&&(s.uint32(34),s.bytes(i.observedAddr)),i.protocols!=null&&i.protocols.length>0)for(let c of i.protocols)s.uint32(26),s.string(c);i.signedPeerRecord!=null&&(s.uint32(66),s.bytes(i.signedPeerRecord)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={listenAddrs:[],protocols:[]},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 5:{c.protocolVersion=i.string();break}case 6:{c.agentVersion=i.string();break}case 1:{c.publicKey=i.bytes();break}case 2:{if(a.limits?.listenAddrs!=null&&c.listenAddrs.length===a.limits.listenAddrs)throw new le('Decode error - repeated field "listenAddrs" had too many elements');c.listenAddrs.push(i.bytes());break}case 4:{c.observedAddr=i.bytes();break}case 3:{if(a.limits?.protocols!=null&&c.protocols.length===a.limits.protocols)throw new le('Decode error - repeated field "protocols" had too many elements');c.protocols.push(i.string());break}case 8:{c.signedPeerRecord=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={listenAddrs:0,protocols:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 5:{yield{field:`${a}.protocolVersion`,value:i.string()};break}case 6:{yield{field:`${a}.agentVersion`,value:i.string()};break}case 1:{yield{field:`${a}.publicKey`,value:i.bytes()};break}case 2:{if(c.limits?.listenAddrs!=null&&l.listenAddrs===c.limits.listenAddrs)throw new le('Streaming decode error - repeated field "listenAddrs" had too many elements');yield{field:`${a}.listenAddrs[]`,index:l.listenAddrs,value:i.bytes()},l.listenAddrs++;break}case 4:{yield{field:`${a}.observedAddr`,value:i.bytes()};break}case 3:{if(c.limits?.protocols!=null&&l.protocols===c.limits.protocols)throw new le('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${a}.protocols[]`,index:l.protocols,value:i.string()},l.protocols++;break}case 8:{yield{field:`${a}.signedPeerRecord`,value:i.bytes()};break}default:{i.skipType(d&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Fs||(Fs={}));var zr={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function zR(r){return r.bytes.length===0}function wb(r){if(r!=null&&r.length>0)try{let e=j(r);if(!zR(e))return e}catch{}}async function g3(r,e,t,n,o){if(t("received identify from %p",n.remotePeer),o==null)throw new he("message was null or undefined");let i={},s=o.listenAddrs.map(wb).filter(l=>l!=null);if(o.listenAddrs.length>0&&(i.addresses=s.map(l=>({isCertified:!1,multiaddr:l}))),o.protocols.length>0&&(i.protocols=o.protocols),o.publicKey!=null){let l=Et(o.publicKey);if(!zo(l).equals(n.remotePeer))throw new he("public key did not match remote PeerId");i.publicKey=l}let a;if(o.signedPeerRecord!=null){t.trace("received signedPeerRecord from %p",n.remotePeer);let l=o.signedPeerRecord,u=await gn.openAndCertify(l,Or.DOMAIN),d=Or.createFromProtobuf(u.payload),f=Lr(u.publicKey.toCID());if(!d.peerId.equals(f))throw new he("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(d.peerId))throw new he("signing key does not match remote PeerId");let h;try{h=await r.get(d.peerId)}catch(y){if(y.name!=="NotFoundError")throw y}if(h!=null&&(i.metadata=h.metadata,h.peerRecordEnvelope!=null)){let y=gn.createFromProtobuf(h.peerRecordEnvelope),g=Or.createFromProtobuf(y.payload);g.seqNumber>=d.seqNumber&&(t("sequence number was lower or equal to existing sequence number - stored: %d received: %d",g.seqNumber,d.seqNumber),d=g,l=h.peerRecordEnvelope)}i.peerRecordEnvelope=l;let p=d.multiaddrs.filter(y=>!zR(y));i.addresses=p.map(y=>({isCertified:!0,multiaddr:y})),a={seq:d.seqNumber,addresses:p}}else t("%p did not send a signed peer record",n.remotePeer);if(t.trace("patching %p with",n.remotePeer,i),await r.patch(n.remotePeer,i),o.agentVersion!=null||o.protocolVersion!=null){let l={};o.agentVersion!=null&&(l.AgentVersion=Ms(o.agentVersion)),o.protocolVersion!=null&&(l.ProtocolVersion=Ms(o.protocolVersion)),t.trace("merging %p metadata",n.remotePeer,l),await r.merge(n.remotePeer,{metadata:l})}let c={peerId:n.remotePeer,protocolVersion:o.protocolVersion,agentVersion:o.agentVersion,publicKey:o.publicKey,listenAddrs:s,observedAddr:o.observedAddr==null?void 0:j(o.observedAddr),protocols:o.protocols,signedPeerRecord:a,connection:n};return e.safeDispatchEvent("peer:identify",{detail:c}),c}function y3(r){let e={...r[0]};for(let t of r.slice(1))t.protocolVersion!=null&&(e.protocolVersion=t.protocolVersion),t.agentVersion!=null&&(e.agentVersion=t.agentVersion),t.publicKey!=null&&(e.publicKey=t.publicKey),t.observedAddr!=null&&(e.observedAddr=t.observedAddr),t.signedPeerRecord!=null&&(e.signedPeerRecord=t.signedPeerRecord),e.listenAddrs=[...e.listenAddrs,...t.listenAddrs],e.protocols=[...new Set([...e.protocols,...t.protocols])];return e}async function w3(r,e,t,n){let o=Xe(r,{maxDataLength:e}).pb(Fs),i=[];for(let s=0;s<10;s++)try{i.push(await o.read(t))}catch(a){if(i.length===0)throw a;n.trace("stopped reading identify - %e",a);break}i.length>=10&&n("reached MAX_IDENTIFY_MESSAGES, returning truncated identify");try{await r.close(t)}catch(s){n.trace("error closing identify stream after read - %e",s),r.abort(s)}return i}var vu=class{host;components;protocol;started;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;runOnLimitedConnection;log;constructor(e,t){this.protocol=t.protocol,this.started=!1,this.components=e,this.log=t.log,this.timeout=t.timeout??zr.timeout,this.maxInboundStreams=t.maxInboundStreams??zr.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??zr.maxOutboundStreams,this.maxMessageSize=t.maxMessageSize??zr.maxMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??zr.maxObservedAddresses,this.runOnLimitedConnection=t.runOnLimitedConnection??zr.runOnLimitedConnection,this.host={protocolVersion:`${t.protocolPrefix??zr.protocolPrefix}/${$R}`,agentVersion:e.nodeInfo.userAgent},this.handleProtocol=this.handleProtocol.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.merge(this.components.peerId,{metadata:{AgentVersion:Ms(this.host.agentVersion),ProtocolVersion:Ms(this.host.protocolVersion)}}),await this.components.registrar.handle(this.protocol,this.handleProtocol,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}};var b3=class extends vu{connectionManager;concurrency;_push;constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??zr.protocolPrefix}/${HR}/${VR}`,log:e.logger.forComponent("libp2p:identify-push")}),this.connectionManager=e.connectionManager,this.concurrency=t.concurrency??zr.concurrency,this._push=Ei(this.sendPushMessage.bind(this),t.debounce??1e3),(t.runOnSelfUpdate??zr.runOnSelfUpdate)&&e.events.addEventListener("self:peer:update",n=>{this.push().catch(o=>{this.log.error("error pushing updates to peers - %e",o)})})}[be]=["@libp2p/identify-push"];async push(){this._push()}async sendPushMessage(){if(this.isStarted())try{let e=this.components.addressManager.getAddresses().map(u=>u.decapsulateCode(421)),t=new Or({peerId:this.components.peerId,multiaddrs:e}),n=await gn.seal(t,this.components.privateKey),o=this.components.registrar.getProtocols(),i=await this.components.peerStore.get(this.components.peerId),s=yb(i.metadata.get("AgentVersion")??Ms(this.host.agentVersion)),a=yb(i.metadata.get("ProtocolVersion")??Ms(this.host.protocolVersion)),c=this;async function*l(){for(let u of c.connectionManager.getConnections())(await c.components.peerStore.get(u.remotePeer)).protocols.includes(c.protocol)&&(yield async()=>{let f,h=AbortSignal.timeout(c.timeout);try{f=await u.newStream(c.protocol,{signal:h,runOnLimitedConnection:c.runOnLimitedConnection}),await Xe(f,{maxDataLength:c.maxMessageSize}).pb(Fs).write({listenAddrs:e.map(y=>y.bytes),signedPeerRecord:n.marshal(),protocols:o,agentVersion:s,protocolVersion:a},{signal:h}),await f.close({signal:h})}catch(p){f?.log.newScope("identify-push")?.error("could not push identify update to peer",p),f?.abort(p)}})}await pr(yn(l(),{concurrency:this.concurrency}))}catch(e){this.log.error("error pushing updates to peers - %e",e)}}async handleProtocol(e,t){let n=e.log.newScope("identify-push");if(this.components.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let o={signal:AbortSignal.timeout(this.timeout)},i=await w3(e,this.maxMessageSize,o,n);await g3(this.components.peerStore,this.components.events,n,t,y3(i)),n.trace("handled push from %p",t.remotePeer)}};var x3=class extends vu{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??zr.protocolPrefix}/${"id"}/${qR}`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??zr.runOnConnectionOpen)&&e.events.addEventListener("connection:open",n=>{let o=n.detail;this.identify(o).catch(()=>{})})}[be]=["@libp2p/identify"];async _identify(e,t={}){let n,o;if(t.signal==null){let i=AbortSignal.timeout(this.timeout);t={...t,signal:i}}this.log("run identify on new connection %a",e.remoteAddr);try{n=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),o=n.log.newScope("identify");let i=await w3(n,this.maxMessageSize,t,o);return y3(i)}catch(i){throw o?.error("identify failed - %e",i),n?.abort(i),i}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:o,protocols:i,observedAddr:s}=n;if(o==null)throw new he("Public key was missing from identify message");let a=Et(o),c=Lr(a.toCID());if(!e.remotePeer.equals(c))throw new he("Identified peer does not match the expected peer");if(this.components.peerId.equals(c))throw new he("Identified peer is our own peer id?");return this.maybeAddObservedAddress(s),this.log("completed for peer %p and protocols %o",c,i),g3(this.components.peerStore,this.components.events,this.log,e,n)}maybeAddObservedAddress(e){let t=wb(e);if(t==null||(this.log.trace("our observed address was %a",t),wt(t)))return;let n=t.getComponents();if((n[0].code===41||n[0].code===42&&n[1].code===41)&&!ym(t)){this.log.trace("our observed address was IPv6 but not a global unicast address");return}bi.exactMatch(t)||(this.log.trace("storing the observed address"),this.components.addressManager.addObservedAddr(t))}async handleProtocol(e,t){let n=e.log.newScope("identify");n("responding to identify");let o=AbortSignal.timeout(this.timeout);let i=await this.components.peerStore.get(this.components.peerId,{signal:o}),s=this.components.addressManager.getAddresses().map(u=>u.decapsulateCode(421)),a=i.peerRecordEnvelope;if(s.length>0&&a==null){let u=new Or({peerId:this.components.peerId,multiaddrs:s});a=(await gn.seal(u,this.components.privateKey,{signal:o})).marshal().subarray()}let c=t.remoteAddr.bytes;jS.matches(t.remoteAddr)||(c=void 0);let l=Xe(e).pb(Fs);n("send response"),await l.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Ht(this.components.privateKey.publicKey),listenAddrs:s.map(u=>u.bytes),signedPeerRecord:a,observedAddr:c,protocols:i.protocols},{signal:o}),n("close write"),await l.unwrap().unwrap().close({signal:o})}};function GR(r={}){return e=>new x3(e,r)}function WR(r={}){return e=>new b3(e,r)}var xc=1e3,bb=60*xc,E3=60*bb,jR="/ipfs/kad/1.0.0",v3=48*E3;var YR=24*E3,XR=10,QR=16384,ZR=E3,xb=E3,oke=10*xc,JR=10*xc;var S3=20,Us=10,eP=5*bb,tP=xc,rP=5*xc,nP=5*bb,oP=30*xc,iP=180*xc,Eb=`${ca}-kad-dht`;function vb(r=0){return new Uint8Array(r)}var Ph;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.key!=null&&i.key.byteLength>0&&(s.uint32(10),s.bytes(i.key)),i.value!=null&&i.value.byteLength>0&&(s.uint32(18),s.bytes(i.value)),i.timeReceived!=null&&i.timeReceived!==""&&(s.uint32(42),s.string(i.timeReceived)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={key:vb(0),value:vb(0),timeReceived:""},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.key=i.bytes();break}case 2:{c.value=i.bytes();break}case 5:{c.timeReceived=i.string();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.key`,value:i.bytes()};break}case 2:{yield{field:`${a}.value`,value:i.bytes()};break}case 5:{yield{field:`${a}.timeReceived`,value:i.string()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Ph||(Ph={}));function sP(r){let e=r.getUTCFullYear(),t=String(r.getUTCMonth()+1).padStart(2,"0"),n=String(r.getUTCDate()).padStart(2,"0"),o=String(r.getUTCHours()).padStart(2,"0"),i=String(r.getUTCMinutes()).padStart(2,"0"),s=String(r.getUTCSeconds()).padStart(2,"0"),a=r.getUTCMilliseconds(),c=String(a*1e3*1e3).padStart(9,"0");return`${e}-${t}-${n}T${o}:${i}:${s}.${c}Z`}function aP(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),o=parseInt(t[2],10)-1,i=parseInt(t[3],10),s=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),l=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,o,i,s,a,c,l))}var ft=class r{key;value;timeReceived;constructor(e,t,n){if(!(e instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(t instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=e,this.value=t,this.timeReceived=n}serialize(){return Ph.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:sP(this.timeReceived)}}static deserialize(e){let t=Ph.decode(e);return new r(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){let t=aP(e.timeReceived);if(e.key==null)throw new Error("key missing from deserialized object");if(e.value==null)throw new Error("value missing from deserialized object");return new r(e.key,e.value,t)}};function So(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 $s=class extends Error{constructor(e="Query error"){super(e),this.name="QueryError"}},A3=class extends Error{constructor(e="Invalid record"){super(e),this.name="InvalidRecordError"}},T3=class extends Error{constructor(e="No selector function configured for prefix"){super(e),this.name="MissingSelectorError"}};function Sb(r=0){return new Uint8Array(r)}function Ec(r=0){return new Uint8Array(r)}var cP;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.key!=null&&(s.uint32(10),s.bytes(i.key)),i.value!=null&&(s.uint32(18),s.bytes(i.value)),i.author!=null&&(s.uint32(26),s.bytes(i.author)),i.signature!=null&&(s.uint32(34),s.bytes(i.signature)),i.timeReceived!=null&&(s.uint32(42),s.string(i.timeReceived)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.key=i.bytes();break}case 2:{c.value=i.bytes();break}case 3:{c.author=i.bytes();break}case 4:{c.signature=i.bytes();break}case 5:{c.timeReceived=i.string();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.key`,value:i.bytes()};break}case 2:{yield{field:`${a}.value`,value:i.bytes()};break}case 3:{yield{field:`${a}.author`,value:i.bytes()};break}case 4:{yield{field:`${a}.signature`,value:i.bytes()};break}case 5:{yield{field:`${a}.timeReceived`,value:i.string()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(cP||(cP={}));var De;(function(r){r.PUT_VALUE="PUT_VALUE",r.GET_VALUE="GET_VALUE",r.ADD_PROVIDER="ADD_PROVIDER",r.GET_PROVIDERS="GET_PROVIDERS",r.FIND_NODE="FIND_NODE",r.PING="PING"})(De||(De={}));var _3;(function(r){r[r.PUT_VALUE=0]="PUT_VALUE",r[r.GET_VALUE=1]="GET_VALUE",r[r.ADD_PROVIDER=2]="ADD_PROVIDER",r[r.GET_PROVIDERS=3]="GET_PROVIDERS",r[r.FIND_NODE=4]="FIND_NODE",r[r.PING=5]="PING"})(_3||(_3={}));(function(r){r.codec=()=>Ye(_3)})(De||(De={}));var vc;(function(r){r.NOT_CONNECTED="NOT_CONNECTED",r.CONNECTED="CONNECTED",r.CAN_CONNECT="CAN_CONNECT",r.CANNOT_CONNECT="CANNOT_CONNECT"})(vc||(vc={}));var Ab;(function(r){r[r.NOT_CONNECTED=0]="NOT_CONNECTED",r[r.CONNECTED=1]="CONNECTED",r[r.CAN_CONNECT=2]="CAN_CONNECT",r[r.CANNOT_CONNECT=3]="CANNOT_CONNECT"})(Ab||(Ab={}));(function(r){r.codec=()=>Ye(Ab)})(vc||(vc={}));var Hs;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.id!=null&&i.id.byteLength>0&&(s.uint32(10),s.bytes(i.id)),i.multiaddrs!=null&&i.multiaddrs.length>0)for(let c of i.multiaddrs)s.uint32(18),s.bytes(c);i.connection!=null&&(s.uint32(24),vc.codec().encode(i.connection,s)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={id:Sb(0),multiaddrs:[]},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.id=i.bytes();break}case 2:{if(a.limits?.multiaddrs!=null&&c.multiaddrs.length===a.limits.multiaddrs)throw new le('Decode error - repeated field "multiaddrs" had too many elements');c.multiaddrs.push(i.bytes());break}case 3:{c.connection=vc.codec().decode(i);break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={multiaddrs:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${a}.id`,value:i.bytes()};break}case 2:{if(c.limits?.multiaddrs!=null&&l.multiaddrs===c.limits.multiaddrs)throw new le('Streaming decode error - repeated field "multiaddrs" had too many elements');yield{field:`${a}.multiaddrs[]`,index:l.multiaddrs,value:i.bytes()},l.multiaddrs++;break}case 3:{yield{field:`${a}.connection`,value:vc.codec().decode(i)};break}default:{i.skipType(d&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Hs||(Hs={}));var qs;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.type!=null&&_3[i.type]!==0&&(s.uint32(8),De.codec().encode(i.type,s)),i.clusterLevel!=null&&(s.uint32(80),s.int32(i.clusterLevel)),i.key!=null&&(s.uint32(18),s.bytes(i.key)),i.record!=null&&(s.uint32(26),s.bytes(i.record)),i.closer!=null&&i.closer.length>0)for(let c of i.closer)s.uint32(66),Hs.codec().encode(c,s);if(i.providers!=null&&i.providers.length>0)for(let c of i.providers)s.uint32(74),Hs.codec().encode(c,s);a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={type:De.PUT_VALUE,closer:[],providers:[]},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.type=De.codec().decode(i);break}case 10:{c.clusterLevel=i.int32();break}case 2:{c.key=i.bytes();break}case 3:{c.record=i.bytes();break}case 8:{if(a.limits?.closer!=null&&c.closer.length===a.limits.closer)throw new le('Decode error - repeated field "closer" had too many elements');c.closer.push(Hs.codec().decode(i,i.uint32(),{limits:a.limits?.closer$}));break}case 9:{if(a.limits?.providers!=null&&c.providers.length===a.limits.providers)throw new le('Decode error - repeated field "providers" had too many elements');c.providers.push(Hs.codec().decode(i,i.uint32(),{limits:a.limits?.providers$}));break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={closer:0,providers:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${a}.type`,value:De.codec().decode(i)};break}case 10:{yield{field:`${a}.clusterLevel`,value:i.int32()};break}case 2:{yield{field:`${a}.key`,value:i.bytes()};break}case 3:{yield{field:`${a}.record`,value:i.bytes()};break}case 8:{if(c.limits?.closer!=null&&l.closer===c.limits.closer)throw new le('Streaming decode error - repeated field "closer" had too many elements');for(let f of Hs.codec().stream(i,i.uint32(),`${a}.closer[]`,{limits:c.limits?.closer$}))yield{...f,index:l.closer};l.closer++;break}case 9:{if(c.limits?.providers!=null&&l.providers===c.limits.providers)throw new le('Streaming decode error - repeated field "providers" had too many elements');for(let f of Hs.codec().stream(i,i.uint32(),`${a}.providers[]`,{limits:c.limits?.providers$}))yield{...f,index:l.providers};l.providers++;break}default:{i.skipType(d&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(qs||(qs={}));function Tb(r,e={}){let t={...r,name:"SEND_QUERY",type:0,messageName:r.type,messageType:r.type};return e.onProgress?.(new CustomEvent("kad-dht:query:send-query",{detail:t})),t}function Dh(r,e={}){let t={...r,name:"PEER_RESPONSE",type:1,messageName:r.messageType,closer:r.closer??[],providers:r.providers??[]};return e.onProgress?.(new CustomEvent("kad-dht:query:peer-response",{detail:t})),t}function C3(r,e={}){let t={...r,name:"FINAL_PEER",type:2};return e.onProgress?.(new CustomEvent("kad-dht:query:final-peer",{detail:t})),t}function Ao(r,e={}){let t={...r,name:"QUERY_ERROR",type:3};return e.onProgress?.(new CustomEvent("kad-dht:query:query-error",{detail:t})),t}function _b(r,e={}){let t={...r,name:"PROVIDER",type:4};return e.onProgress?.(new CustomEvent("kad-dht:query:provider",{detail:t})),t}function Lh(r,e={}){let t={...r,name:"VALUE",type:5};return e.onProgress?.(new CustomEvent("kad-dht:query:value",{detail:t})),t}function Cb(r,e={}){let t={...r,name:"DIAL_PEER",type:7};return e.onProgress?.(new CustomEvent("kad-dht:query:dial-peer",{detail:t})),t}function lP(r,e={}){let t={...r,name:"PATH_ENDED",type:8};return e.onProgress?.(new CustomEvent("kad-dht:query:path-ended",{detail:t})),t}function dP(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var uP=dP("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ib=dP("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=Ec(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),cY={utf8:uP,"utf-8":uP,hex:oe.base16,latin1:Ib,ascii:Ib,binary:Ib,...oe},I3=cY;function br(r,e="utf8"){let t=I3[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}async function fP(r,e,t){if(t.length===0)throw new E("No records given");let o=br(e).split("/");if(o.length<3)throw new E("Record key does not have a selector function");let i=r[o[1].toString()];if(i==null)throw new T3(`No selector function configured for key type "${o[1]}"`);return t.length===1?0:i(e,t)}function lY(r,e){return 0}var hP={pk:lY};async function Su(r,e,t){let n=e.key,i=br(n).split("/");if(i.length<3)throw new E("Record key is missing a namespace");let s=r[i[1].toString()];if(s==null)throw new E(`No validator available for key type "${i[1]}"`);await s(n,e.value,t)}var uY=async(r,e,t)=>{if(!(r instanceof Uint8Array))throw new E('"key" must be a Uint8Array');if(r.byteLength<5)throw new E("Invalid public key record");if(br(r.subarray(0,4))!=="/pk/")throw new E("key was not prefixed with /pk/");let o=Et(e),i=r.slice(4);if(!So(i,o.toMultihash().bytes))throw new E("public key does not match passed in key")},pP={pk:uY};function dY(r){return r?.buffer instanceof ArrayBuffer}function k3(r){if(dY(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function kb(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=Ec(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return k3(t)}function R3(r,e="utf8"){let t=I3[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var fY=R3("/pk/");function mP(r){return{...r,multiaddrs:r.multiaddrs.filter(e=>!wt(e))}}async function Vs(r,e){let t=await ct.digest(r);return e?.signal?.throwIfAborted(),t.digest}async function Gr(r,e){return Vs(r.toMultihash().bytes,e)}function Ks(r,e){return new He(`${r}/${br(e,"base32")}`,!1)}function gP(r){return kb([fY,r.toMultihash().bytes])}function yP(r){return br(r.subarray(0,4))==="/pk/"}function wP(r){let e=xe(r.subarray(4));return bt(e)}function Rb(r,e){let t=new Date;return new ft(r,e,t).serialize()}function P3(r){let e=r.toString().split("/"),t=e.pop(),n=e.pop();if(t==null||n==null)throw new Error(`incorrectly formatted provider entry key in datastore: ${r.toString()}`);return{cid:F.createV1(Ie,xe(R3(n,"base32"))),peerId:Ee(t)}}function D3(r,e,t){let n=typeof e=="string"?e:br(e.multihash.bytes,"base32"),o=[r,n];return t!=null&&o.push(t.toString()),new He(o.join("/"))}function L3(r){return new Date(No(r))}function Sc(r,e,t){return async function*(...n){let o=e.queryTime?.timer(t),i=e.errorTime?.timer(t),s=!1;try{e.queries?.increment({[t]:!0}),yield*r(...n)}catch(a){throw s=!0,i?.(),e.errors?.increment({[t]:!0}),a}finally{e.queries?.decrement({[t]:!0}),s||o?.()}}}function N3(r,e,t){return async function(...n){let o=e?.queryTime?.timer(t),i=e?.errorTime?.timer(t),s=!1;try{return e.queries?.increment({[t]:!0}),await r(...n)}catch(a){throw s=!0,i?.(),e.errors?.increment({[t]:!0}),a}finally{e.queries?.decrement({[t]:!0}),s||o?.()}}}var O3=class{log;components;validators;selectors;peerRouting;queryManager;network;datastorePrefix;constructor(e,t){let{validators:n,selectors:o,peerRouting:i,queryManager:s,network:a,logPrefix:c}=t;this.components=e,this.log=e.logger.forComponent(`${c}:content-fetching`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.validators=n,this.selectors=o,this.peerRouting=i,this.queryManager=s,this.network=a,this.get=e.metrics?.traceFunction("libp2p.kadDHT.get",this.get.bind(this),{optionsIndex:1})??this.get,this.put=e.metrics?.traceFunction("libp2p.kadDHT.put",this.put.bind(this),{optionsIndex:2})??this.put}async getLocal(e,t){this.log("getLocal %b",e);let n=Ks(this.datastorePrefix,e);this.log("fetching record for key %k",n);let o=await this.components.datastore.get(n,t);this.log("found %k in local datastore",n);let i=ft.deserialize(o);return await Su(this.validators,i,t),i}async*sendCorrectionRecord(e,t,n,o){this.log("sendCorrection for %b",e);let i=Rb(e,n);for(let{value:s,from:a}of t){if(So(s,n)){this.log("record was ok");continue}if(this.components.peerId.equals(a)){try{let u=Ks(this.datastorePrefix,e);this.log(`Storing corrected record for key ${u.toString()}`),await this.components.datastore.put(u,i.subarray(),o)}catch(u){this.log.error("failed error correcting self - %e",u)}continue}let c=!1,l={type:De.PUT_VALUE,key:e,record:i};for await(let u of this.network.sendRequest(a,l,o))u.name==="PEER_RESPONSE"&&u.record!=null&&So(u.record.value,ft.deserialize(i).value)&&(c=!0),yield u;if(!c)throw new $s("Could not send correction");this.log.error("failed error correcting entry")}}async*put(e,t,n){this.log("put key %b value %b",e,t);let o=Rb(e,t),i=Ks(this.datastorePrefix,e);this.log(`storing record for key ${i.toString()}`),await this.components.datastore.put(i,o.subarray(),n),yield*on(this.peerRouting.getClosestPeers(e,{...n,signal:n.signal}),s=>Ct(s,a=>async()=>{if(a.name!=="FINAL_PEER")return[a];let c=[],l={type:De.PUT_VALUE,key:e,record:o};this.log("send put to %p",a.peer.id);for await(let u of this.network.sendRequest(a.peer.id,l,{...n,path:a.path}))c.push(u),u.name==="PEER_RESPONSE"&&(u.record!=null&&So(u.record.value,ft.deserialize(o).value)||c.push(Ao({from:a.peer.id,error:new $s("Value not put correctly"),path:u.path},n)));return c}),s=>yn(s,{ordered:!1,concurrency:Us}),async function*(s){for await(let a of s)yield*a})}async*get(e,t){this.log("get %b",e);let n=[];for await(let a of this.getMany(e,t)){if(a.name==="VALUE"){n.push(a);continue}yield a}if(n.length===0)return;let o=n.map(a=>a.value),i=0;try{i=await fP(this.selectors,e,o)}catch(a){if(a.name!=="InvalidParametersError")throw a}let s=o[i];if(this.log("GetValue %b %b",e,s),s==null)throw new qe("Best value was not found");yield*this.sendCorrectionRecord(e,n,s,{...t,path:{index:-1,queued:0,running:0,total:0}}),yield n[i]}async*getMany(e,t={}){this.log("getMany values for %b",e);try{let i=await this.getLocal(e,t);yield Lh({value:i.value,from:this.components.peerId,path:{index:-1,running:0,queued:0,total:0}},t)}catch(i){this.log("error getting local value for %b",e,i)}let n=this,o=async function*({peer:i,signal:s,path:a}){for await(let c of n.peerRouting.getValueOrPeers(i.id,e,{...t,signal:s,path:a}))yield c,c.name==="PEER_RESPONSE"&&c.record!=null&&(yield Lh({from:i.id,value:c.record.value,path:a},t))};yield*this.queryManager.run(e,o,t)}};function bP(r,e){return{id:r.id.toMultihash().bytes,multiaddrs:(r.multiaddrs??[]).map(n=>n.bytes),connection:e}}function Nh(r){if(r.id==null)throw new Error("Invalid peer in message");let e=xe(r.id);return{id:bt(e),multiaddrs:(r.multiaddrs??[]).map(t=>j(t))}}var B3=class{log;components;network;peerRouting;queryManager;routingTable;providers;constructor(e,t){let{network:n,peerRouting:o,queryManager:i,routingTable:s,providers:a,logPrefix:c}=t;this.components=e,this.log=e.logger.forComponent(`${c}:content-routing`),this.network=n,this.peerRouting=o,this.queryManager=i,this.routingTable=s,this.providers=a,this.findProviders=e.metrics?.traceFunction("libp2p.kadDHT.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(l,u)=>(l.name==="PROVIDER"&&(u.providers??=[],u.providers.push(...l.providers.map(d=>d.id.toString()))),u)})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.kadDHT.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(l,u)=>(l.name==="PEER_RESPONSE"&&l.messageName==="ADD_PROVIDER"&&(u.providers??=[],u.providers.push(l.from.toString())),u)})??this.provide}async*provide(e,t,n={}){this.log("provide %s",e);let o=e.multihash.bytes;await this.providers.addProvider(e,this.components.peerId,n);let i={type:De.ADD_PROVIDER,key:o,providers:[bP({id:this.components.peerId,multiaddrs:t})]},s=0,a=this;async function*c(d){try{a.log("sending provider record for %s to %p",e,d.peer.id);for await(let f of a.network.sendMessage(d.peer.id,i,{...n,path:d.path}))f.name==="PEER_RESPONSE"&&(a.log("sent provider record for %s to %p",e,d.peer.id),s++),yield f}catch(f){a.log.error("error sending provide record to peer %p - %e",d.peer.id,f),yield Ao({from:d.peer.id,error:f,path:d.path},n)}}let l=Nt({objectMode:!0}),u=new vt({concurrency:Us});u.addEventListener("idle",()=>{l.end()}),u.addEventListener("failure",d=>{this.log.error("error publishing provider record to peer - %e",d.detail.error)}),u.add(async()=>{let d=[];for await(let f of this.peerRouting.getClosestPeers(o,n))l.push(f),f.name==="FINAL_PEER"&&d.push(f);d.forEach(f=>{u.add(async()=>{for await(let h of c(f))l.push(h)}).catch(h=>{this.log.error("error publishing provider record to peer - %e",h)})})}).catch(d=>{l.end(d)}),yield*l,this.log("sent provider records to %d peers",s)}async*findProviders(e,t){let n=this.routingTable.kBucketSize,o=0,i=e.multihash.bytes,s=this;this.log("findProviders %c",e);let a=await this.providers.getProviders(e,t);if(a.length>0){let u=[];for(let d of a.slice(0,n))try{let f=await this.components.peerStore.get(d,t);u.push({id:d,multiaddrs:f.addresses.map(({multiaddr:h})=>h)})}catch(f){if(f.name!=="NotFoundError")throw f;this.log("no peer store entry for %p",d)}if(yield Dh({from:this.components.peerId,messageType:De.GET_PROVIDERS,providers:u,path:{index:-1,queued:0,running:0,total:0}},t),yield _b({from:this.components.peerId,providers:u,path:{index:-1,queued:0,running:0,total:0}},t),o+=u.length,o>=n)return}let c=async function*({peer:u,signal:d,path:f}){let h={type:De.GET_PROVIDERS,key:i};yield*s.network.sendRequest(u.id,h,{...t,signal:d,path:f})},l=new fn(a);for await(let u of this.queryManager.run(i,c,t))if(yield u,u.name==="PEER_RESPONSE"){this.log("Found %d provider entries for %c and %d closer peers",u.providers.length,e,u.closer.length);let d=[];for(let f of u.providers)l.has(f.id)||(l.add(f.id),d.push(f));if(d.length>0&&(yield _b({from:u.from,providers:d,path:u.path},t),o+=d.length,o>=n))return}}};var M3=class extends se{log;protocol;running;components;timeout;metrics;constructor(e,t){super(),this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:network`),this.running=!1,this.protocol=t.protocol,this.timeout=new ho({...t.timeout??{},metrics:e.metrics,metricName:`${t.metricsPrefix}_network_message_send_times_milliseconds`}),this.metrics={operations:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_outbound_rpc_requests_total`),errors:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_outbound_rpc_errors_total`)},this.sendRequest=e.metrics?.traceFunction("libp2p.kadDHT.sendRequest",this.sendRequest.bind(this),{optionsIndex:2,getAttributesFromArgs([n,o],i){return{...i,to:n.toString(),"message type":`${o.type}`}},getAttributesFromYieldedValue:(n,o)=>(n.name==="PEER_RESPONSE"&&(n.providers.length>0&&n.providers.forEach((i,s)=>{o[`providers-${s}`]=i.id.toString()}),n.closer.length>0&&n.closer.forEach((i,s)=>{o[`closer-${s}`]=i.id.toString()})),o)})??this.sendRequest,this.sendMessage=e.metrics?.traceFunction("libp2p.kadDHT.sendMessage",this.sendMessage.bind(this),{optionsIndex:2,getAttributesFromArgs([n,o],i){return{...i,to:n.toString(),"message type":`${o.type}`}},getAttributesFromYieldedValue:(n,o)=>(n.name==="PEER_RESPONSE"&&(n.providers.length>0&&n.providers.forEach((i,s)=>{o[`providers-${s}`]=i.id.toString()}),n.closer.length>0&&n.closer.forEach((i,s)=>{o[`closer-${s}`]=i.id.toString()})),o)})??this.sendMessage}async start(){this.running||(this.running=!0)}async stop(){this.running=!1}isStarted(){return this.running}async*sendRequest(e,t,n){if(!this.running)return;let o=t.type;if(o==null)throw new E("Message type was missing");let i,s=this.timeout.getTimeoutSignal(n);n={...n,signal:s};try{this.metrics.operations?.increment({[o]:!0}),this.log("dialling %p",e),yield Cb({peer:e,path:n.path},n),i=await this.components.connectionManager.openStream(e,this.protocol,n),this.log("sending %s to %p",t.type,e),yield Tb({to:e,type:o,path:n.path},n);let a=await this._writeReadMessage(i,t,n);i.close(n).catch(c=>{this.log.error("error closing stream to %p - %e",e,c),i?.abort(c)}),yield Dh({from:e,messageType:a.type,closer:a.closer.map(Nh),providers:a.providers.map(Nh),record:a.record==null?void 0:ft.deserialize(a.record),path:n.path},n)}catch(a){this.metrics.errors?.increment({[o]:!0}),i?.abort(a),n.signal?.aborted!==!0&&this.log.error("could not send %s to %p - %e",t.type,e,a),yield Ao({from:e,error:a,path:n.path},n)}finally{this.timeout.cleanUp(s)}}async*sendMessage(e,t,n){if(!this.running)return;let o=t.type;if(o==null)throw new E("Message type was missing");let i,s=this.timeout.getTimeoutSignal(n);n={...n,signal:s};try{this.metrics.operations?.increment({[o]:!0}),this.log("dialling %p",e),yield Cb({peer:e,path:n.path},n),i=await this.components.connectionManager.openStream(e,this.protocol,n),this.log("sending %s to %p",t.type,e),yield Tb({to:e,type:o,path:n.path},n),await this._writeMessage(i,t,n),i.close(n).catch(a=>{this.log.error("error closing stream to %p - %e",e,a),i?.abort(a)}),yield Dh({from:e,messageType:o,path:n.path},n)}catch(a){this.metrics.errors?.increment({[o]:!0}),i?.abort(a),yield Ao({from:e,error:a,path:n.path},n)}finally{this.timeout.cleanUp(s)}}async _writeMessage(e,t,n){await Xe(e).write(t,qs,n)}async _writeReadMessage(e,t,n){let o=Xe(e);await o.write(t,qs,n);let i=await o.read(qs,n);return i.closer.forEach(s=>{this.safeDispatchEvent("peer",{detail:Nh(s)})}),i.providers.forEach(s=>{this.safeDispatchEvent("peer",{detail:Nh(s)})}),i}};function To(r,e){if(r.length!==e.length)throw new Error("Inputs should have the same length");let t=Ec(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return k3(t)}function zs(r,e){if(r.byteLength!==e.byteLength)throw new Error("Inputs should have the same length");for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}var Gs=class{originDhtKey;capacity;peerDistances;constructor(e,t){this.originDhtKey=e,this.capacity=t,this.peerDistances=[]}get length(){return this.peerDistances.length}get peers(){return[...this.peerDistances]}async add(e,t={index:-1,queued:0,running:0,total:0},n){let o=await Gr(e.id,n);this.addWithKadId(e,o,t)}addWithKadId(e,t,n={index:-1,queued:0,running:0,total:0}){if(this.peerDistances.find(s=>s.peer.id.equals(e.id))!=null)return;let o={peer:e,distance:To(this.originDhtKey,t),path:n};if(this.peerDistances.length===this.capacity){let s=this.peerDistances[this.peerDistances.length-1];if(s!=null&&zs(o.distance,s.distance)!==-1)return}let i=!1;for(let s=0;s<this.peerDistances.length;s++){let a=zs(this.peerDistances[s].distance,o.distance);if(a===0||a===1){i=!0,this.peerDistances.splice(s,0,o);break}}i||this.peerDistances.push(o),this.peerDistances=this.peerDistances.slice(0,this.capacity)}async isCloser(e,t){if(this.length===0)return!0;let n=await Gr(e,t),o=To(n,this.originDhtKey),i=this.peerDistances[this.peerDistances.length-1].distance;return zs(o,i)===-1}async anyCloser(e,t){return e.length===0?!1:Promise.any(e.map(async n=>this.isCloser(n,t)))}};var F3=class{log;routingTable;network;validators;queryManager;components;constructor(e,t){this.routingTable=t.routingTable,this.network=t.network,this.validators=t.validators,this.queryManager=t.queryManager,this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:peer-routing`),this.findPeer=e.metrics?.traceFunction("libp2p.kadDHT.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.kadDHT.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async findPeerLocal(e,t){let n,o=await this.routingTable.find(e,t);if(o!=null){this.log("findPeerLocal found %p in routing table",e);try{n=await this.components.peerStore.get(o,t)}catch(i){if(i.name!=="NotFoundError")throw i}}if(n==null)try{n=await this.components.peerStore.get(e,t)}catch(i){if(i.name!=="NotFoundError")throw i}if(n!=null)return this.log("findPeerLocal found %p in peer store",e),{id:n.id,multiaddrs:n.addresses.map(i=>i.multiaddr)}}async*_getValueSingle(e,t,n){let o={type:De.GET_VALUE,key:t};yield*this.network.sendRequest(e,o,n)}async*getPublicKeyFromNode(e,t={}){let n=gP(e),o={index:-1,queued:0,running:0,total:0};for await(let i of this._getValueSingle(e,n,{...t,path:o}))if(yield i,i.name==="PEER_RESPONSE"&&i.record!=null){let s=Et(i.record.value),a=zo(s);if(!a.equals(e))throw new ai("public key does not match id");if(a.publicKey==null)throw new ai("public key missing");yield Lh({from:e,value:i.record.value,path:o},t)}throw new $s(`Node not responding with its public key: ${e.toString()}`)}async*findPeer(e,t={}){if(this.log("findPeer %p",e),t.useCache!==!1){let o=await this.findPeerLocal(e,t);if(o!=null){this.log("found local"),yield C3({from:this.components.peerId,peer:o,path:{index:-1,queued:0,running:0,total:0}},t);return}}let n=!1;if(t.useNetwork!==!1){let o=this,i=async function*({peer:s,signal:a,path:c}){let l={type:De.FIND_NODE,key:e.toMultihash().bytes};for await(let u of o.network.sendRequest(s.id,l,{...t,signal:a,path:c}))if(yield u,u.name==="PEER_RESPONSE"){let d=u.closer.find(f=>f.id.equals(e));d!=null&&(yield C3({from:u.from,peer:d,path:u.path},t))}};for await(let s of this.queryManager.run(e.toMultihash().bytes,i,t))s.name==="FINAL_PEER"&&(n=!0),yield s}if(!n)throw new qe("Not found")}async*getClosestPeers(e,t={}){this.log("getClosestPeers to %b",e);let n=await Vs(e,t),o=new Gs(n,this.routingTable.kBucketSize),i=this,s=async function*({peer:a,path:c,peerKadId:l,signal:u}){i.log("getClosestPeers asking %p",a.id);let d={type:De.FIND_NODE,key:e};yield*i.network.sendRequest(a.id,d,{...t,signal:u,path:c}),o.addWithKadId(a,l,c)};yield*this.queryManager.run(e,s,t),this.log("found %d peers close to %b",o.length,e);for(let{peer:a,path:c}of o.peers)yield C3({from:this.components.peerId,peer:a,path:{index:c.index,queued:0,running:0,total:0}},t)}async*getValueOrPeers(e,t,n){for await(let o of this._getValueSingle(e,t,n)){if(o.name==="PEER_RESPONSE"&&o.record!=null)try{await this._verifyRecordOnline(o.record,n)}catch{let s="invalid record received, discarded";this.log(s),yield Ao({from:o.from,error:new $s(s),path:n.path},n);continue}yield o}}async _verifyRecordOnline(e,t){if(e.timeReceived==null)throw new A3("invalid record received");await Su(this.validators,new ft(e.key,e.value,e.timeReceived),t)}async getClosestPeersOffline(e,t){let n=[];try{let s=xe(e),a=bt(s),c=await this.components.peerStore.get(a,t);n.push({id:c.id,multiaddrs:c.addresses.map(({multiaddr:l})=>l)})}catch{}let o=await Vs(e,t),i=this.routingTable.closestPeers(o,t);for(let s of i)try{n.push(await this.components.peerStore.getInfo(s,t))}catch(a){if(a.name!=="NotFoundError")throw a}return n.length>0?this.log("getClosestPeersOffline returning the %d closest peer(s) we know to %b",n.length,e):this.log("getClosestPeersOffline could not any peers close to %b with %d peers in the routing table",e,this.routingTable.size),n}};var U3=class{log;datastore;datastorePrefix;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:providers`),this.datastorePrefix=`${t.datastorePrefix}/provider`,this.datastore=e.datastore}async addProvider(e,t,n){this.log.trace("%p provides %s",t,e),await this.writeProviderEntry(e,t,n)}async removeProvider(e,t,n){let o=D3(this.datastorePrefix,e,t);this.log.trace("%p no longer provides %s",t,e),await this.datastore.delete(o,n)}async getProviders(e,t){this.log.trace("get providers for %c",e);let n=await this.loadProviders(e,t);return this.log.trace("got %d providers for %c",n.size,e),[...n.keys()]}async writeProviderEntry(e,t,n){let o=D3(this.datastorePrefix,e,t),i=ur(n?.time?.getTime()??Date.now());await this.datastore.put(o,i,n)}async loadProviders(e,t){let n=new mr,o=D3(this.datastorePrefix,e);for await(let i of this.datastore.query({prefix:o.toString()},t)){let{peerId:s}=P3(i.key);n.set(s,L3(i.value))}return n}};async function*xP(r){let{key:e,startingPeers:t,ourPeerId:n,query:o,alpha:i,path:s,numPaths:a,log:c,peersSeen:l,connectionManager:u,signal:d}=r,f=Nt({objectMode:!0}),h=new vt({concurrency:i,sort:(y,g)=>zs(y.options.distance,g.options.distance)});h.addEventListener("idle",()=>{f.push(lP({path:{index:s,queued:h.queued,running:h.running,total:h.size}},r)),f.end()}),h.addEventListener("failure",y=>{c.error("error during query - %e",y.detail.error)});let p=()=>{h.abort(),f.end(new Tr)};d.addEventListener("abort",p);try{let g=function(m,b){if(m==null)return;l.add(m.id.toMultihash().bytes);let _=To(b,y);h.add(async()=>{try{for await(let R of o({...r,key:e,peer:m,path:{index:s,queued:h.queued,running:h.running,total:h.size},numPaths:a,peerKadId:b,signal:d})){if(R.name==="PEER_RESPONSE")for(let D of R.closer){if(l.has(D.id.toMultihash().bytes)){c("already seen %p in query",D.id);continue}if(n.equals(D.id)){c("not querying ourselves");continue}if(!await u.isDialable(D.multiaddrs,{signal:d})){c("not querying undialable peer");continue}let O=await Gr(D.id,{signal:d}),U=To(O,y);if(zs(U,_)!==-1){c("skipping %p as they are not closer to %b than %p",D.id,e,m.id);continue}c("querying closer peer %p",D.id),g(D,O)}f.push({...R,path:{index:s,queued:h.queued,running:h.running,total:h.size}})}}catch(R){f.push(Ao({from:m.id,error:R,path:{index:s,queued:h.queued,running:h.running-1,total:h.size-1}},r))}},{distance:_}).catch(R=>{c.error("error during query - %e",R)})},y=await Vs(e,{signal:d});await Promise.all(t.map(async m=>{g({id:m,multiaddrs:[]},await Gr(m,{signal:d}))})),yield*f}finally{d.removeEventListener("abort",p)}}var $3=class{disjointPaths;alpha;shutDownController;running;logger;peerId;connectionManager;routingTable;initialQuerySelfHasRun;logPrefix;allowQueryWithZeroPeers;constructor(e,t){this.logPrefix=t.logPrefix,this.disjointPaths=t.disjointPaths??S3,this.alpha=t.alpha??Us,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun,this.routingTable=t.routingTable,this.logger=e.logger,this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.allowQueryWithZeroPeers=t.allowQueryWithZeroPeers??!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.running=!1}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.shutDownController=new AbortController,this.shutDownController.signal,void 0)}async stop(){this.running=!1,this.shutDownController.abort()}async*run(e,t,n={}){if(!this.running)throw new Error("QueryManager not started");if(n.signal==null){let c=AbortSignal.timeout(iP);n={...n,signal:c}}let o=new AbortController,i=ae([this.shutDownController.signal,o.signal,n.signal]);o.signal;let s=this.logger.forComponent(`${this.logPrefix}:query:`+br(e,"base58btc")),a=!1;try{this.routingTable.size===0&&!this.allowQueryWithZeroPeers&&(s("routing table was empty, waiting for some peers before running%s query",n.isSelfQuery===!0?" self":""),await ke(this.routingTable,"peer:add",{signal:i,filter:h=>!this.peerId.equals(h.detail)}),s("routing table has peers, continuing with%s query",n.isSelfQuery===!0?" self":"")),n.isSelfQuery!==!0&&this.initialQuerySelfHasRun!=null&&(s("waiting for initial self query before continuing"),await Me(this.initialQuerySelfHasRun.promise,i),this.initialQuerySelfHasRun=void 0),s("query:start");let c=await Vs(e,{signal:i}),l=this.routingTable.closestPeers(c,{count:this.routingTable.kBucketSize}),u=l.sort(()=>Math.random()>.5?1:-1).reduce((h,p,y)=>(h[y%this.disjointPaths].push(p),h),new Array(this.disjointPaths).fill(0).map(()=>[])).filter(h=>h.length>0);if(l.length===0){s.error("running query with no peers");return}let d=Lt(1024),f=u.map((h,p)=>xP({...n,key:e,startingPeers:h,ourPeerId:this.peerId,signal:i,query:t,path:p,numPaths:u.length,alpha:this.alpha,log:s,peersSeen:d,onProgress:n.onProgress,connectionManager:this.connectionManager}));for await(let h of Rr(...f))h.name==="QUERY_ERROR"&&s.error("query error - %e",h.error),h.name==="PEER_RESPONSE"&&this.routingTable.queueRoutingTableUpdate(h.from),i.throwIfAborted(),yield h;a=!0}catch(c){if(this.running)throw c}finally{a||(s("query exited early"),o.abort()),i.clear(),s("query finished")}}};function pY(r){return r[Symbol.asyncIterator]!=null}function mY(r){if(pY(r))return(async()=>{let e=0;for await(let t of r)e++;return e})();{let e=0;for(let t of r)e++;return e}}var H3=mY;var q3=class{log;peerId;peerRouting;events;count;interval;initialInterval;queryTimeout;running;timeoutId;controller;initialQuerySelfHasRun;querySelfPromise;constructor(e,t){this.peerId=e.peerId,this.log=e.logger.forComponent(`${t.logPrefix}:query-self`),this.events=e.events,this.running=!1,this.peerRouting=t.peerRouting,this.count=t.count??S3,this.interval=t.interval??eP,this.initialInterval=t.initialInterval??tP,this.queryTimeout=t.queryTimeout??rP,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun,this.querySelf=N3(this.querySelf.bind(this),t.operationMetrics,"SELF_QUERY")}isStarted(){return this.running}start(){this.running||(this.running=!0,clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.querySelf().catch(e=>{this.log.error("error running self-query - %e",e)})},this.initialInterval))}stop(){this.running=!1,this.timeoutId!=null&&clearTimeout(this.timeoutId),this.controller!=null&&this.controller.abort()}async querySelf(){if(!this.running){this.log("skip self-query because we are not started");return}if(this.querySelfPromise!=null)return this.log("joining existing self query"),this.querySelfPromise.promise;if(this.querySelfPromise=me(),this.running){this.controller=new AbortController;let e=[this.controller.signal];if(this.initialQuerySelfHasRun==null){let n=AbortSignal.timeout(this.queryTimeout);e.push(n)}let t=ae(e);this.controller.signal;try{this.log("run self-query, look for %d peers timing out after %dms",this.count,this.queryTimeout);let n=Date.now(),o=await on(this.peerRouting.getClosestPeers(this.peerId.toMultihash().bytes,{signal:t,isSelfQuery:!0}),s=>vs(s,this.count),async s=>H3(s));t?.throwIfAborted();let i=Date.now()-n;this.log("self-query found %d peers in %dms",o,i),this.events.dispatchEvent(new CustomEvent("kad-dht:query:self",{detail:{peers:o,duration:i}}))}catch(n){this.log.error("self-query error - %e",n)}finally{t.clear(),this.initialQuerySelfHasRun!=null&&(this.initialQuerySelfHasRun.resolve(),this.initialQuerySelfHasRun=void 0)}}this.querySelfPromise.resolve(),this.querySelfPromise=void 0,this.running&&(this.timeoutId=setTimeout(()=>{this.querySelf().catch(e=>{this.log.error("error running self-query - %e",e)})},this.interval))}};var V3=class extends se{log;reprovideQueue;maxQueueSize;datastore;timeout;reprovideTimeout;running;shutdownController;reprovideThreshold;contentRouting;datastorePrefix;addressManager;validity;interval;peerId;constructor(e,t){super(),this.log=e.logger.forComponent(`${t.logPrefix}:reprovider`),this.peerId=e.peerId,this.reprovideQueue=new vt({concurrency:t.concurrency??XR,metrics:e.metrics,metricName:`${t.metricsPrefix}_reprovide_queue`}),this.reprovideTimeout=new ho({...t.timeout??{},metrics:e.metrics,metricName:`${t.metricsPrefix}_reprovide_timeout_milliseconds`}),this.datastore=e.datastore,this.addressManager=e.addressManager,this.datastorePrefix=`${t.datastorePrefix}/provider`,this.reprovideThreshold=t.threshold??YR,this.maxQueueSize=t.maxQueueSize??QR,this.validity=t.validity??v3,this.interval=t.interval??ZR,this.contentRouting=t.contentRouting,this.running=!1,this.reprovide=N3(this.reprovide.bind(this),t.operationMetrics,"PROVIDE")}start(){this.running||(this.running=!0,this.shutdownController=new AbortController,this.shutdownController.signal,this.timeout=setTimeout(()=>{this.processRecords({signal:AbortSignal.timeout(xb)}).catch(e=>{this.log.error("error running process to reprovide/cleanup - %e",e)})},this.interval))}stop(){this.running=!1,this.reprovideQueue.clear(),clearTimeout(this.timeout),this.shutdownController?.abort()}async processRecords(e){try{this.safeDispatchEvent("reprovide:start"),this.log("starting reprovide/cleanup");for await(let t of this.datastore.query({prefix:this.datastorePrefix},e))try{let{cid:n,peerId:o}=P3(t.key),s=L3(t.value).getTime()+this.validity,a=Date.now(),c=a>s,l=this.peerId.equals(o);this.log.trace("comparing: %d (now) < %d (expires) = %s %s",a,s,c,c?"(expired)":"(valid)"),c&&!l&&await this.datastore.delete(t.key,e),this.shouldReprovide(l,s)&&(this.log("reproviding %c as it is within the reprovide threshold (%d)",n,this.reprovideThreshold),this.queueReprovide(n).catch(u=>{this.log.error("could not reprovide %c - %e",n,u)}))}catch(n){this.log.error("error processing datastore key %s - %s",t.key,n.message)}this.log("reprovide/cleanup successful")}finally{this.safeDispatchEvent("reprovide:end"),this.running&&(this.log("queuing next re-provide/cleanup run in %d ms",this.interval),this.timeout=setTimeout(()=>{this.processRecords({signal:AbortSignal.timeout(xb)}).catch(t=>{this.log.error("error running re-provide - %e",t)})},this.interval))}}shouldReprovide(e,t){if(!e)return!1;let n=Date.now();return t<n?!0:t-n<this.reprovideThreshold}async queueReprovide(e,t){if(!this.running)return;this.log.trace("waiting for queue capacity before adding %c to re-provide queue",e),await this.reprovideQueue.onSizeLessThan(this.maxQueueSize,t);let n=this.reprovideQueue.queue.find(o=>o.options.cid.equals(e));if(n!=null)return this.log.trace("not adding %c to re-provide queue - already in queue",e),n.join();this.log.trace("adding %c to re-provide queue",e),this.reprovideQueue.add(async o=>{if(o.signal?.throwIfAborted(),!this.running)return;this.log.trace("re-providing %c",e);let i=this.reprovideTimeout.getTimeoutSignal(o);try{await this.reprovide(o.cid,o)}finally{this.reprovideTimeout.cleanUp(i)}this.log.trace("re-provided %c",e)},{signal:this.shutdownController?.signal,cid:e}).catch(o=>{this.log.error("could not re-provide key %c - %e",e,o)})}async reprovide(e,t){await pr(this.contentRouting.provide(e,this.addressManager.getAddresses(),t))}};var gY=20,yY=5e3,wY="kad-close",bY=50,K3=class{routingTable;components;closestPeers;newPeers;refreshInterval;peerSetSize;timeout;closeTagName;closeTagValue;log;running;constructor(e,t){this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:routing-table`),this.routingTable=t.routingTable,this.refreshInterval=t.refreshInterval??yY,this.peerSetSize=t.peerSetSize??gY,this.closeTagName=t.closeTagName??wY,this.closeTagValue=t.closeTagValue??bY,this.closestPeers=new fn,this.onPeerPing=this.onPeerPing.bind(this),this.running=!1}async start(){if(this.running)return;this.running=!0;let e=await Gr(this.components.peerId);this.newPeers=new Gs(e,this.peerSetSize),this.routingTable.addEventListener("peer:ping",this.onPeerPing),this.timeout=setInterval(()=>{this.updatePeerTags().catch(t=>{this.log.error("error updating peer tags - %e",t)})},this.refreshInterval)}stop(){this.running=!1,this.routingTable.removeEventListener("peer:ping",this.onPeerPing),clearTimeout(this.timeout)}onPeerPing(e){this.newPeers?.add({id:e.detail,multiaddrs:[]}).catch(t=>{this.log.error("error adding peer to distance list - %e",t)})}async updatePeerTags(){let e=new fn(this.newPeers?.peers.map(({peer:o})=>o.id)),t=e.difference(this.closestPeers),n=this.closestPeers.difference(e);this.closestPeers=e,await Promise.all([...[...t].map(async o=>{await this.components.peerStore.merge(o,{tags:{[this.closeTagName]:{value:this.closeTagValue},[Eb]:{value:1}}})}),...[...n].map(async o=>{await this.components.peerStore.merge(o,{tags:{[this.closeTagName]:void 0,[Eb]:void 0}})})])}};function Oh(r){return Array.isArray(r?.peers)}var z3=class{peerId;root;localPeer;prefixLength;splitThreshold;kBucketSize;numberOfNodesToPing;lastPingThreshold;ping;verify;onAdd;onRemove;onMove;addingPeerMap;constructor(e,t){this.peerId=e.peerId,this.prefixLength=t.prefixLength??EP,this.kBucketSize=t.kBucketSize??Bh,this.splitThreshold=t.splitThreshold??this.kBucketSize,this.numberOfNodesToPing=t.numberOfOldContactsToPing??vP,this.lastPingThreshold=t.lastPingThreshold??SP,this.ping=t.ping,this.verify=t.verify,this.onAdd=t.onAdd,this.onRemove=t.onRemove,this.addingPeerMap=Ai({name:`${t.metricsPrefix}_adding_peer_map`,metrics:e.metrics}),this.root={prefix:"",depth:0,peers:[]}}async start(){await this.addSelfPeer(this.peerId)}stop(){this.addingPeerMap.clear(),this.root={prefix:"",depth:0,peers:[]}}async addSelfPeer(e,t){this.localPeer={peerId:e,kadId:await Gr(e,t),lastPing:Date.now()}}async add(e,t){let n={peerId:e,kadId:await Gr(e,t),lastPing:0},o=this.addingPeerMap.get(e);if(o!=null)return o;try{let i=this._add(n,t);this.addingPeerMap.set(e,i),await i}finally{this.addingPeerMap.delete(e)}}async _add(e,t){let n=this._determineBucket(e.kadId);if(this._indexOf(n,e.kadId)>-1)return;if(n.peers.length===this.splitThreshold&&n.depth<this.prefixLength){await this._split(n,t),await this._add(e,t);return}if(n.peers.length<this.kBucketSize){if(!EY(e,this.lastPingThreshold)){n.peers.push(e),await this.onAdd?.(e,n,t);return}await this.verify(e,t)&&(e.lastPing=Date.now(),await this._add(e,t));return}let o=n.peers.filter(s=>!(s.peerId.equals(this.localPeer?.peerId)||s.lastPing>Date.now()-this.lastPingThreshold)).sort((s,a)=>s.lastPing<a.lastPing?-1:s.lastPing>a.lastPing?1:0).slice(0,this.numberOfNodesToPing),i=!1;for await(let s of this.ping(o,t))i=!0,await this.remove(s.kadId,t);i&&await this._add(e,t)}*closest(e,t){let n=new Gs(e,t?.count??this.kBucketSize);for(let o of this.toIterable())t?.exclude?.some(i=>i.equals(o.peerId))!==!0&&n.addWithKadId({id:o.peerId,multiaddrs:[]},o.kadId);yield*Ct(n.peers,({peer:o})=>o.id)}count(){function e(t){if(Oh(t))return t.peers.length;let n=0;return t.left!=null&&(n+=e(t.left)),t.right!=null&&(n+=e(t.right)),n}return e(this.root)}get(e){let t=this._determineBucket(e),n=this._indexOf(t,e);return t.peers[n]}async remove(e,t){let n=this._determineBucket(e),o=this._indexOf(n,e);if(o>-1){let i=n.peers.splice(o,1)[0];await this.onRemove?.(i,n,t)}}*toIterable(){function*e(t){if(Oh(t)){yield*t.peers;return}yield*e(t.left),yield*e(t.right)}yield*e(this.root)}distance(e,t){return BigInt("0x"+br(To(e,t),"base16"))}_determineBucket(e){let t=br(e,"base2");function n(o,i=0){return Oh(o)?o:t[i]==="0"?n(o.left,i+1):n(o.right,i+1)}return n(this.root)}_indexOf(e,t){return e.peers.findIndex(n=>So(n.kadId,t))}async _split(e,t){let n={prefix:"0",depth:e.depth+1,peers:[]},o={prefix:"1",depth:e.depth+1,peers:[]};for(let i of e.peers)br(i.kadId,"base2")[e.depth]==="0"?(n.peers.push(i),await this.onMove?.(i,e,n,t)):(o.peers.push(i),await this.onMove?.(i,e,o,t));xY(e,n,o)}};function xY(r,e,t){return delete r.peers,r.left=e,r.right=t,r.prefix===""&&(delete r.depth,delete r.prefix),!0}function EY(r,e){return r.lastPing<Date.now()-e}var Bh=20,EP=6;var vY=20,SY=100,AY=16,TY=16384,vP=3;var _Y=20,CY=100,AP="kad-peer",IY=1,SP=6e5,kY=!0,RY=1e3,G3=class extends se{kBucketSize;kb;network;closestPeerTagger;log;components;running;pingNewContactTimeout;pingNewContactQueue;pingOldContactTimeout;pingOldContactQueue;routingTableUpdateQueue;populateFromDatastoreOnStart;populateFromDatastoreLimit;protocol;peerTagName;peerTagValue;metrics;shutdownController;constructor(e,t){super(),this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:routing-table`),this.kBucketSize=t.kBucketSize??Bh,this.running=!1,this.protocol=t.protocol,this.network=t.network,this.peerTagName=t.peerTagName??AP,this.peerTagValue=t.peerTagValue??IY,this.pingOldContacts=this.pingOldContacts.bind(this),this.verifyNewContact=this.verifyNewContact.bind(this),this.peerAdded=this.peerAdded.bind(this),this.peerRemoved=this.peerRemoved.bind(this),this.populateFromDatastoreOnStart=t.populateFromDatastoreOnStart??kY,this.populateFromDatastoreLimit=t.populateFromDatastoreLimit??RY,this.shutdownController=new AbortController,this.shutdownController.signal,this.routingTableUpdateQueue=new Gt({concurrency:t.routingTableUpdateQueueConcurrency??AY,metricName:`${t.metricsPrefix}_routing_table_update_queue`,metrics:this.components.metrics,maxSize:t.routingTableUpdateMaxQueueSize??TY}),this.pingOldContactQueue=new Gt({concurrency:t.pingOldContactConcurrency??_Y,metricName:`${t.metricsPrefix}_ping_old_contact_queue`,metrics:this.components.metrics,maxSize:t.pingOldContactMaxQueueSize??CY}),this.pingOldContactTimeout=new ho({...t.pingOldContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_old_contact_time_milliseconds`}),this.pingNewContactQueue=new Gt({concurrency:t.pingNewContactConcurrency??vY,metricName:`${t.metricsPrefix}_ping_new_contact_queue`,metrics:this.components.metrics,maxSize:t.pingNewContactMaxQueueSize??SY}),this.pingNewContactTimeout=new ho({...t.pingNewContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_new_contact_time_milliseconds`}),this.kb=new z3(e,{kBucketSize:t.kBucketSize,prefixLength:t.prefixLength,splitThreshold:t.splitThreshold,numberOfOldContactsToPing:t.numberOfOldContactsToPing,lastPingThreshold:t.lastPingThreshold,ping:this.pingOldContacts,verify:this.verifyNewContact,onAdd:this.peerAdded,onRemove:this.peerRemoved,metricsPrefix:t.metricsPrefix}),this.closestPeerTagger=new K3(this.components,{logPrefix:t.logPrefix,routingTable:this,peerSetSize:t.closestPeerSetSize,refreshInterval:t.closestPeerSetRefreshInterval,closeTagName:t.closeTagName,closeTagValue:t.closeTagValue}),this.components.metrics!=null&&(this.metrics={routingTableSize:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_size`),routingTableKadBucketTotal:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_total`),routingTableKadBucketAverageOccupancy:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_average_occupancy`),routingTableKadBucketMinOccupancy:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_min_occupancy`),routingTableKadBucketMaxOccupancy:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_max_occupancy`),routingTableKadBucketMaxDepth:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_max_depth`),kadBucketEvents:this.components.metrics.registerCounterGroup(`${t.metricsPrefix}_kad_bucket_events_total`)})}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.shutdownController=new AbortController,this.shutdownController.signal,await Rt(this.closestPeerTagger,this.kb))}async afterStart(){let e=0;Promise.resolve().then(async()=>{if(!this.populateFromDatastoreOnStart)return;let t=ae([this.shutdownController.signal,AbortSignal.timeout(2e4)]);try{for(let n of await this.components.peerStore.all({filters:[o=>o.protocols.includes(this.protocol)&&o.tags.has(AP)],limit:this.populateFromDatastoreLimit,signal:t})){if(!this.running)return;try{await this.add(n.id,{signal:t}),e++}catch{this.log("failed to add peer %p to routing table, removing kad-dht peer tags - %e"),await this.components.peerStore.merge(n.id,{tags:{[this.peerTagName]:void 0}})}}}finally{t.clear()}this.log("added %d peer store peers to the routing table",e)}).catch(t=>{this.log.error("error adding %d, peer store peers to the routing table - %e",e,t)})}async stop(){this.running=!1,await Ut(this.closestPeerTagger,this.kb),this.routingTableUpdateQueue.abort(),this.pingOldContactQueue.abort(),this.pingNewContactQueue.abort(),this.shutdownController.abort()}queueRoutingTableUpdate(e,t={}){let n=this.routingTableUpdateQueue.find(e);if(n!=null){n.join(t).catch(()=>{});return}this.routingTableUpdateQueue.add(async o=>{let i=o,s;t.activeTimeout!=null&&(s=ae([o.signal,AbortSignal.timeout(t.activeTimeout)]),i={...o,signal:s});try{await this.add(e,i)}finally{s?.clear()}},{peerId:e,signal:this.shutdownController.signal}).catch(o=>{this.shutdownController.signal.aborted||o?.name==="AbortError"||this.log.error("could not update routing table for peer %p - %e",e,o)})}async peerAdded(e,t,n){this.components.peerId.equals(e.peerId)||await this.components.peerStore.merge(e.peerId,{tags:{[this.peerTagName]:{value:this.peerTagValue}}},n),this.updateMetrics(),this.metrics?.kadBucketEvents.increment({peer_added:!0}),this.safeDispatchEvent("peer:add",{detail:e.peerId})}async peerRemoved(e,t,n){this.components.peerId.equals(e.peerId)||await this.components.peerStore.merge(e.peerId,{tags:{[this.peerTagName]:void 0}},n),this.updateMetrics(),this.metrics?.kadBucketEvents.increment({peer_removed:!0}),this.safeDispatchEvent("peer:remove",{detail:e.peerId})}async*pingOldContacts(e,t){if(!this.running)return;let n=[];for(let o of e){if(this.kb.get(o.kadId)==null){this.log("asked to ping contact %p that was not in routing table",o.peerId);continue}this.metrics?.kadBucketEvents.increment({ping_old_contact:!0}),n.push(async()=>{let i=this.pingOldContactQueue.find(o.peerId);if(i!=null)return this.log("asked to ping contact %p was already being pinged",o.peerId),await i.join(t)?void 0:o;if(!await this.pingOldContactQueue.add(async a=>{let c=this.pingOldContactTimeout.getTimeoutSignal(),l=ae([c,this.shutdownController.signal,a?.signal]);try{return await this.pingContact(o,a)}catch{return this.metrics?.kadBucketEvents.increment({ping_old_contact_error:!0}),!0}finally{this.pingOldContactTimeout.cleanUp(c),l.clear()}},{peerId:o.peerId,signal:t?.signal}))return o})}for await(let o of yn(n))o!=null&&(yield o)}async verifyNewContact(e,t){let n=this.pingNewContactTimeout.getTimeoutSignal(),o=ae([n,this.shutdownController.signal,t?.signal]);try{let i=this.pingNewContactQueue.find(e.peerId);return i!=null?(this.log("joining existing ping to add new peer %p to routing table",e.peerId),await i.join({signal:o})):await this.pingNewContactQueue.add(async s=>(this.metrics?.kadBucketEvents.increment({ping_new_contact:!0}),this.log("pinging new peer %p before adding to routing table",e.peerId),this.pingContact(e,s)),{peerId:e.peerId,signal:o})}catch{return this.log.trace("tried to add peer %p but they were not online",e.peerId),this.metrics?.kadBucketEvents.increment({ping_new_contact_error:!0}),!1}finally{this.pingNewContactTimeout.cleanUp(n),o.clear()}}async pingContact(e,t){let n;try{return this.log("pinging contact %p",e.peerId),await this.components.ping.ping(e.peerId,t),this.log("contact %p ping ok",e.peerId),this.safeDispatchEvent("peer:ping",{detail:e.peerId}),!0}catch(o){return this.log("error pinging old contact %p - %e",e.peerId,o),n?.abort(o),!1}}get size(){return this.kb==null?0:this.kb.count()}async find(e,t){let n=await Gr(e,t);return this.kb.get(n)?.peerId}closestPeer(e){let t=this.closestPeers(e,{count:1});if(t.length>0)return t[0]}closestPeers(e,t){return this.kb==null?[]:[...this.kb.closest(e,t)]}async add(e,t){if(this.kb==null)throw new Error("RoutingTable is not started");await this.kb.add(e,t)}async remove(e,t){if(this.kb==null)throw new Error("RoutingTable is not started");let n=await Gr(e,t);await this.kb.remove(n,t)}updateMetrics(){if(this.metrics==null||this.kb==null)return;let e=0,t=0,n=0,o=20,i=0;function s(a){if(Oh(a)){a.depth>n&&(n=a.depth),t++,e+=a.peers.length,a.peers.length<o&&(o=a.peers.length),a.peers.length>i&&(i=a.peers.length);return}s(a.left),s(a.right)}s(this.kb.root),this.metrics.routingTableSize.update(e),this.metrics.routingTableKadBucketTotal.update(t),this.metrics.routingTableKadBucketAverageOccupancy.update(Math.round(e/t)),this.metrics.routingTableKadBucketMinOccupancy.update(o),this.metrics.routingTableKadBucketMaxOccupancy.update(i),this.metrics.routingTableKadBucketMaxDepth.update(n)}};var TP=[77591,22417,43971,28421,740,29829,71467,228973,196661,78537,27689,36431,44415,14362,19456,106025,96308,2882,49509,21149,87173,131409,75844,23676,121838,30291,17492,2953,7564,110620,129477,127283,53113,72417,165166,109690,21200,102125,24049,71504,90342,25307,72039,26812,26715,32264,133800,71161,88956,171987,51779,24425,16671,30251,186294,247761,14202,2121,8465,35024,4876,85917,169730,3638,256836,96184,943,18678,6583,52907,35807,112254,214097,18796,11595,9243,23554,887,268203,382004,24590,111335,11625,16619,29039,102425,69006,97976,92362,32552,63717,41433,128974,137630,59943,10019,13986,35430,33665,108037,43799,43280,38195,29078,58629,18265,14425,46832,235538,40830,77881,110717,58937,3463,325358,51300,47623,117252,19007,10170,20540,91237,294813,4951,79841,56232,36270,128547,69209,66275,100156,32063,73531,34439,80937,28892,44466,88595,216307,32583,49620,16605,82127,45807,21630,78726,20235,40163,111007,96926,5567,72083,21665,58844,39419,179767,48328,42662,51550,5251,37811,49608,81056,50854,55513,20922,18891,197409,164656,32593,71449,220474,58919,85682,67854,13758,35066,3565,61905,214793,119572,141419,21504,10302,27354,67003,46131,32668,15165,64871,34450,17821,2757,11452,34189,5160,12257,85523,560,53385,65887,119549,135620,312353,115979,122356,10867,193231,124537,54783,90675,120791,4715,142253,50943,17271,43358,25331,4917,120566,34580,12878,33786,160528,32523,4869,301307,104817,81491,23276,8832,97911,31265,52065,7998,49622,9715,43998,34091,84587,20664,69041,29419,53205,10838,58288,116145,6185,5154,141795,35924,21307,144738,43730,12085,8279,10002,119,133779,199668,72938,31768,39176,67875,38453,9700,44144,4121,116048,41733,12868,82669,92308,128,34262,11332,7712,90764,36141,13553,71312,77470,117314,96549,49135,23602,54468,28605,6327,62308,17171,67531,21319,14105,894,107722,46157,8503,51069,100472,45138,15246,14577,35609,191464,1757,13364,161349,32067,91705,81144,52339,5408,91066,21983,14157,100545,4372,26630,129112,1423,29676,213626,4397,88436,99190,6877,49958,26122,114348,60661,29818,293118,50042,179738,16400,163423,89627,31040,43973,36638,45952,5153,1894,109322,1898,134021,12402,112077,68309,190269,69866,31938,107383,11522,105232,11248,14868,39852,71707,186525,16530,38162,106212,11700,5130,16608,26998,59586,108399,230033,43683,48135,82179,2073,5015,196684,189293,16378,23452,8301,35640,11632,214551,29240,57644,33137,91949,55157,52384,117313,5090,17717,89668,49363,82238,241035,66216,29066,184088,97206,62820,26595,4241,135635,173672,8202,459,71355,146294,29587,3008,135385,141203,14803,6634,45094,69362,50925,546,51884,62011,83296,234584,44515,56050,89476,87751,19373,12691,149923,19794,13833,35846,87557,58339,2884,19145,25647,12224,11024,77338,64608,122297,53025,7205,36189,36294,170779,21750,7739,173883,75192,35664,224240,113121,30181,26267,27036,117827,92015,106516,55628,203549,67949,60462,60844,35911,20457,1820,920,19773,8738,73173,181993,38521,98254,76257,46008,92796,5384,26868,151566,22124,2411,15919,186872,180021,28099,152961,78811,80237,62352,102653,74259,184890,16792,123702,224945,29940,19512,75283,14059,112691,92811,233329,20411,138569,53341,109802,50600,134528,66747,5529,166531,31578,64732,67189,1596,126357,967,167999,206598,109752,119431,207825,78791,91938,10301,27311,24233,252343,28831,32812,66002,112267,90895,8786,8095,16824,22866,21813,60507,174833,19549,130985,117051,52110,6938,81923,123864,38061,919,18680,53534,46739,112893,161529,85429,26761,11900,81121,91968,15390,217947,56524,1713,6654,37089,85630,138866,61850,16491,75577,16884,98296,73523,6140,44645,6062,36366,29844,57946,37932,42472,5266,20834,19309,33753,127182,134259,35810,41805,45878,312001,14881,47757,49251,120050,44252,3708,25856,107864,120347,1228,36550,41682,34496,47025,8393,173365,246526,12894,161607,35670,90785,126572,2095,124731,157033,58694,554,12786,9642,4817,16136,47864,174698,66992,4639,69284,10625,40710,27763,51738,30404,264105,137904,109882,52487,42824,57514,2740,10479,146799,107390,16586,88038,174951,9410,16185,44158,5568,40658,46108,12763,97385,26175,108859,664,230732,67470,46663,14395,50750,141320,93140,15361,47997,55784,6791,307840,118569,107326,18056,58281,260415,54691,8790,73332,45633,7511,45674,143373,14031,11799,94491,35646,96544,14560,26049,32983,25791,83814,42094,231370,63955,139212,2359,169908,3108,183486,105867,28197,32941,124968,26402,88267,149768,23053,3078,19091,52924,25383,19209,111548,97361,3959,24880,235061,9099,24921,161254,151405,20508,7159,34381,20133,11434,74036,19974,34769,36585,1076,22454,17354,38727,235160,111547,96454,117448,156940,91330,37299,7310,26915,117060,51369,22620,61861,322264,106850,111694,15091,2624,40345,300446,177064,1707,27389,54792,327783,132669,183543,59003,17744,20603,151134,106923,53084,71803,279424,319816,11579,21946,16728,38274,72711,5085,83391,88646,40159,25027,34680,10752,12988,54126,30365,18338,100445,230674,44874,84974,143877,123253,139372,28082,91477,144002,13096,219729,46016,50029,42377,14601,6660,58244,58978,23918,88206,113611,64452,17541,41032,10942,12021,49189,10978,40175,37156,10947,71709,106894,112538,57007,137486,150608,152719,40615,7746,279716,13101,19524,28708,40578,72320,1096,182051,94527,51275,22833,45164,81917,77519,48508,5421,140302,37845,149830,5587,27579,5357,428725,248187,6326,206760,39814,32585,89923,44341,288753,284443,96368,31201,94189,119504,20359,52073,103216,179,27934,32801,96035,34111,34309,101326,18198,20704,210266,37643,27880,141873,106e3,19414,56614,167714,66483,107885,86602,4379,20796,75467,4987,5017,118857,26003,34308,114428,29198,6686,29697,73632,3739,69795,16798,41504,7207,30722,21436,36735,28067,28545,3239,11221,36031,41889,100010,19247,317673,29495,174554,6424,129725,53845,94986,7955,59676,2604,191497,19735,102214,62954,23844,11872,179525,261436,34492,428,78404,142035,16747,17246,27578,37021,33672,57944,26056,135760,2369,61674,122066,31327,19374,157065,40553,130982,69619,71290,38855,72100,92903,95940,51422,165999,65713,57873,50726,7288,20272,2081,42326,22624,81120,57914,79352,19447,1684,72302,11774,302559,161481,96396,13692,414988,3721,79066,56627,46883,21150,11747,12184,5856,113458,176117,84416,52079,27933,3354,59765,141359,2212,216309,2555,23458,196722,142463,45701,44548,28798,19418,215,29916,9396,10574,114226,84475,13520,18694,34056,4524,90302,62930,13539,19407,77209,7728,38088,9535,2263,23875,183945,17750,26274,67172,10585,28042,22199,7478,51331,66030,26774,192929,31434,25850,50197,52926,178158,4679,181256,70184,229600,9959,105594,72158,73974,2726,35085,78087,23284,35568,51713,155676,5401,27254,11966,17569,223253,71993,103357,111477,55722,30504,26034,46774,35392,36285,214814,41143,163465,1051,16094,81044,6636,76489,179102,20712,39178,35683,125177,54219,30617,52994,25324,50123,2543,87529,58995,10688,125199,12388,60158,125481,131646,7642,133350,65874,3438,97277,101450,10075,56344,116821,50778,60547,98016,106135,13859,14255,16300,77373,173521,8285,45932,37426,4054,114295,55947,7703,39114,52,51119,128135,19714,60715,9554,50492,88180,2823,118271,52993,122625,97919,23859,37895,25040,33614,32102,20431,3577,9275,15686,43031,157741,110358,1884,40291,125391,13736,5008,64881,87336,77381,70711,43032,49155,118587,70494,4318,10168,30126,12580,10524,280104,104001,145413,2862,84140,6603,106005,13566,12780,11251,42830,571,179910,82443,13146,469,42714,32591,265217,424024,92553,54721,134100,6007,15242,114681,59030,16718,85465,200214,85982,55174,165013,23493,56964,82529,109150,32706,27568,82442,5350,14976,13165,44890,60021,21343,33978,17264,4655,22328,27819,75730,16567,55483,14510,17926,45827,150609,3704,7385,272531,161543,76904,122163,52405,2039,19165,41623,14423,228354,3369,176360,85491,7122,35789,303724,4465,13628,2233,55311,118771,20713,10006,221519,45115,71021,35650,29775,7337,10864,20665,21142,1746,15080,1624,32449,10905,105743,229797,7701,3940,22997,178467,57208,389057,39683,59403,63344,63125,54847,69691,18336,56448,3362,37202,18282,29648,138224,35867,10495,5911,28814,26653,31514,176702,26550,45621,11734,4525,40543,73944,121080,27858,155561,14887,44670,30742,8796,107455,113472,56369,75581,183777,240095,133699,153299,8768,160464,26058,49078,103971,21875,71486,44888,17156,9678,89541,123019,102337,3972,83930,21245,87852,109660,287918,183019,686,10100,39177,283941,11274,24736,26793,26214,25995,77011,141580,4070,23742,46285,46632,30700,26669,19056,35951,115575,174034,56097,35463,87425,24575,44245,38701,82317,85922,281616,100333,147697,61503,7730,84330,8530,59917,61597,17173,9092,32658,90288,193136,39023,20381,56654,31132,7779,1919,1375,117128,30819,11169,40938,23935,115201,101155,151034,4835,11231,74550,89388,59951,91704,107312,167882,115062,12732,72738,88703,464019,158267,57995,60496,737,14371,123867,4174,243339,159946,7568,16025,134556,110916,38103,191,80226,88794,29688,27230,10454,76308,57647,77409,113483,66864,14745,19808,12023,46583,84805,16015,17102,2231,20611,3547,95740,250131,34559,108894,8498,15853,159169,148920,20942,2813,93160,45188,210613,45531,52587,149062,39782,28194,57849,60965,84954,89766,84453,100927,16501,27658,165311,103841,54192,207341,19558,20084,319622,5672,205467,98462,61849,36279,13609,147177,24726,165015,209489,59591,31157,6551,117580,75060,141146,277310,21072,22023,106474,63041,137443,122965,68371,5383,42146,98961,113467,30863,23794,4843,99630,30392,82679,13699,241612,33601,93146,24319,18643,32155,95669,40440,15333,34089,67799,142144,58245,38633,114531,117400,77861,188726,5507,2568,8853,10987,107222,2663,2421,11530,13345,30075,41785,118661,104786,17459,12490,16281,71936,193555,17431,5944,71758,26485,77317,20803,367167,158,7362,93430,11735,172445,46002,11532,54482,930,62911,2235,23004,179236,4764,101859,208113,22477,55163,95579,14098,67320,162556,90709,156949,3826,57492,4025,34092,87442,104565,6718,186015,28214,14209,10039,107186,233912,58877,81637,55265,39828,6194,145813,50831,105849,4974,88319,122296,10272,197216,95714,51540,72418,23324,91555,8743,140452,250249,51666,34124,7229,38592,129641,78169,174242,22464,149964,51450,14034,10026,95376,26190,120062,14401,8700,265,31386,143573,7203,229889,61567,4227,140981,2466,72052,10787,10062,30958,6099,38471,30103,23202,208101,70847,467,58934,32271,32984,36637,24107,30771,17109,73353,13650,2098,157040,67366,66904,106018,265380,107238,18535,44025,32681,144983,62505,91295,56120,3082,77508,10322,63023,36700,81885,224127,16721,45023,239261,111272,13852,7866,149243,204199,32309,22084,42029,38316,126644,104973,14406,43454,67322,61310,15789,40285,24026,181047,6301,70927,23319,115823,27248,66693,115875,278566,63007,146844,56841,59007,87368,180001,22370,42114,80605,12022,10374,308,25079,14689,12618,63368,7936,264973,212291,136713,95999,105801,18965,32075,48700,52230,35119,96912,32992,8586,16606,101333,101812,14969,39930,759,193090,27387,42914,12937,5058,62646,64528,38624,25743,37502,3716,4435,30352,178687,26461,132611,42002,138442,35833,59582,16345,8048,60319,49349,309,47800,49739,90482,26405,34470,63786,32479,85028,39866,47846,11649,23934,29466,2816,42864,31828,7410,74885,49632,47629,111801,90749,19536,18767,105764,59606,21223,10746,76298,22220,39408,7190,79654,64856,11602,82156,272765,17079,70089,245473,51813,184407,384678,1576,122249,5064,27481,6188,25790,74361,27541,318284,45430,31488,620,93579,45723,192118,22670,51913,4162,70244,35966,26397,16199,50899,209613,121702,287507,2993,36101,132229,67345,33062,76295,118628,78705,52316,34375,107083,107454,44863,127561,33964,3073,154010,190914,55967,39074,6272,31047,5550,41123,26154,98638,47110,19998,148091,50229,31329,59900,195442,19106,61347,73497,70015,682,45850,25776,38022,148951,6288,37411,232526,109277,27286,32342,9262,5220,16651,23175,46740,129438,78614,121925,66914,88710,127952,5563,21500,34521,10739,14863,191006,62956,17359,16749,67027,56284,69134,43301,35039,58883,54466,60823,404451,75743,59856,86979,7923,34273,83785,32142,7693,268986,197428,282681,17049,22346,22990,92245,107180,3357,37104,96724,49153,7683,31197,43267,82231,164276,23696,20848,188364,22309,24821,158707,1018,22514,70922,27792,45589,59709,10765,736,35218,63479,51987,24275,63588,55361,92929,81964,4658,20122,12330,44058,13065,311456,72224,8337,211229,38979,22590,138478,52757,32595,133600,8838,31549,94412,43391,90056,1585,94802,127271,6223,31889,137038,132910,2165,57616,230152,6080,10748,36737,74579,134062,50525,180532,119270,34556,76155,82394,52595,29258,31435,87820,67996,26943,183878,38007,2410,13526,180297,69856,3503,187396,167700,7838,16701,9199,56267,3661,37407,65994,23767,5708,62508,221700,67088,86978,46776,84434,32088,5612,9149,88244,21685,95151,46750,189612,2979,506311,2594,3628,40074,105039,78243,28523,6651,38058,71999,30992,12764,68261,108991,6165,26450,61961,13400,22426,7490,60890,109623,2070,12958,50355,67979,257096,7213,42578,52121,35716,65461,7516,124758,39268,302,64712,14977,1467,219452,2840,34229,11121,21602,19270,63574,8024,1532,17331,79839,78885,52029,180767,57957,6069,91265,61380,55767,8927,32881,287603,22149,35029,68876,6428,199567,46926,13412,104132,21434,366616,45060,110046,81924,128910,45886,52821,130416,29416,77342,21762,67329,121432,79924,11724,38625,81006,102033,28338,13326,3250,82056,82526,38212,21112,12382,111495,3263,7414,86274,93490,40844,30224,45212,24019,48411,71367,24941,76729,57776,3769,38114,202019,197745,31953,237533,33270,201580,255648,100798,44741,32241,98468,106931,10085,15090,170358,33154,66787,18819,69760,25061,234005,82660,6295,131975,16874,9076,4094,25005,17740,40908,19533,220019,44330,99792,50040,19619,13950,55228,24423,31253,95308,103177,184795,28590,82285,5059,3210,75525,49894,70007,56178,10580,36051,139681,21617,98736,3555,106306,164189,37352,63915,47824,24883,145530,61904,28444,11483,19837,145446,30420,112972,85939,11835,191233,2262,20705,58630,1753,148334,1197,144714,6887,11223,107667,60879,77914,4151,57417,81594,96681,169430,1784,20444,95138,254041,27038,596,7117,72808,13759,3353,126776,21074,55322,27081,36942,39547,139830,179275,4453,713,8722,71399,19204,25785,22794,23923,104114,11291,25458,102309,88396,75288,230440,206396,104551,58447,130857,37247,94734,31548,176529,226077,65159,20104,10096,66881,94191,237909,27109,37404,1520,27421,25220,113003,23423,24884,50585,6286,231877,150800,11789,3226,90004,60642,5053,202400,61442,132531,175329,57138,30116,103847,9973,75367,16452,32360,59119,21246,10191,164804,23305,61051,37348,154530,13214,5468,50403,66754,130976,50559,80515,14436,155492,84017,5472,43107,41240,2890,90431,70188,382,76234,48040,50211,281038,237007,32115,142178,1536,22761,96429,1811,31243,1679,49143,55209,17402,235054,61494,7462,77030,34925,87609,78002,9499,9027,73289,201078,101379,63544,27666,5469,10642,30029,49816,132979,95620,58086,351930,116300,2110,2043,30845,6154,11279,16727,4122,2277,27281,4971,3650,39060,61970,65951,39674,75686,38151,11370,130809,177895,32665,63725,122267,7857,39618,118483,44792,157755,178624,136994,24260,41308,22471,12404,21707,12486,30473,52781,50246,20247,39065,909,56825,103158,128603,31542,1089,41935,32744,12428,37963,84420,33134,72921,208449,42622,168151,127335,147107,46699,38216,12591,94342,85814,31423,24944,2605,87542,67473,192551,4496,56321,91819,17630,6300,256183,114569,202090,33209,35289,34897,24967,40520,43470,5344,10199,34810,14283,10381,10017,62923,49924,23233,64539,13051,35686,19698,11570,135555,120868,44924,87065,52318,52335,47586,140906,245885,109834,78668,9065,46990,25258,72022,61243,40838,4545,146387,10537,11557,17470,36930,68104,46711,24264,79401,81043,18225,120488,24746,84338,81652,28266,13776,21878,46973,1047,230465,73357,95777,24973,210160,62210,58404,110633,169651,6937,41870,9909,26822,191062,76553,27519,96256,239070,2478,205678,67955,58532,20601,50120,19148,78501,195724,110740,8249,109665,27446,30568,57631,31425,49752,32820,65504,50079,3663,102256,219898,23849,211315,14645,4359,91767,9528,12449,49366,7941,49763,107848,8930,27086,50686,9744,10447,81935,39513,46514,1670,29229,6172,22312,137280,97759,9806,14445,22976,56458,73391,34983,93760,174219,52573,33149,59747,2429,136277,75123,165263,91040,7446,57632,48633,97140,246081,84766,151684,79918,93268,120346,54059,54875,77858,32996,103590,45276,11968,19600,25849,17159,132907,42828,16817,4913,99462,103303,27395,5737,74184,20749,21160,14377,77062,131403,158735,10999,27799,77785,9320,34366,51593,61070,33746,47048,29268,36675,30262,53297,9832,82e3,20188,122292,39917,7331,18160,68301,185935,134830,15031,4935,10004,165845,185534,46923,30109,44134,122631,18874,22903,112790,26561,18549,348902,82871,140345,255565,135390,63556,103747,145055,179600,145662,296111,61661,211987,23952,52342,126343,48450,32919,44277,82185,9591,62139,205363,376969,394874,108461,18040,120885,14798,39863,16571,16794,58271,81025,55206,14640,118656,6361,44092,85970,6262,153863,108244,180200,72264,79947,38044,10050,5735,61221,80712,5471,115689,11391,11661,184257,20010,60116,30320,19327,134598,45455,27542,18004,125092,452272,1549,91523,46567,180063,156026,2608,11174,58848,37788,65907,80194,30490,5786,40775,119519,106241,11323,156297,8425,61495,2617,29675,2425,59886,112582,49142,59618,4863,50597,86710,50650,168632,27693,85641,83643,18993,25768,84284,28090,93592,36627,312804,43381,9887,9402,100931,97165,3311,173330,66805,28935,4963,184460,3201,78102,19126,21607,37496,24938,22615,16153,32862,134792,153318,61120,6067,2812,12826,12792,23825,37559,64662,202250,102694,155488,85881,149193,46233,65383,15521,106982,11358,176786,25752,39717,34208,24510,32464,77742,39371,72028,138229,60688,71386,102834,132477,2208,11548,63670,271279,28351,30338,38620,32491,99845,143885,152266,13252,2825,178663,108097,1775,78201,14897,113573,163346,62292,171129,22183,96598,38733,64971,166776,117445,9968,146393,44677,74867,20908,97328,12761,25656,26785,9148,112344,26115,99176,110121,22437,49547,6180,79320,5835,31392,43328,33377,75870,119860,69497,80273,7325,155219,43167,111173,28347,20222,3763,71752,55041,47252,14618,28088,15012,97805,194698,54636,2036,41349,6173,96604,61530,51859,43782,13361,24334,22668,24792,7070,23441,16789,3209,36211,208475,26242,32880,122181,182407,21444,31060,88459,29929,77907,12716,10934,97005,20599,31690,8403,58445,30303,22700,10336,86731,103115,337709,72556,46788,112566,47684,67089,53548,36874,56487,41387,125985,26893,40071,106683,73712,18787,40105,72992,67246,137276,50802,36790,70328,138827,22466,39263,183295,29858,50975,9322,57397,10654,24364,30383,55799,41600,23584,127295,296610,129078,143558,244131,86397,36049,1085,80677,3820,108139,5476,34767,24683,7758,13060,7239,131671,250593,59556,103392,29810,4188,252323,39404,116877,7651,43600,40338,13554,157253,39196,25978,144387,61211,234,50104,6129,10449,93777,9240,356378,274148,4439,72970,3724,147770,78680,62570,115877,40027,40547,36817,224392,64609,34795,165027,67440,2477,37206,23431,50754,164797,46018,94995,170982,27051,7957,22767,3674,27900,56419,18930,60701,41302,2692,84749,339721,61996,111094,80221,50129,1045,8153,62945,19202,8250,37208,37418,32560,79477,41106,88569,33963,36693,5892,30570,1581,66471,49647,11922,160717,29442,5643,114865,82962,95982,132098,22633,22838,94726,54556,28566,205039,162340,33216,16849,35847,221339,94851,26533,71469,1805,3804,12935,45483,71020,36310,65381,192960,34240,35165,59773,1248,46954,155332,96864,4246,388800,16129,57133,74592,44807,442014,38203,42574,80818,91592,26377,36424,65760,977,77387,22628,147610,28018,30561,98454,6969,119628,63648,18170,36854,26601,64018,22027,37279,51395,152934,21153,9430,58760,194742,5330,55115,34158,28917,174111,13171,122326,1526,43896,66094,25325,4234,148354,11450,275,18999,112191,44365,22723,68409,8733,57746,96565,75007,14196,108844,29475,88599,177563,100792,106156,86323,93726,14248,135341,194131,40126,47099,14779,8272,39597,95983,171398,65882,28052,10393,47213,40689,22120,72212,106829,34964,109146,753,648,21660,30047,17527,181025,5619,145357,4085,216883,9359,186951,24779,53931,24545,36197,223296,62628,168101,4243,107313,30321,26642,13049,51059,31027,107912,807,73550,26551,84369,122422,165872,49754,74213,234264,33151,52014,33100,87183,22365,52500,40013,23302,5652,72723,21404,26107,48434,587,94049,168493,96418,32871,70860,31709,25128,443,71597,166253,15670,70994,26341,133675,28280,75491,54756,47955,56028,26182,11952,113272,472197,64640,110753,17919,337,50642,22576,142,87371,53391,93210,126694,15285,19642,85667,14148,1506,42092,52962,33243,11970,20734,135843,57044,58880,13002,219134,22876,64754,232519,4257,43120,321573,24799,64526,124728,52579,81472,70831,276848,17403,74359,23021,182101,74597,23744,148267,12055,7976,5349,11772,67540,167347,65318,18720,127832,108238,22828,90233,9987,259080,118185,73209,79270,13775,90100,137742,90799,70569,15699,19961,9087,67475,57872,39731,8810,134897,131868,146849,19898,3334,2281,167061,91073,60356,467742,74712,188,53179,137679,92769,29241,9537,132595,80119,1041,88962,5976,40171,44911,102859,139059,104558,98987,47761,19272,71472,113864,175377,73338,10857,23402,23758,1591,139864,5644,4076,118760,16427,134198,18853,20291,100849,37423,22038,36677,19071,195521,57445,11069,31869,55718,66882,148490,44,41296,75242,49704,166810,9906,20943,122258,49112,105667,15969,10344,6408,187694,21399,72742,58970,14867,14376,81889,41856,23225,15042,56993,16074,131389,74276,72407,53875,383108,53597,37363,68993,44854,122548,430927,198279,38430,80409,12245,2981,628,2818,17760,37437,238229,7968,46892,2200,3730,34190,65983,37959,112291,87850,70827,6522,20750,73913,111621,41652,19587,2780,58668,25916,85259,18200,168962,95781,42445,102050,7776,57662,103313,47742,96358,41964,66174,100396,29069,204735,19679,27978,7479,40264,22534,61183,36081,107436,58223,14680,23002,101311,24716,124108,12908,5646,31750,40380,14215,232799,102772,14122,96775,61398,50917,12096,149880,67833,598749,124194,155871,49216,790,14677,65319,56917,7440,145744,95701,12206,49405,129269,76199,45732,9767,11058,9047,210885,11051,7392,26307,2130,8132,147526,20802,232698,115660,50060,59789,57344,107623,80343,112676,23291,9866,160971,34032,118291,15719,59730,164911,28975,2659,58046,78480,21854,66209,53863,109085,116045,29021,46481,107552,22130,18764,70254,31272,11300,52460,43933,84738,20721,53869,190840,79673,105300,7561,321817,66924,13940,33281,101046,183181,32176,71878,5678,62924,79535,56646,40303,19559,27703,93042,73368,42187,3670,37376,46440,7023,36816,109628,20680,5940,276440,275233,170848,112093,136996,14984,20226,111441,77693,112960,48577,39370,55707,50314,123404,26570,54281,61372,123391,4857,35928,246740,132507,106646,44241,7196,92258,9825,37688,51197,303141,5590,15476,132986,10955,85782,34486,26696,7991,28813,18858,39546,11703,11365,38185,5716,93555,11925,40121,60002,6985,10976,171384,3887,43394,13337,56346,6381,252336,39573,75042,53711,1028,31781,44295,95925,131713,7214,68125,43571,70954,213234,1628,8760,13391,65485,17320,56038,1710,25248,60803,57399,19839,3870,326,281556,50945,72400,21460,316244,75619,56246,98775,481,13513,55765,50427,7388,123519,32929,57908,27124,61316,101097,57467,30228,48792,10788,20402,37318,50526,155730,34456,158065,145305,17832,43733,64052,4506,35072,205355,177028,184004,187081,68616,35938,83703,10367,36892,93186,260137,51934,89970,4985,23445,26755,21558,7948,78741,23376,124405,85594,68596,57536,49351,12619,56593,132668,99924,109728,71844,71935,196018,65464,17617,14987,89701,143773,33997,8687,22701,33258,2914,4436,72108,85610,9671,49067,2327,82988,1361,1672,44033,35777,30269,24057,10605,82236,616,15793,13919,47249,112086,116698,9484,80207,90574,33304,68624,93127,56101,42210,160929,4827,38995,38095,4701,125119,5027,33680,9236,231236,14135,87837,23318,70261,78893,30151,81482,14332,1084,74256,27532,46644,79185,3148,62615,6981,55672,31668,36825,1849,14536,37446,14738,23779,43058,162749,72199,1168,21346,5592,85932,85302,9668,18351,57135,150360,2080,228015,77953,34670,119302,151751,31009,106725,84265,45214,59289,74178,113071,263206,111009,4021,44449,188119,192629,123592,392506,292847,114487,12831,205858,9852,20780,79648,75767,357014,97721,18166,21005,67950,33226,204009,16536,2987,11335,66717,144910,47950,17262,55060,15063,2934,51038,26775,178497,66008,3427,49433,128592,20036,157553,63861,3089,23015,51210,28696,35933,49942,71135,231518,99620,17248,21835,176536,20676,16944,38700,165831,233253,295625,36723,13023,52745,10907,19423,67972,125868,95473,82875,1183,108455,52685,33417,64095,21433,52438,33191,127809,44505,211823,7810,2752,95548,162031,7185,91196,47563,61721,33359,17897,23682,42806,178101,22874,49707,199897,75419,82456,8618,11171,79712,116847,18783,44190,46564,5346,59046,95032,7893,14916,3214,26800,24172,121453,34362,10250,17408,18888,4840,68696,22831,13162,36005,32512,14800,62357,41723,45046,27247,37486,5372,2564,34261,298500,66509,133920,89138,31305,117697,19097,108304,81386,84106,23802,46411,63304,946,51417,41777,41041,19501,115864,60743,294354,37955,94165,18116,1156,17937,20645,57114,90804,58042,48643,92288,9861,2557,88546,61333,101008,12853,5148,87856,4152,144503,73841,18718,9789,147565,10846,42085,12789,30223,8993,56352,67203,2448,28215,6052,23540,126319,75933,36689,80235,23231,23561,21383,38800,77548,102798,21234,31468,158608,46188,63960,191679,8051,67014,11185,170078,42186,28827,34777,41930,212079,12421,34750,24111,110344,73918,45171,70826,141949,40063,23979,24254,37309,26724,27179,24718,83648,54938,14591,17425,29525,102675,48975,48654,12316,8929,60640,41709,50168,63264,89812,50716,48632,38755,138583,160123,55579,71829,24230,233277,46322,39650,166388,34718,24108,98252,7031,106695,62498,18258,35062,217827,78731,34824,33354,19520,60852,2432,60224,8587,2836,62955,702,20227,42285,40560,95592,62486,11094,53035,143291,18842,46177,77994,1770,9657,107422,172915,32655,128716,25886,25164,156740,119928,165875,85817,11007,89110,33956,12652,65156,180266,8494,36889,19958,20955,96,1264,118288,135769,44754,86671,5632,19026,168220,289120,33569,93821,66144,70635,7687,5642,2714,55445,56636,71545,184182,93133,7332,37389,12643,52315,22729,11014,158742,17050,152889,50178,34601,41945,52136,9948,26914,63548,95721,115951,40759,8960,158258,38938,49232,48325,42234,81523,253019,66128,40978,20048,238048,38760,62928,122560,118532,43687,137472,163689,26680,9878,17448,51035,16211,60834,36749,29178,14241,59868,150086,2305,26477,42422,34342,165341,83279,33894,14257,29928,12743,13957,125571,89134,66712,10952,16507,147839,30146,7249,16565,45399,39874,114565,215780,31990,230881,171477,102,196546,44538,10880,84948,281705,86651,10617,31395,2342,453658,43569,60561,132901,21845,17727,58556,258242,22262,58728,4008,77997,11806,37431,30599,81375,109137,185787,114085,217292,97453,169085,30593,60212,11544,102056,65580,2384,91655,4855,95725,7295,157994,16228,20669,53276,141590,105246,17334,25440,76067,17967,39321,38911,11362,28559,63807,21627,26468,85816,40120,1025,15234,58319,69516,66512,124548,75845,78873,22137,46681,51242,85683,32909,76747,35555,43396,101465,1765,73094,1077,2962,39028,66777,57831,42048,15828,13962,36041,63657,52412,5242,58846,2141,5506,219012,134451,3936,182230,17558,17153,152237,22621,49377,170216,35257,68233,65374,6510,11126,212151,7184,2480,22517,3437,33073,30156,16557,3768,55067,86829,91e3,12350,148650,66017,79424,70885,49066,28250,21369,51213,34533,11510,3258,18176,18465,84413,6315,36411,163765,4346,356,107618,598,13727,285026,162695,8749,14583,7132,63521,184253,32378,25991,5604,30961,53675,4874,84693,5086,34811,26978,56564,7904,33519,51221,113942,69253,6664,125563,22055,220680,102008,742,51930,19494,176108,44424,35123,13025,75685,11759,74335,22250,181453,131147,16984,132115,154311,11991,76452,52609,85351,196,30969,9198,74919,2529,56838,71779,29187,116304,3504,62330,41190,86153,28393,254926,104228,105189,13264,84359,3574,12415,8534,57147,10175,188174,59504,60932,66318,16407,107921,17638,99103,49278,28403,39786,145865,8462,3558,43406,142271,29139,21989,36552,93955,72365,7176,13556,106185,37957,321774,17782,129017,51154,27938,24952,1935,39366,2791,33489,41582,56078,24558,9311,5449,218786,27808,190429,68013,36020,86003,29735,3404,87348,119357,115714,2324,86796,81973,40992,43376,93621,28784,16808,36367,2517,2909,191926,24978,55303,53308,205724,60068,3098,21375,64784,23949,26579,63121,12319,80145,39967,97861,6757,70143,67642,37082,34698,69140,122883,46151,62187,80934,429,19437,135071,137885,222647,13331,154065,327,61778,74257,40116,37493,14855,85079,237641,42342,102164,199965,71204,4662,29368,5042,113914,122214,8955,13149,102503,43173,5659,163787,69003,307084,63392,171080,21390,81918,86666,36622,24126,28887,5736,28054,207170,163428,79891,346467,95363,38980,111806,80828,9200,19288,294896,114468,87405,111715,141705,7015,72754,68463,48738,243147,33397,101210,37051,98801,82847,20397,4940,185559,18716,54718,83491,11725,40803,1128,12128,23060,5174,7745,67007,46701,1571,27807,180186,256996,18975,16837,7877,212758,250379,15440,87954,57755,24719,124057,83461,258,50864,8874,29038,71289,31627,15429,9005,4061,113851,107716,82819,13651,79656,117851,17539,111446,12938,39724,190787,4352,15402,21070,62708,8539,23777,73853,13552,38810,86117,16285,56400,1718,75342,142863,29033,378,110113,180321,32586,23606,26393,160984,207987,23783,8406,16904,24596,47274,11693,46539,60524,78595,48423,31718,20170,9009,146268,15183,191060,172765,1349,138436,37365,10970,40509,225817,20021,70394,152138,21541,66559,66544,89352,2725,17258,91345,7313,3815,115868,8660,40362,4071,103524,39388,118275,21950,6549,38226,32754,209574,29201,43495,18028,20296,40597,18370,47520,202450,24134,2219,8195,69545,38041,136934,46374,19041,159811,84865,58620,846,98749,13569,30714,97246,32186,4479,27355,92973,35214,151491,75963,37631,1561,27200,238083,23182,60756,12291,25766,39355,102333,87362,65741,59906,19538,201575,48772,102938,24438,292580,39964,66366,9004,61379,50548,37622,38732,28379,68180,76622,17488,69849,5963,7219,48143,43413,55358,540,58691,29506,19245,52193,48621,5518,13048,118625,44755,191081,42061,89197,2259,60665,66994,71210,51232,3585,142096,55024,7892,8345,58653,463307,65658,64319,137941,136323,53499,12746,43492,6978,95163,29925,60175,5128,7352,41463,184756,121146,20473,18426,4598,5309,54580,14277,121151,10691,56711,43880,63409,76682,11830,172218,264898,32632,66536,81062,31649,25788,92774,60222,11100,63159,9432,224657,25240,53613,152,138620,163829,2397,85345,12501,37507,64932,38575,43522,65789,80198,78796,35226,3851,108891,73311,3060,28391,93671,39663,46142,30982,66041,37281,68157,26553,71872,81142,211527,39747,118119,22695,2859,11066,20232,168911,7933,197005,17066,111071,44434,133994,120798,12766,227798,45756,132852,29917,36076,55352,65281,129800,41958,18944,84678,18580,168093,132621,39997,54092,27740,32354,3770,114118,103242,43918,15899,18574,145944,3190,123469,219903,24169,100571,62403,16776,92779,14535,17168,16475,14304,37231,1712,28218,242754,61688,28980,1318,51359,222657,99200,67989,31772,23932,35351,201251,49041,27306,19128,40135,3986,77333,19649,120683,151927,21081,7076,78375,77501,101599,8011,89585,96715,58179,5378,102138,106793,26051,217276,4197,16297,27014,46721,13322,22806,5278,29629,70632,9647,71519,58818,40603,128530,8903,36770,56900,31483,26935,43845,34265,34920,87658,6114,84767,64250,47318,50720,19264,162514,33357,13117,6705,46696,75032,71054,87004,42035,69138,11903,99854,102328,19611,34525,69312,6431,49842,101600,133178,108751,41829,89939,225664,48916,99556,9195,130387,5960,36857,116724,53518,94002,39077,53996,6945,22261,64291,8314,152785,57588,16522,9091,5048,87671,35441,39509,1945,12423,158923,178413,37549,14095,1475,73188,62878,4819,24012,68534,42606,4010,120809,57497,59564,101758,103718,32701,80116,12345,95834,46918,21468,53213,15665,31200,3867,5140,96013,250744,21016,10069,13968,35449,180829,27683,39704,59956,22893,3115,26293,32785,75934,62445,141162,62720,2018,83638,19949,114012,95006,3330,99829,130935,309272,9565,55874,121727,37017,23586,319858,40970,27602,8625,112329,61060,100088,118525,25922,16232,1907,60671,51583,44553,80993,5262,94679,8676,940,20736,11823,3020,16476,12340,152600,97416,3703,25744,66826,16245,16876,46446,84798,74227,176020,45192,61955,75496,23946,23626,40372,26036,6149,11822,30582,16541,41914,82385,232823,40921,80773,14930,3631,7517,39619,4348,36180,126106,138939,62611,1477,113512,47321,25052,14546,118881,29060,23589,128322,36795,18401,137921,104699,267929,36194,172791,18113,4766,188215,30083,332586,94089,5805,77909,22194,68234,154976,43220,40660,70001,184893,138095,11128,103010,22663,5108,212615,8485,5565,49222,54614,26530,42639,16319,55062,152662,105595,21114,22216,10294,68158,10436,86950,7206,62115,3977,3657,59874,456,118617,18156,106663,112229,80992,17442,8217,55551,5133,34344,251927,51153,39364,201321,7816,66803,23057,156724,145664,14276,95705,979,2796,6875,13429,212525,50602,26276,28284,3424,19465,52397,46963,31420,51399,206476,92317,48851,637,100820,83349,10317,60227,21972,6908,282439,32857,224767,95629,83882,42106,87338,69757,29840,68709,37665,45244,114577,49188,175943,54009,186746,106158,70168,3358,234002,50555,9221,129338,9562,20118,32923,78479,118280,65752,4977,10474,102174,60947,129006,10570,83451,8598,8078,159367,123785,80438,16742,5905,5281,181513,42402,6977,163136,93179,42191,14968,50421,112401,105440,33456,57347,121611,4221,94954,36517,24046,27796,6255,33394,72990,135408,116627,1233,57874,25654,95419,68156,401399,313338,55208,45573,93124,119251,47200,38196,11909,130667,45391,73904,64964,167846,4137,115606,52036,62214,7969,160925,7187,1132,134835,40309,73195,64494,80472,444841,61111,26500,45323,40743,53625,52797,22659,15631,29739,36706,28841,39147,102836,26794,10536,14845,87305,45874,12241,127587,83833,57183,79722,30844,41304,84655,20825,92500,3722,25655,27811,10157,81634,31362,34088,92487,70123,22190,185100,72658,139035,192523,88241,2078,230490,44528,85638,100198,22088,29982,291233,241062,13865,4445,137791,37835,107218,31726,19718,38234,72528,23046,19177,66695,5109,17251,28077,5617,21554,47839,72425,133825,1486,73065,181275,141508,21768,62971,63082,2512,34200,9904,120309,6392,91243,68416,268253,41199,116757,138551,185526,41246,28986,4093,19057,17295,4148,245766,122360,35356,112075,20301,75441,10998,7977,19769,62922,937,63547,100196,26427,157820,20983,236696,22935,8140,90315,156004,47204,140973,7726,45097,52725,22636,23436,257282,105247,522,88389,216031,202204,46812,211666,19693,68828,81691,45925,11256,30292,372,5236,167826,88328,232776,151611,5360,82104,18841,80393,25465,18285,20320,72377,31730,33160,45803,38715,27705,37379,24163,18360,103586,4015,32305,269494,91252,20080,36567,54650,7797,57073,12650,31164,42209,6375,261663,105528,81661,106002,2800,5375,17247,43151,4442,15727,194619,100855,144898,62320,78465,39929,16454,1967,28311,61363,17219,9395,8745,121445,76939,80385,162380,22009,54191,44248,16299,122830,48151,74429,78291,64755,14238,44966,2511,17712,67954,93583,829,105899,49935,84750,11591,33185,85447,42717,27409,208542,28965,62052,52525,5597,25694,65594,16343,63224,276188,12475,9331,127507,38522,57287,24128,133161,79723,105548,133695,48917,27558,43278,46520,13778,141954,110785,83366,17715,46317,105763,66298,147013,41086,94180,16478,220447,44611,730,19722,78975,117889,125643,26254,16574,18480,65006,15806,38549,246418,46052,36056,8440,34984,30170,3163,59800,4458,115442,4283,41970,33507,104078,1653,22,121158,276486,3655,6338,24048,133421,23641,2161,24422,36006,8086,10675,181474,12307,29514,59143,14729,52509,87128,122470,19446,80852,33314,24573,119864,14237,9652,57779,6612,51851,15284,98871,90581,124466,156831,21190,22015,71380,161906,87247,69201,18392,17908,108470,72962,40719,14338,17911,95260,43339,20610,78916,20710,72451,11315,31448,17263,58853,178878,48111,116002,45497,80506,82605,85880,36300,121755,25215,36118,301929,88728,405223,276136,553,34704,212438,49970,78329,922,20711,25036,257130,38295,145369,18128,15385,30829,55656,48345,8012,3561,28004,122041,192900,58338,112508,41085,29976,87040,47117,23905,4336,92061,138880,97407,42083,172121,6256,25192,172671,5,93568,1420,12677,31605,56743,40620,6015,78415,231077,31298,80026,13902,19048,24924,170586,32955,176119,87859,36731,6773,27711,24658,26475,115216,133207,93250,95820,88522,8317,5714,124047,55219,86860,19677,23961,22928,162209,8904,225992,359835,56084,96201,29392,96558,86071,93643,55114,13347,8183,95129,82012,2017,123336,34219,115554,157159,47747,101684,41008,18735,193781,104151,226906,7552,179874,124113,31159,21162,44010,14771,51268,166128,31382,73124,77438,92830,205709,12113,1292,38937,13114,1334,2118,15597,69581,14449,21934,76618,48728,67038,14967,51495,24243,87736,147249,26720,11119,46063,43749,5843,44147,152629,133428,65703,14269,45604,57982,28672,55616,45957,8438,95433,37698,220862,132034,39456,61870,4161,26501,73560,56418,9845,4654,20916,10456,88920,119358,9015,65931,96507,48029,38534,21676,109081,43078,34943,25089,6131,28766,23665,5477,10255,16695,67,45778,42443,42770,29534,23733,100513,62617,42630,48746,14191,43753,50295,26007,8792,57243,43119,54725,164253,58250,112304,131796,25165,4651,3188,24831,47748,3705,19540,13211,102095,5593,18699,23666,32005,117571,33541,60584,74573,86311,99443,25172,27222,168938,7143,11853,53560,18834,19960,86522,28217,53266,117700,72989,34323,18721,66450,34346,74056,47217,202002,46269,9429,68582,75458,37823,82843,96652,32549,145144,27958,19820,158086,31955,201406,135379,31207,192545,12950,51704,9094,248263,76147,64028,110009,79407,89345,99284,223492,47966,26848,15359,201137,2861,110507,71231,72297,31851,118777,71039,151051,240855,16333,50766,14727,7939,4149,80908,418780,88378,59276,1327,7284,38576,79814,65820,42199,84860,49574,62596,12396,70598,40117,8648,7994,16836,7630,14047,359699,106878,525,29037,28064,13380,11675,50669,74216,103539,180314,27449,56299,172344,19274,7301,246099,32043,19422,36506,129317,6806,30140,4614,46639,66926,932,86600,6322,27847,233103,10541,39025,34887,3517,12972,26220,2031,66561,115015,48658,47596,12714,33845,3893,16165,35237,89983,14769,11962,147224,47018,29977,27979,5552,82338,86023,131368,1218,24853,237840,132193,15455,40873,3668,65351,53388,15229,59889,272245,47934,11858,34347,18038,90853,86981,300602,19343,114181,29362,84921,6095,106059,79472,38015,1206,48741,6208,8e4,21916,17423,6002,108083,24479,34931,56661,9511,26995,100694,163853,35997,81254,58321,18919,171890,86877,91341,74503,70477,53412,7027,59281,39892,131302,5864,15947,61301,67466,162369,47956,27874,35624,282324,21270,111847,102548,41482,30955,116737,28264,8592,55458,22301,75090,29821,30697,51709,3041,19208,8038,24634,30467,87509,126428,19389,18814,152686,20701,83474,45832,80891,105808,11378,153223,120770,98186,150633,49838,9141,12755,30962,5260,74490,21256,31678,65062,33326,289838,187831,20595,89768,2805,58535,10844,70085,12090,2451,138068,98544,24461,4511,6754,41684,28203,3383,65355,82833,30161,83924,234361,128424,28921,222594,33975,125491,34069,11508,67464,144226,41850,98703,34371,7901,21254,38398,65651,23549,53883,213340,123269,12028,71764,177701,28758,2623,68395,11549,15232,68603,9660,63116,36079,57093,31198,20475,48467,89984,35619,186847,107469,31389,43631,73867,41949,68841,114250,1605,30564,63403,17588,27680,99533,12641,70325,50428,73426,78379,11855,91651,72081,91720,60198,15743,12065,83398,140046,6761,46598,45900,5068,886,62448,148968,37347,19405,9680,15819,43496,63370,75667,163700,37639,3633,22774,34341,183131,134335,37200,23915,7054,14194,12970,26438,13350,285521,25594,8219,104410,91039,168804,138480,149734,15907,33818,61132,60082,4622,110187,56736,13551,73571,3945,73463,65498,17758,263266,17593,2710,27585,54469,38200,45367,63754,28881,3473,12791,98287,31895,65787,4463,94536,24951,36332,59901,28803,52130,86403,7668,181822,74831,18977,9850,177206,145485,109798,7292,31421,26280,77211,58511,12507,127004,11113,147,8729,56208,43066,79926,129937,31345,83947,39915,46146,98763,42566,1337,13192,18323,105163,80570,117753,16555,72883,11077,159438,40764,70933,83329,26066,12276,72059,21655,173836,126713,69454,153482,91585,70644,102558,110483,6764,127864,190133,3961,101798,20945,71138,82402,90884,69669,44753,923,16939,59700,164258,25969,27082,31399,43846,6306,246093,51342,6153,151581,202801,182731,56475,162188,89426,141356,14355,121815,27536,28023,65257,77523,106668,127314,24947,12790,38796,169698,23555,10725,44573,183083,42088,62716,43265,105958,32050,44067,50118,1668,3874,6243,318411,16599,1691,94999,52378,28671,216728,123258,2059,34969,69225,5913,136280,171443,141515,91662,22175,135282,80020,92270,1663,4808,4482,3495,34691,5226,109830,108512,17342,107488,11606,123190,100247,29666,146527,113014,15794,30894,13224,39585,243192,22351,9903,7836,47699,11078,25468,122291,48821,26780,122679,75521,81450,630,4895,92900,55074,74293,17441,3563,111657,103102,51613,12318,52370,36191,68245,34269,40445,41354,122901,168604,182500,62012,42557,11259,24428,115113,86345,12362,3909,78430,86852,134602,20459,47853,93879,22577,7659,3688,38555,13349,17381,56715,91639,12493,10895,92438,3142,37057,28928,2004,36427,32268,34222,209974,10432,67436,41989,173518,107930,27079,62729,30908,55558,5828,45031,14902,53546,8204,144263,60255,14520,88212,86582,109589,69356,8064,47449,8505,66558,16886,4844,52817,111260,215129,12941,91118,650,20770,6273,73089,40618,62790,2873,35002,14023,97208,19386,102646,36993,143736,135457,35385,113601,17893,32627,84439,100619,56016,6581,57264,172160,45452,111710,203627,70131,24100,322787,1996,35665,70078,22358,90922,83658,4097,63200,58499,14542,99153,52159,6615,12414,63415,31986,16823,1579,65405,137809,8841,16898,48082,259,33014,42375,12260,179850,73667,91389,98882,29532,17311,326251,41092,5928,20742,44964,48019,43505,9317,49265,6643,192712,48424,163487,19861,20113,70848,31928,105333,23685,78563,14638,54755,7158,24142,44018,20774,125255,20331,24280,10163,1285,2336,39851,4299,117269,46714,63816,87779,159624,11731,9971,990,137317,108831,50994,74554,162680,23640,131597,146962,170620,34829,91205,21184,1913,63616,18427,93136,156592,17519,67565,115882,138220,78622,88535,18115,2711,33554,109492,54298,971,24914,25863,36363,45715,27099,194995,14299,178181,111488,72395,322385,157719,130787,11897,81843,83999,11369,49280,118604,40922,61332,110343,53407,75639,40582,300440,54722,25637,13694,48248,48278,194521,56203,52779,48783,72627,10953,376,16733,280238,26351,230789,15132,25168,137270,3588,63704,73376,94031,74284,19443,159557,9697,39901,13351,119050,15406,146455,3460,29556,75195,37673,102524,92329,47289,98413,15311,100684,56345,7116,95480,11590,7200,167,23610,58426,17730,136656,27944,53151,2701,8824,103124,3017,90744,113588,53216,79736,65940,26931,498,29568,80540,143543,21292,1740,59268,16561,180816,42323,50174,40890,52866,10703,57169,4700,17191,4424,93511,49698,166650,26972,48631,165169,82879,69326,202970,4007,2376,231325,139592,22119,62851,37504,68816,58345,67398,186643,43331,277416,53749,15746,23102,17432,4793,151138,48822,54265,48203,198688,14305,54287,2291,18018,113378,123260,7180,97549,87027,120085,2920,76080,8190,102005,5641,64580,14955,59802,54028,58884,19367,81779,412567,85957,97053,103637,78871,29364,27637,141728,4767,30686,112738,130146,42745,12730,105040,14844,232,210944,36581,152317,135543,29744,3129,55647,58149,46319,27265,17499,28005,59948,7170,34138,5702,293047,110892,408,91760,218674,18469,46095,81403,14389,4610,35672,73060,11006,74848,104820,118143,190357,20043,105358,141735,5115,27093,45924,123073,52599,29433,9616,238350,78610,24851,58858,26769,31969,24613,18294,4982,32735,39639,143563,112073,202205,12567,4873,88601,44897,81503,101648,81362,34662,85277,17574,48173,21435,221188,40215,39576,80786,26544,64668,81841,10731,37733,247986,149188,127703,495,18382,54388,72446,43071,30974,198723,89608,41360,190,33045,8386,31658,19992,237838,119015,137622,50890,100913,6460,116233,267230,26621,104129,65114,14190,41542,14888,85962,23342,23041,26453,43725,71809,45186,4770,46452,53894,56616,221286,18973,9038,109299,55365,19366,26863,18808,60909,69353,41738,83463,12100,68561,72860,3980,13796,49340,12332,31311,27418,4255,53430,18976,45523,510,14224,30477,26581,4530,3651,101663,139840,22709,150861,31996,63923,120623,262522,3076,10528,2929,14672,130238,18087,9816,121894,100308,25085,55111,14565,18952,53293,2042,369988,23674,61789,133529,28783,108293,35477,47119,36448,71049,40015,33055,78598,198442,1833,159937,40654,77444,189245,113153,8621,18599,38553,35223,166072,2375,11659,21786,89523,6032,12116,63046,159398,18454,3678,32521,47626,11411,103527,38896,42946,15696,26370,10185,8413,37080,165583,4331,63555,14907,72220,50056,6623,62236,36565,49783,10049,17503,100581,55951,146244,24724,9626,17969,25524,109300,173965,99994,101056,46459,43647,53737,277968,8347,123521,74858,33829,44762,77574,877,81377,222525,123532,30602,43881,53145,2973,16284,81940,61281,127044,63620,9875,14756,114829,19032,9202,52759,119141,23928,120551,19607,3599,33401,76821,73233,117430,39968,36539,7071,5446,121735,194059,15206,45283,6706,15603,65615,1207,165723,92275,34773,104447,8396,32353,205240,164323,13600,60555,79205,25532,22907,33410,57480,107111,69630,32137,47832,70913,33161,20321,2371,117348,10714,86246,1625,11763,17900,268,78457,99175,97940,101092,86660,32221,14041,128504,125080,53744,124263,31017,13897,403,31859,21964,5633,111630,5547,77329,17961,18241,84995,25984,12983,67491,62168,47262,5241,297,51191,7351,8967,147212,82060,16821,782,11033,82431,62957,5026,43459,77963,203477,53528,6247,191852,87774,74164,215654,13467,1522,219964,28589,244104,16242,117821,67725,72570,156792,17186,15979,26990,44128,193014,35276,57125,16212,166451,68017,6905,77608,16364,53777,75921,76426,37975,26203,269296,64099,84122,12077,38533,830,4407,20139,963,43028,38902,42911,37503,83343,85045,16979,1165,60835,137387,58380,86990,110066,134540,56331,193845,81238,17922,163093,38744,110641,12502,56404,34862,26865,125964,12965,111648,25547,7771,27196,136980,9555,29551,107158,57885,18831,37705,35505,101742,13970,102109,62548,124657,23328,11124,89592,146376,248050,6241,22033,18337,80685,29898,11908,216623,67721,106162,146610,21377,15085,91552,42041,62560,122532,125336,102365,121537,142559,29693,223919,11515,110495,18776,22494,5895,185059,103592,229351,51220,100102,37027,257855,29359,54123,36066,106493,12244,79258,32002,432,56205,94836,90182,6726,14762,29391,48938,26864,38083,60364,3310,60192,14766,205567,57504,110760,22649,24666,46333,21517,3430,13135,28873,27052,158809,11597,20529,6695,23138,22960,37137,45574,6545,305877,43423,26153,24769,59844,14501,10430,134352,56169,13213,103432,49523,35181,13435,12408,129475,64620,230854,77390,51990,15653,83248,33466,44571,117828,51481,2187,10559,68019,18021,54895,48247,18354,33737,4554,108595,37288,39767,116707,9175,3726,108877,21616,83684,49862,1938,8543,276466,20134,108498,48770,102254,31914,131520,185291,100559,51890,209,19526,76471,50544,71814,99351,8172,198526,28816,20419,9109,98389,136777,76479,75596,30635,165417,48216,120220,25955,211071,39314,24308,32164,2559,146280,43403,9233,17947,90585,1786,86920,125662,2457,64741,32152,32918,122882,78538,44001,31723,56426,23375,103172,88177,145697,52506,49319,68016,31664,41488,18486,110400,7030,28241,986,109199,19900,42147,56864,65287,49183,7858,24e3,30453,840,16673,25907,68916,89927,6309,158335,36407,199737,130464,13137,59603,201778,195292,21015,42466,179062,172561,89492,11075,180407,31868,72493,20998,60217,9865,19530,39274,130266,54539,21623,12535,13505,40641,73375,4087,85633,2153,3117,70680,55788,92096,47509,98493,37490,271936,151475,3032,16171,96642,34106,78425,125761,19591,3366,19316,54508,24183,50786,194248,91528,33253,34622,108355,41741,705,3814,3883,108929,13203,67831,10142,59754,68208,29128,84820,56880,38794,24972,48571,40821,40476,18137,164254,24064,236309,79181,11282,395,39169,2013,51587,28551,9645,701,109513,115899,113566,12762,62045,58322,103726,41343,40866,244102,143816,2490,70346,40973,52618,15412,30720,104315,38917,42027,93676,17513,107418,20706,123890,13399,97727,24044,87962,65606,44250,98044,65276,74790,101473,19350,91570,1326,87790,172042,7577,100813,86896,85891,41512,108130,27794,14875,71431,12835,156250,58135,3759,22476,42176,115873,34686,56523,73643,108505,51491,20838,12721,32863,45700,29496,13700,34294,55360,29206,155942,123812,7706,163234,203,132720,49358,144431,8130,175788,35818,3270,76832,25710,54095,97274,28779,94621,74396,19092,128242,58067,20885,14670,93255,15107,63291,23654,126900,129421,59294,262659,9798,3251,67344,28600,44629,50672,29072,26999,31526,23183,49175,165843,175455,17282,175411,32022,45989,30298,90690,78118,83156,23749,35636,31317,7069,80381,94561,133756,14960,97404,6138,41065,78041,32843,16601,34123,9559,146529,123377,96395,54441,42012,84257,123541,10745,22139,106459,11720,150883,172651,154996,110538,4728,53447,25704,2009,71152,119354,21166,66604,1429,216162,8637,122250,63520,27180,29172,36124,276428,107787,77184,4680,14952,104903,24418,14793,51561,52931,8371,26342,48526,7118,92066,67280,40653,8847,34597,105438,14198,50163,61188,146286,50315,41205,170829,161496,585,197359,95056,1687,365794,91349,48507,5804,49263,5146,104902,96365,117343,132222,46084,96919,16875,8073,262381,79982,52663,13928,16056,153908,15145,109256,132308,18763,24904,167644,13618,40750,18686,147124,114709,150038,52849,2938,12568,48617,8778,5459,44202,44591,74914,17183,248689,13878,7822,80060,23116,194037,18487,2067,7798,43077,33678,244028,31320,74273,2794,19466,8218,36280,183997,48124,19416,29656,19280,98734,7715,18311,30701,133602,150307,126956,7378,2933,79903,13178,12593,86571,26604,92446,13574,44205,65699,427599,21118,8245,14407,27877,47936,33542,7916,26460,117762,21596,37818,2249,127359,209394,60044,47677,308089,36791,154971,31417,6998,150042,174360,12255,43009,29335,48739,3912,101398,53340,2580,146939,151295,45360,125275,15273,45383,27456,48761,23314,8750,60801,85823,104759,27894,123685,66968,39480,26917,55290,83305,2696,98390,57569,145853,340733,4919,20024,52268,30884,7413,203685,70989,112855,4129,50536,349518,68205,332641,159581,135361,236026,37563,176404,64899,6578,122033,63871,1850,85234,82089,66124,74145,121098,107351,12687,36881,117334,13136,14698,85933,93866,18047,32620,310,15094,46e3,88451,23632,36645,27940,87618,80520,58892,20976,27702,140090,96075,67841,103292,238964,87778,107338,17019,83427,67522,7302,8261,47570,116787,8730,80484,61772,174422,56005,131193,52875,14588,28471,59817,9586,15720,158155,51307,109734,15196,11025,59331,3884,52626,102602,84797,25158,27314,4437,20488,76214,189248,35023,114952,157376,2827,62439,102878,129749,36405,10329,109339,108633,36662,1254,13267,5470,87105,58004,15397,10434,159667,21864,52022,179464,3013,32147,31496,116832,18494,105502,129227,107267,50033,13481,9954,24267,22141,16257,116154,36185,950,115685,11305,176708,2048,178671,112573,287867,162328,497663,95170,50979,193861,50987,30368,136257,31830,46549,15119,169876,23788,17462,249887,57377,1949,35448,14791,43769,210091,3783,34612,282103,88380,245190,5457,20491,98908,11402,86899,117916,16028,162584,60644,320177,156096,31065,55876,22e3,77655,9992,23397,13757,317623,63978,215255,2443,17648,93231,27388,104529,93807,55505,140477,12046,112040,70887,40152,94365,112353,25063,114679,266061,71248,119555,15589,2244,617,14129,211431,70110,100652,7777,4383,85911,89221,21010,120615,58357,86405,37554,41647,18,15143,69662,60491,14714,186134,148344,42347,5410,168175,44535,42449,343894,129417,99682,20659,27272,140483,63455,222159,17536,13722,42637,62324,11976,114691,148109,2283,32057,182393,4295,147364,33705,2075,44303,30274,28331,63740,69740,29148,10346,44862,33716,73937,153333,12930,38784,247159,2515,41053,20256,83368,256189,54639,115240,5096,24661,175419,153552,26516,141,138176,63885,34115,47222,55709,2765,28479,38875,236608,12229,22921,77291,54426,45388,2860,57787,114579,295139,105782,17826,71066,19119,54364,69385,16568,12323,28057,33346,34919,124763,155533,101386,31644,8627,49001,303600,29868,63213,9103,77280,71333,9696,138789,37059,24823,5057,21352,32368,114208,56803,19424,10445,58514,8661,209508,26187,171838,10460,63454,14016,122504,41328,21329,46618,32493,38225,7855,31763,7945,29876,8734,6438,24205,97490,139977,130740,47323,33195,85390,57194,13813,60600,21313,96251,7699,27584,170521,139271,1363,4402,336738,129223,84983,69150,13147,3590,163929,207225,155260,55916,20288,4503,8398,98490,11773,27512,37113,84976,86558,28365,11756,116005,182148,13733,115313,47644,67208,85069,9347,14995,226141,14704,101835,41159,35314,13113,63526,214039,29978,50446,83339,17440,129441,72522,118641,97816,24907,73844,15717,118884,167255,96509,162793,30847,36849,51297,78974,77793,10427,1873,2972,9999,35074,28190,64297,146836,46298,60038,163007,108919,61219,2403,75022,127339,4233,110389,69022,9833,128097,88016,79390,222936,22570,94657,28462,56956,38803,81536,30474,152794,19566,16481,147408,74574,81895,20731,1918,1366,76367,187321,54494,24366,21690,61696,33283,107477,77499,31112,414383,74362,18463,218441,120929,59848,258629,201924,69269,454,19989,13054,59894,3623,58908,20681,35723,78523,102680,38988,184112,108087,50944,132704,52966,21699,18860,96349,201411,82697,85395,95658,5093,6427,177894,44191,32755,26961,155739,6249,31310,81030,26574,84311,120155,86730,113535,7424,48888,13516,45747,98098,20077,183995,81945,43210,26704,40420,75831,45648,11180,6855,57927,65528,124096,34851,2598,156633,107572,127352,38169,123845,60142,62722,105584,232364,23211,68120,1601,22169,89299,747,258039,80572,7258,152249,11862,101204,8834,121434,33761,19175,133142,46343,40178,48723,3589,41977,30210,38868,62257,10087,82658,87827,90646,16415,47552,351723,28298,72225,91146,272760,1701,11295,1652,109651,300747,51863,198800,29446,11794,32345,37538,22356,33102,37590,113544,37970,11478,179743,25454,103417,59905,221970,105196,145604,7817,164809,102360,16974,75840,255333,56902,6659,1954,645,59400,67769,7689,18675,5215,13793,20536,27852,3387,29523,259718,16860,94625,43143,29245,15848,233581,22685,63631,78557,22836,133302,84513,1348,51826,47129,98836,58284,1830,1749,94642,10933,6145,12506,10975,13879,103781,144434,10268,28409,32346,52968,121567,107374,77268,23686,35097,10501,155275,15303,47136,21102,168741,55332,90385,15996,84817,681,137803,25054,142275,6163,38175,8056,124296,240642,65621,4934,178205,16101,62803,60964,18230,100622,76465,44689,14545,9543,47514,16852,93380,28048,12047,107106,37575,101485,77047,57326,34819,96137,76916,6469,46264,115983,75768,87668,69942,13027,165,8373,114231,26434,52844,42799,182044,23580,146254,38081,43236,33883,146220,382894,14606,46035,36481,166621,35417,95382,2957,59384,60428,36358,66343,75378,22267,22950,83528,17577,56474,25285,4619,179691,75355,95836,53295,34588,171410,4487,14679,84208,44015,18562,109133,54101,11531,86052,174479,303157,28095,9953,35642,14564,39802,16145,77606,117406,53038,121117,53624,22062,1212,7632,127157,237292,189087,10478,127345,102515,181997,86752,87623,10966,121602,68783,68681,83042,114380,138349,191305,67176,50085,39016,1427,42384,1412,67118,122616,72389,25260,2237,13576,137346,19938,20304,2191,68759,5373,61364,238507,75814,23931,69565,38993,131741,38364,12528,87762,5679,129853,5310,186831,32653,90338,260176,389531,108118,26843,43985,50175,30563,25106,56965,18130,140428,4542,165503,117991,24219,229605,1819,129663,1240,3797,76093,18398,71339,51919,93043,27175,47060,216257,6483,35051,1217,16512,80798,129064,13225,69339,8548,237079,72298,2575,34280,51379,117910,55671,53345,247552,29486,39328,140821,34681,57045,60177,5004,90269,78522,2479,322607,48474,61296,13057,31558,4678,59271,6699,27044,31988,35944,12503,83480,4389,136508,3781,114121,70279,4488,155829,42214,2898,68191,75695,305850,45041,74344,106509,30087,17429,93292,12477,290,23080,114802,35714,18751,26554,105424,17775,2144,2412,100610,65192,113975,52975,180272,135050,129815,76238,106483,21440,63186,4260,46189,9711,28249,4169,23429,23390,8324,141585,63809,67668,38457,38063,39226,59972,1189,203916,62368,14403,16949,61767,85801,1739,40147,35049,76757,33124,62102,15780,103593,103009,53484,22952,67973,114645,6566,5245,50462,7601,8288,3513,194571,80276,1908,54592,5124,58571,2513,6800,273997,193904,1119,17991,117245,2508,129156,82366,26278,71465,63341,56943,39662,106116,94966,156875,9736,2204,122308,94418,27134,1280,24539,49022,45314,3764,50904,46424,30699,28087,293839,9400,33646,40165,822,147499,50263,116179,29085,11863,31314,5578,17797,5104,12454,1604,15342,219206,10232,67800,94261,25872,13565,90339,78971,75377,26649,41184,47695,11514,35369,20767,14227,41953,309396,148270,147938,33074,14453,27499,109019,39018,25738,240196,158931,52820,8612,95853,21524,137010,84901,70869,70021,116794,48404,38771,6732,1070,70990,187297,49140,5238,576,3564,253975,16027,16483,2811,37775,19034,25259,4053,2e3,70083,95774,19713,33431,92703,91314,42381,288770,48194,95985,3991,77418,13406,241328,245086,56533,35275,62725,9246,51924,70181,95331,16163,31410,79016,39312,120878,119371,275987,80124,27712,9186,220,23598,146167,85209,68238,282190,57048,31273,30555,80913,17594,75779,59160,135002,101219,189377,29225,96735,60126,62522,104e3,27620,86814,17240,147533,11001,5425,43682,410,49460,87270,69480,46315,59448,1816,76201,9431,11788,87960,29063,65539,47347,11678,33846,7008,196704,9895,6753,8633,120892,59970,572824,115934,6646,202559,892,48351,37611,251282,57823,67263,57750,26527,34485,90747,7685,88370,6144,64182,1709,41969,21458,62327,181657,49247,225330,122600,114574,107124,85361,111833,63243,71420,15655,191178,72430,18063,51425,54002,12364,53225,86557,18193,97580,41232,138398,67821,128724,8944,233212,101353,52099,42127,14006,120107,32789,32132,3498,18123,33758,56058,5779,128760,59888,98869,18445,84702,51911,13234,218379,20093,39031,8074,70195,20708,23462,24355,131384,60189,26390,10403,41060,7140,10781,49410,42261,87202,82566,41663,43105,60276,2768,5733,74176,28329,2297,145430,131632,83615,122915,105441,655,224102,5284,136426,67763,16294,188511,32538,61049,27893,3394,13951,159099,28542,17930,145360,9492,190122,32285,78855,26440,13570,58648,73908,4239,124561,2444,74172,53131,11468,10794,73566,11623,35343,64710,30481,4163,10328,38309,29901,10538,154377,76132,92405,24839,11679,3465,13449,11637,7824,2337,57754,1260,14458,41118,19878,38661,13416,159180,37074,163164,54137,28627,52134,184900,8520,40385,29546,30502,22386,66527,107458,6850,24022,47983,30603,35083,8934,304066,39500,9,28261,33026,77251,9374,44833,116312,34990,29236,63563,125639,135405,165398,159055,55690,88141,69643,236964,31983,25572,20436,36746,60896,31850,16179,11828,5888,3043,66368,9750,31167,7915,53111,36430,1333,64344,93659,20061,60596,180191,51630,6792,30244,43509,101058,22409,420,44210,109783,43223,27030,72477,72831,32679,29235,7675,47556,12258,39907,149412,84926,118247,24692,71717,105038,86009,45941,41189,89453,29856,52543,30627,226798,67303,59230,67415,34408,1367,99685,16867,128419,52147,4111,125381,117881,16173,44093,102224,31575,23234,24870,83790,127407,239098,3200,994,1255,100903,242275,117266,55116,38205,16140,29662,11307,40414,208793,123355,56470,4862,75600,30119,58218,70828,24075,26974,7802,192353,4851,5475,78720,66596,3409,28573,64396,30381,30690,59859,88256,5406,99945,103064,34463,37727,24238,86643,60088,4057,23741,5967,162904,38240,28356,93858,25510,122879,6897,3278,7057,11971,4400,35461,211413,21395,59615,39471,87233,55795,128426,3051,22470,41950,14705,3974,180108,80476,78442,204996,91987,15634,67610,139015,142373,35611,51134,10387,4353,153456,57749,181039,14183,68447,151532,21107,36452,20551,3186,46247,46383,129666,88736,140662,146243,2066,8360,7978,64818,106963,17896,47801,10723,114821,223295,74192,3293,3393,16987,74064,11277,91622,4270,29828,27951,387869,103235,1374,61988,120083,477,145892,128378,11779,211263,61354,18221,17869,46530,83061,108538,157981,90608,67199,95080,49064,195814,12302,66307,10348,231346,160732,112859,63633,146558,21271,31037,198802,47622,12862,95710,3910,77850,73961,85585,34752,61e3,4082,24595,103679,71107,8208,79568,150019,16615,24961,139857,32664,197366,4559,54735,32696,4126,162019,75698,13916,70108,159638,19834,9349,24675,175560,49643,18206,52459,27992,10809,88865,401975,133172,29e3,34558,30915,3658,25834,42430,36562,125265,18182,10155,40149,97082,208980,19575,60853,90529,66545,9600,789,46420,2317,88593,55595,98980,115302,5742,169155,1073,177901,3472,11189,63711,78643,65472,50459,127979,93,42202,67053,21720,157650,11145,141378,42033,22824,85705,79114,35584,15974,1510,54172,28562,12451,104226,19190,97151,73024,20948,5151,81741,21499,29006,84183,198074,54003,45120,170125,26240,35177,28389,64863,79974,60778,176915,232183,45342,2038,80253,41564,40703,32689,5430,100689,5366,23007,134279,14266,26712,73993,24934,64242,52113,102887,61801,46415,201049,54251,62133,122757,164883,30815,139966,2319,30842,766,13362,10287,134518,86111,81665,82440,28333,43019,18963,8804,161944,23439,102144,101145,80029,39052,248708,30350,117340,11878,128467,974,138625,63961,5237,74778,61834,67040,43814,13690,65947,33809,232476,115258,181745,28824,94013,9510,10246,93722,81976,7217,114383,3493,16014,69045,72692,12145,80981,9507,6692,1620,60820,330444,35474,33962,4797,7053,295463,46445,27026,12491,77988,49524,35675,90947,29114,166705,101385,133782,32704,6186,84595,176031,185623,45966,151302,63069,1699,107491,947,15458,74452,196212,6046,10498,12163,10239,35191,243951,9277,9090,29539,54460,22820,26514,112549,60372,51753,48756,21812,70861,260326,41,44222,10441,16961,48148,138771,216194,5914,52153,53400,212036,56519,26245,10117,45888,15294,138019,90913,26368,43842,42111,23348,6082,194845,161089,156206,51546,11647,30759,302912,262094,8635,78876,26535,35283,54183,31183,85484,147873,12989,5197,6356,72894,65347,20150,27370,73787,1493,45918,12366,190217,20724,13858,10981,67449,81213,7553,14115,72242,271517,11842,48310,88743,143726,22177,3290,243231,58452,62937,12592,1654,40066,33477,13751,9921,128442,15868,7106,75236,83773,10775,36938,10482,170465,17368,17469,161508,32752,98340,800,19824,264456,3901,87319,2867,26782,9630,113102,185815,24197,44584,86366,40224,3636,140916,31731,267731,9567,53678,72984,29389,27963,17106,50282,284911,60170,8322,12608,23374,89652,5268,39044,229766,8869,151350,31436,177342,12269,183212,120418,116270,2843,78888,69192,7865,184099,1086,129897,18383,70508,20242,18508,229924,124569,35749,50589,55626,9884,83115,40971,30671,18135,14452,38861,17844,201826,5549,26413,17189,13561,38539,10679,143331,3314,36785,171194,49685,187713,67506,4618,104039,17060,195080,50648,33159,19238,67559,134840,28599,157523,17130,38064,117398,94355,31918,13575,34538,40326,13997,3494,348283,62481,26862,3603,104426,244363,153709,112487,304612,199674,41239,35545,54869,293005,28223,26277,26899,4533,18518,15492,38587,80488,70485,160395,263,60162,11382,222152,4696,250751,51921,182609,10707,48463,46243,1227,49111,111564,46502,33342,56846,68541,63559,858,139927,16654,229375,76759,26478,33205,95828,23399,92945,2637,35630,28470,143992,50214,14174,21456,166191,65665,1711,21594,78019,97599,111701,36,147151,110246,189022,43021,30397,40757,131935,42065,73335,48039,26596,28984,15102,2361,7421,202167,69744,43766,52826,3642,83304,33873,75140,63169,192389,36551,92748,13039,123959,233220,21738,84447,77230,20228,187852,19095,25799,92136,108774,29237,53947,2299,118106,2687,8830,42331,202924,33667,2023,73763,30704,19363,19779,16737,35629,48081,24068,101013,162338,291912,13749,24745,328289,167679,70086,48299,23306,16732,17801,43322,54589,3586,63653,43624,53474,925,109177,251316,43805,13082,19511,86565,142182,92461,17117,101033,103319,64589,4022,4351,235897,5352,82705,107142,46391,156084,5860,61365,10558,13045,7717,18357,33922,12590,33065,6928,46993,783,46937,67846,8952,26295,6107,119656,18799,17458,50747,4229,179559,112727,118080,20683,41464,125468,51560,49749,44231,7359,35339,62988,136487,67015,5208,29150,24956,105186,48858,6143,18097,6972,16404,73489,58742,97196,36357,164616,5834,32267,13746,147733,15113,132091,34127,106298,39729,106426,22294,9780,15602,36213,71502,42808,66802,599,60755,5851,39120,67363,108623,126368,72770,91263,32486,30596,151717,7951,52002,43103,11768,68942,40901,39344,24037,127500,116890,48403,16926,86750,17745,48648,159545,34460,58419,5634,114317,67865,31462,23352,24010,98185,125708,69686,68337,13610,26271,70691,2980,4768,27225,102402,75453,28106,8104,6931,1176,6274,6475,112635,22498,6176,238686,26832,28893,90319,14441,15682,15087,39517,45270,109134,104440,45965,47645,81772,7876,52683,87720,12898,4505,185665,2769,113401,15664,57592,105229,137381,97059,119268,6876,43309,33886,128363,35476,144249,67013,143587,83367,25703,91436,59347,53236,2289,16519,19844,46309,58558,99834,23313,218816,231303,36388,51333,183535,109792,139277,54306,90139,18235,8275,32710,37677,82464,86025,92204,88842,117723,37570,128723,234242,76350,73795,34896,148247,58424,11105,11744,45746,63372,17118,49772,199520,81902,38004,22911,33752,3125,1995,53792,4689,26909,108150,146062,69674,41811,161444,84855,8999,28561,16731,93937,3189,21967,24890,22943,1356,145300,51569,28802,517,118679,31703,40607,48098,108854,25003,10233,73969,177495,5248,24516,215347,146192,48712,60626,69188,40735,5866,586,101541,6509,47590,52129,5969,222045,110933,25733,24223,65339,62812,2414,155418,35819,16022,78423,43138,20995,128255,240673,46745,236093,72176,57085,97841,61248,107,36068,193177,105427,55726,215229,20446,47228,100420,87091,14429,121708,23605,21157,187721,21880,2997,203976,99166,95068,25877,7724,98925,83401,4829,13182,18229,13718,239662,38653,116505,153497,30589,89029,38962,181302,43853,78872,180301,4786,248240,7401,106136,112590,77745,19731,60880,77789,125748,135487,5975,48627,34084,12419,215770,47557,254582,10364,106495,21856,67539,88981,38805,21428,48732,42316,12149,16078,52808,25327,51322,33850,51147,12253,122354,46077,56483,254553,115417,81834,150991,94662,86668,7381,12841,100650,18218,15741,22372,68294,50705,15535,84660,61887,22553,72299,31361,24824,17743,46820,64288,31582,77006,111674,116384,30760,80920,86149,77192,51979,79691,60342,122805,103800,240873,160744,233114,78962,54920,8608,3484,316104,72548,24337,5088,230040,21926,10172,36838,26,86221,83458,102176,12062,17571,41929,41170,28428,68239,41750,103930,2634,18313,53019,34825,97837,63115,24606,73157,152474,14715,91439,37033,109806,140259,30668,174760,380,135597,95673,136073,65073,134249,13829,17279,122305,4420,46444,10237,64848,203623,70728,10349,182885,65075,24519,25783,40318,34139,22222,63394,55266,102764,41422,20126,65100,90408,53640,35128,48932,11192,38935,96839,34782,39492,19396,41332,6250,5511,19492,51304,25936,104466,54099,73771,86115,5080,7669,30891,111700,13931,25276,72289,135447,14820,258641,25265,31005,281179,75286,393,95359,14623,13584,6680,101227,80173,44933,76666,54542,13244,39348,458,25379,109451,134348,81143,6959,65554,12027,51311,8716,57589,140731,28467,23316,17272,30458,25980,55229,77197,83798,28302,114784,7428,34548,26241,14712,39336,103304,18928,54080,12870,334,87722,15208,16895,142098,114262,39820,83913,57817,28682,7721,14900,108672,11250,62246,42849,415188,1724,26555,24549,25505,26443,107450,145899,61035,43528,6901,60726,65906,267741,21338,147590,42079,18924,73017,135236,15393,5206,4026,84185,1531,5988,113890,82647,303391,7386,69844,71611,189865,76523,31877,13315,19314,198575,32821,1928,67641,25913,104475,103489,3297,70391,18406,15446,113347,19295,93790,27856,1792,167471,116449,8541,4408,41757,63233,25765,86680,64501,27034,24816,34975,6079,4486,49693,36229,16917,21581,62426,27862,11612,54284,35702,194034,355,24277,48262,87411,70504,310164,118018,12516,47559,43502,57433,107139,9290,66533,80863,14634,34312,91725,28606,21342,67241,72355,43244,375789,37402,174015,105070,8342,44167,67494,1890,16365,11723,271002,1865,47918,8350,45564,27742,25110,125803,8553,49504,81925,62211,4534,15491,19011,80373,206920,667,102405,128623,245524,5553,113309,192739,65766,19567,22832,261958,29679,21293,71134,20962,105123,24721,860,21752,33448,18372,157167,94822,35770,173224,232737,75729,28937,46828,28062,25453,5207,140366,36665,30652,6169,67920,150458,92040,23186,184604,92330,20891,176492,49427,27828,38305,42495,143982,49560,25503,90043,29747,65328,47830,12932,11068,77721,9003,25213,94205,140426,46090,89945,138173,192691,33329,112232,129905,35709,27514,1841,19957,31411,127476,53572,17497,173549,55063,175135,19841,69314,5192,237921,117660,150697,4060,273045,50414,98940,65348,153665,164423,58804,156695,48994,213928,86036,28608,8355,39574,34540,16927,135680,18374,151587,10830,53805,16878,16623,4282,48030,8537,14986,46102,13062,72897,72,33050,108227,39451,45935,651,113320,40535,95176,57450,48843,5003,19019,10407,211163,3848,1068,4988,32091,30095,41692,15099,43602,107434,50744,7627,171349,16313,150832,352665,207750,33937,38256,51091,156e3,87889,90663,84175,24908,114900,50365,31494,83829,5398,169342,47521,54818,18935,8356,43094,41212,174536,10082,92550,6678,60614,23355,69721,14796,34149,128830,58187,3179,208,40325,28399,225029,401412,51150,31580,207268,6657,10993,69818,64282,289845,23308,12961,38447,6681,52944,31855,2572,47646,120728,179148,37240,45196,218274,4816,3695,21961,50084,35209,18073,51452,27004,6100,33941,1377,84831,171214,85,141510,9078,99227,32610,6417,11718,49868,65579,87902,73018,49062,46280,61742,21512,40862,107733,15941,29168,157765,144919,14487,5767,158014,140070,7241,573,71584,16921,223566,40331,179473,35081,47926,140885,41508,52104,59180,42310,32811,29048,123517,102413,80208,10104,14746,12649,153641,126022,37965,113017,4171,83,142592,2809,6362,50416,71323,116894,260776,16204,1524,5760,30351,12658,20703,54403,36083,45408,74772,4946,14485,50759,111222,10890,2195,167147,92962,130534,16283,177256,35016,15472,210156,151187,73922,117691,43250,52051,37392,24811,24358,30830,5775,818,21969,1476,127322,151783,58392,31021,106913,65215,89407,90802,28531,11690,20234,95249,44602,37256,18707,11928,5161,4410,26571,51903,49768,22008,25252,65780,209499,68769,203726,13249,137363,48845,86823,6658,5674,31881,1083,1823,108676,34518,166752,13791,14287,91576,91429,8665,11529,26401,16191,91972,30964,5254,28486,54697,79613,66520,18447,22870,45203,194466,22822,51703,12278,76716,44595,73455,33546,12235,144843,36154,51247,11116,33040,3180,225753,60864,1972,28469,12891,28879,10338,144157,56294,353058,38302,41447,87532,110616,27065,168438,6557,1213,50804,144643,24817,2390,136531,38174,247513,16190,4059,122791,131994,137430,39506,57650,16305,5188,54309,106128,20628,88071,67394,395446,250285,66176,91254,1399,114196,43915,60230,44853,27206,106353,43013,18733,345105,226453,51202,16607,57106,117175,35492,10476,89598,127439,15187,39624,13688,61570,10615,31111,59370,6238,175252,32143,224492,41388,95408,34384,148238,78307,38959,9340,160091,61443,15737,11216,41244,170,38299,102443,113097,26382,14027,33707,3957,76300,66160,19431,18900,6952,1717,108656,82206,188021,257335,27295,43999,41210,31777,46956,57457,12657,11489,15697,48060,204748,53583,82422,284790,30503,137341,8120,19615,220311,15991,10217,63424,9808,67431,70976,98221,4491,15177,28535,144789,751,13230,2394,1504,33977,132104,30316,22230,931,97193,185240,24826,22687,174322,15307,22988,1390,188745,180325,29580,59068,74903,18994,29195,79,15436,7622,38462,11566,138710,44828,45774,37768,99236,68137,84083,19282,22698,17134,74807,126662,173497,46248,16938,119735,3212,28292,213652,49013,9975,32180,45660,86250,4801,68788,95490,77482,113751,11994,44624,94452,46839,128497,100316,5798,58588,73184,202987,65417,37790,88524,1606,43156,97964,105717,34947,11203,100060,37742,130074,93653,107799,94311,196106,41347,8035,10780,16390,27883,118236,167395,1979,25006,19375,31628,18916,144723,78502,114047,103107,86492,107686,5844,20934,206963,23556,22591,16562,146333,20167,10471,117434,33085,2863,9740,36669,41849,37271,22790,18209,28979,8231,12952,54408,21731,25130,45208,55748,138120,75826,414,29593,9925,292865,25999,683,123149,7036,92159,86055,61827,103680,23176,54918,58466,57578,13305,5709,86479,16697,31064,17660,200919,10770,49793,33423,32370,52047,16488,62555,6459,8426,83493,7763,59725,82812,18628,67760,79405,68557,9612,7673,28102,56517,69620,171797,32458,29541,15870,81109,32080,207644,71495,21202,11039,91036,61230,2810,130800,32260,4613,60590,37112,75214,33979,126402,155062,30642,63875,12810,194463,82799,47664,16725,36685,43367,61099,449,172150,102867,21691,301838,36745,7130,18671,57316,34852,38034,54182,35578,65900,99486,19771,3456,2658,16914,99866,28390,28109,8262,21147,34353,20006,4228,137085,1675,203023,283196,198286,214375,163329,290603,152574,40471,83506,30068,14730,23177,131539,34759,27668,32178,71896,104799,116305,85430,119262,42860,25160,8911,23428,49437,105322,6519,16203,6349,74711,1230,38045,8540,75165,44736,25909,51026,317034,4984,32281,91312,27060,44431,17817,45363,155937,239085,35697,59784,91993,29531,126740,213757,76560,167776,285273,24262,8237,65030,41160,74437,48804,118916,13159,37842,1031,75349,1478,11655,108777,23435,277425,101734,67469,70231,124711,43532,28514,65526,54956,1e3,21882,17728,25302,40952,52214,149632,1999,2111,3259,63362,89961,220561,39777,26335,9063,10572,12416,34551,34623,38604,24723,5947,15588,69927,66252,119177,69173,46629,28714,70715,212408,20521,406913,74380,11716,50659,50862,37009,88460,130101,7210,53853,538,65120,151950,55806,163748,52837,13153,21100,16674,64536,6091,138201,44837,58547,3723,163,2177,32288,85454,34033,8497,14282,25742,10535,10741,79559,117493,243787,49337,100718,79495,40139,42956,7551,55433,15421,31509,23034,45081,547,61176,53434,328001,8470,36263,30145,4519,74173,53935,11845,73774,60211,78025,3,4102,73782,109293,315332,48412,26683,13714,6865,20128,18490,104141,325,39470,171970,115860,15707,7268,73301,74336,31370,2368,111827,107757,136231,142844,97138,96638,84053,38691,23801,1588,10573,122098,77039,240,186135,146101,11996,18143,112963,46171,155836,348769,47795,121213,116266,132515,3344,144804,31286,99187,255838,129694,35894,48779,55235,148582,71967,65282,15174,13920,47080,6147,108242,157593,125025,7136,1286,28957,127956,28402,98813,20805,7532,109417,40610,5041,32958,15142,18408,108596,33543,50517,27748,80114,233434,91447,487,37094,100048,30541,43477,10639,89862,155868,37667,8726,60684,237903,73408,99589,12190,38739,97348,3914,13594,2680,149016,13907,30171,28343,23530,115225,61104,35821,147679,14337,4297,244282,24085,326976,56428,7851,21303,131620,71446,83253,68692,111870,5224,15813,38197,49026,45057,13660,3306,76345,40671,27905,91072,996,68527,62085,91351,122634,55109,168209,2024,27560,112707,17352,8306,167115,169921,166958,5031,46020,11844,67284,19130,76185,6920,32849,5450,14610,22451,21002,17392,31872,66682,84796,13709,40210,59898,12029,8719,53564,21462,91884,21647,88379,194428,12754,37797,132826,160016,22567,54383,53186,77611,31107,8339,4694,19185,90355,23597,17222,140675,28442,23668,55977,9128,61555,28774,155229,17658,9390,24379,69357,15752,127381,239631,62460,93181,55913,45133,140155,18676,25249,33164,29581,82837,67223,22362,29975,7317,52813,1943,29613,20012,207130,49617,49651,5636,15334,36313,29226,28084,95247,72072,19e3,224932,15811,114,32127,38097,37508,88507,37225,27359,91626,12193,69279,20608,11055,88156,92808,2152,57259,55275,72789,24475,104414,1708,9882,3818,48661,66897,1631,34806,227930,85815,87753,18321,250664,72733,25107,206797,50891,8082,196411,92596,96764,152823,65514,22819,387277,62176,51225,40329,15563,189,3659,73670,64357,51793,275136,33482,86653,74615,67058,11318,125720,15388,22388,8267,1730,102663,170910,40784,7144,85373,13040,7088,94309,583,44224,140424,77439,18496,164026,36578,4722,9151,5824,63365,26510,35199,40500,79277,32495,44614,35233,9566,203293,152144,7097,2330,183480,98629,13423,330887,44130,68600,30939,97829,31012,345465,56747,94879,4939,160027,149761,99423,46099,32251,15332,8761,96094,128555,5763,235318,222223,55729,30241,55420,201746,3987,81382,8259,49325,23287,7719,24633,251100,92311,18591,110533,64759,170260,393860,7175,21144,132887,3593,75346,101277,91109,16387,259187,11627,57459,173829,44694,55780,49797,89192,120443,62622,3904,14814,23887,1027,112258,64955,99800,11132,66353,36202,48624,18158,88481,96882,43059,11040,2455,7077,21651,181159,99126,100434,61388,68186,19161,110468,120052,8819,55324,41494,7014,37689,3618,87729,92615,207943,9823,128657,12587,15857,6379,67628,51216,71775,157617,63244,1503,3864,218754,110864,5769,21492,7243,1192,87921,85529,31512,18537,42698,35350,73510,84474,34301,8991,21013,35034,566,38832,19838,35586,37216,39413,55006,12178,59742,856,84563,6900,25632,17437,49786,30723,13847,70845,4044,7843,23944,235976,55530,48942,6518,20939,73769,192653,52936,95207,23895,132542,142982,22632,87452,48042,54018,178468,10728,26230,23559,363,81269,142012,5718,346258,31456,84333,246476,51018,66692,101804,120570,39962,30373,70593,2864,60541,19425,54209,104092,7201,31545,48018,25865,15442,46257,40443,8328,6451,111782,47527,97754,33046,470,245116,31095,39,91934,87208,73470,36708,36521,12801,70624,36272,8892,79768,12427,55454,103756,5908,52390,62962,22720,141138,94634,41689,128402,126390,6628,106394,35527,134394,82727,254651,194502,148064,89549,3202,28359,957,21954,27906,49840,142747,8307,24206,48978,1186,71728,133038,71474,91306,6333,110959,74600,70387,18983,62609,56057,22970,1147,135850,1321,28834,3578,59715,102227,32827,81415,99952,55636,257598,390,22702,35701,85872,402916,39216,189795,14929,19467,10112,144422,61514,5279,63421,134686,41436,8424,51925,10598,132295,124416,4604,194739,210929,57866,31829,51626,50007,9976,91878,61906,56168,81906,60918,61859,40017,23059,16887,40927,62064,12785,32893,32913,21782,93965,20169,44387,79084,38463,11457,93950,27127,157050,2697,337088,5116,54128,48255,33279,8821,27352,25515,124022,65710,28906,38557,33390,1722,104435,72215,38551,12094,30978,25113,6671,37355,175109,42862,98024,65406,221276,59624,118012,64637,78760,86697,21426,1639,40350,12584,67193,84144,31396,7863,143011,69629,63112,9454,28666,65798,46372,134721,6314,51402,30837,151922,2847,38676,38008,92823,136245,17540,5504,109295,205242,37606,5211,214892,1586,20670,208711,137743,19328,40652,16995,20023,14657,154919,34422,12996,13918,38221,47690,16398,2959,37680,89122,6721,198469,91876,172043,83898,101992,26084,94570,3635,76958,22853,76497,38266,176590,168403,44464,142840,79180,184594,1984,41806,83147,11985,6546,366068,59732,24533,271505,8736,39084,222992,93429,28962,58985,86665,8432,30028,14548,32439,54424,165029,55175,27458,69046,121277,46168,33732,20661,24581,135574,123110,37556,79260,72611,16957,12939,46162,58238,44907,72936,253758,41324,32518,96480,11949,124438,65280,43256,34107,53533,43531,37037,28366,45970,32741,173438,6121,194202,62969,26355,30314,58370,28455,1848,50519,82830,90393,21761,295490,10936,256940,133568,44050,20269,4089,27457,21610,219460,36743,14821,101388,52005,13124,30979,140816,167362,26054,18458,60789,34917,40447,26606,33422,9066,3452,83614,5761,20263,137238,25038,91310,101,52322,74548,42572,38084,214054,186568,31802,17665,30620,141936,37730,14420,4265,187218,49640,188208,51441,55388,96452,66659,40869,42039,60967,221027,19234,178581,29105,96050,9165,196118,157335,3738,40354,117436,2965,34136,59659,15570,50843,230035,31444,71260,43886,18316,5387,38500,168508,17406,32174,8828,103373,143806,90367,3560,18719,122310,16508,26719,2541,105429,6645,37998,73190,10591,235916,49737,87112,233941,53188,32193,79154,4544,52905,126477,7580,63501,57314,3216,31337,6541,103083,60846,49,9756,15481,1355,43840,14319,13743,27486,10222,73114,230718,418644,16706,6674,279748,23058,45273,295831,86306,2743,5535,88773,21829,35253,120938,31153,3169,16839,42847,8751,80974,33942,36867,35514,16485,26474,77775,56877,5391,48346,3882,108713,31403,27804,55248,26235,43821,136104,40118,175507,28034,203908,18732,1788,34030,106427,36958,54359,7251,44936,15356,69139,455,157915,22173,140291,50348,43275,82066,49621,54952,15216,36226,96695,66855,6936,1987,8227,196087,4631,68827,99004,47541,110265,17953,147605,110242,58520,31312,38724,329975,642,3155,34497,75937,6207,73843,6120,17249,51429,117746,3218,910,68961,319671,14938,29555,34700,1649,66673,72268,9655,76800,153087,6941,210168,27130,35398,1780,73242,3135,56689,19556,165307,8765,35967,121458,13333,70453,17350,117253,22265,13340,44265,39869,441,3742,135025,23581,33309,16543,17731,13291,157637,283005,21408,101360,63887,52312,83873,5338,233779,23759,186949,34531,177320,38069,156465,91004,19353,59852,68160,14891,1338,1072,29823,1950,28901,81407,313445,73038,84807,162348,240257,37162,138934,16111,58013,41253,102951,16457,96056,19541,56402,67217,41638,94381,89674,29481,37456,80815,151579,13937,13683,132537,19699,134545,67020,29816,222341,141235,427578,48868,129557,233342,23077,87871,16213,18728,16184,9469,37913,19680,2798,171356,178328,13216,50049,72690,71904,124644,55455,7504,29052,41036,266546,19899,30391,188755,8659,59469,16,104298,112943,53865,76203,138226,68857,139953,14125,107625,119795,173133,4398,50273,48808,54390,16466,122086,31835,67035,50971,48859,7508,46427,66477,73021,84615,39985,83076,46779,201569,53336,36443,60865,168164,143810,51393,25548,169307,32896,24485,38424,21837,29087,275813,51674,6714,64883,46169,187369,55186,76192,12852,12018,62134,31067,118303,16542,12125,10579,4928,26291,43854,7091,10946,253716,109062,39283,17261,113012,258512,47764,125126,32646,55892,80279,201623,149872,3192,385,1208,48750,5376,58738,22335,5427,82416,47811,32435,143086,38930,94128,59975,156037,37977,38224,62485,7698,50405,71027,16462,21559,136153,34131,107506,162069,63703,3101,215029,40407,4178,3774,9187,80019,17880,97926,67579,2600,18405,8351,47924,86638,70820,92206,86453,29610,42241,119200,3198,15466,67813,57863,35454,4779,99518,4649,104641,144269,33730,38073,65864,6838,109456,193298,154007,5623,45741,30846,182578,25573,157224,1543,58575,138703,146140,44971,49356,18275,59064,20300,13122,11848,24453,11973,9797,86843,2919,25530,49210,1130,161220,76788,75373,85604,34926,36014,17777,17255,51533,11676,92226,51845,119859,21525,5936,18507,28050,1140,31418,14857,34207,47859,10750,36382,32079,106909,59426,87757,38393,110042,15965,97104,33757,35344,97993,53979,33651,45407,41884,82515,173089,7177,58371,35365,47543,51927,35587,10670,23544,29306,84233,39976,76076,62097,9007,8668,28119,78281,120790,19835,143020,54968,18670,64959,20649,34469,42570,33001,136570,87796,120044,1106,58700,63951,127623,12805,83057,40212,31773,49850,7361,54336,347524,101314,23751,19569,48791,29174,49369,20467,7465,75842,38281,623,112457,60210,28849,51003,94720,6426,90047,85560,43761,3579,85105,34607,90410,118528,7224,42907,111163,18168,6960,161135,191298,5247,100584,127552,171568,20121,91173,12636,54615,20199,63730,98105,2396,40387,14438,125012,4765,33235,12865,45299,37728,82098,77872,114037,59253,19675,24838,398016,102561,11446,17069,57508,178277,65836,99941,26114,2585,271882,136866,50126,11027,155648,118367,14585,8910,123015,335383,40434,41016,53021,14439,87098,176860,201543,121888,2358,9286,5739,22666,54270,37884,169381,33984,93859,16124,89364,72207,51639,76366,99029,65812,2198,12147,174891,194289,6986,30252,88822,21284,11445,288337,160821,33034,100869,43852,25761,52882,1144,103809,1924,84458,86079,43411,13542,139276,18141,34978,41298,7276,26481,173800,33210,17951,142652,33616,33677,2210,19941,98568,2486,192414,80136,12058,235883,50963,249638,29572,27221,47034,6124,72107,63346,97620,158513,299699,40388,23235,37176,224244,198386,121323,67992,23827,63170,17838,106622,158590,26807,5345,23489,91891,55474,74834,37981,13058,5977,72552,34706,26828,145172,19904,21367,34043,960,77092,91381,4733,47446,7680,41697,5170,16960,14741,46101,13656,473,51842,37433,11103,11551,121951,13191,97536,165932,50397,51628,129028,9069,44885,6590,59195,47045,32940,225472,90345,21833,13303,29407,96615,141951,5198,6028,18395,7181,3861,14966,156358,167182,36529,55253,25942,173153,30959,27261,50691,150176,162201,38467,48462,80602,42163,118482,168,108756,26011,17166,54149,456538,22512,91374,13816,90358,131615,18132,226707,1824,28139,26860,42253,93877,77351,65575,8980,80574,22020,27948,40422,91324,76376,13528,39281,91685,82215,122541,144066,1983,193851,17283,26320,2739,194978,4790,26845,42627,61300,65815,174612,55133,4200,191130,79771,158321,52280,166796,221620,62461,11278,4067,88152,83409,31717,121367,13522,47325,37945,10406,174348,249321,154101,64912,29938,51775,17220,15776,166138,78890,84425,54121,42861,16368,24572,291647,10197,32073,22651,11677,97509,26952,35787,18424,41910,71614,94977,72318,41594,70024,275419,37702,60199,7335,39107,61315,18271,18394,33768,87884,104277,123724,7277,56288,71981,189803,49320,3352,6798,14240,8954,69220,94433,57372,28620,68863,193727,85575,42309,41667,67689,42081,22543,44824,12719,28540,114236,101553,27638,27296,4300,5353,4663,19379,94098,3758,95888,95144,80344,87320,28447,259518,12718,71391,152731,37063,24132,31911,104896,15672,103782,1521,4945,72541,23717,122632,15619,87175,206120,29428,189780,61416,28350,44457,972,1175,47233,198738,95789,41907,21953,97034,59341,22864,53713,16873,32971,20693,20954,31336,21477,16169,38370,16412,9019,3841,24599,21938,17085,6484,81198,76413,5849,72514,12320,65247,276175,37234,59796,52642,16312,57349,198507,94148,46134,18958,125552,1747,18725,151873,14901,5490,68287,29470,3689,64794,40814,26018,25692,54450,2703,88278,124886,173087,174e3,24159,179477,24276,46004,201876,209202,445,52876,31948,30206,157610,39180,18439,44124,50469,5774,96278,222758,200216,50290,45486,20435,46986,46276,140133,142326,15569,13363,47522,92583,2182,7135,16853,22998,30272,4952,63263,35623,39096,53789,44864,20053,110392,124213,4630,16087,28221,127787,25839,77481,44693,13464,113146,6983,27069,55717,50102,4760,7107,26186,66507,59145,36032,104182,71328,29425,64317,50781,47465,94298,69706,74899,22754,120756,25108,93077,56834,73286,39928,16218,41699,176763,7555,70819,50083,26895,23315,26014,16773,123079,41712,5719,31516,90427,158540,85051,183128,40864,27505,55392,9058,45224,96857,30901,136622,96557,56304,120061,11501,151448,5773,89743,7769,86069,2935,18471,41628,10114,33660,110170,49479,26745,92846,33221,26731,18795,87076,8550,2100,29972,120289,3077,72490,33784,2630,208722,50861,63483,79029,6419,39467,14302,45286,64207,9686,67513,44170,1050,77246,59266,17055,53801,7150,11111,42432,4278,94579,362117,36175,42902,41933,39002,98489,22913,74161,84773,57036,17556,162288,74485,178760,93867,73635,128860,50362,261,67455,80001,46080,35662,4368,25247,19230,74393,22588,1822,27682,235324,13798,85998,13194,235067,23514,71669,147632,23191,134748,214683,105101,1518,25489,247114,7380,54842,26922,3971,26361,20844,68642,170517,77339,123255,8963,77818,150998,48466,36806,2732,23261,11741,236162,18243,126216,28690,50546,16385,92760,197383,246558,201295,88255,67588,71687,176076,172653,169058,33906,63747,24835,157621,43338,30050,46152,132741,2770,51371,94835,6614,15112,11749,56936,1250,19027,399017,58036,100215,23388,55815,308768,124152,94803,9521,64186,8971,28,30427,62163,7616,103838,35079,29203,131235,7743,17389,10882,37420,61460,228512,85363,41581,131077,62822,119647,10130,54445,26925,19968,29016,24446,74028,24176,61448,67185,9254,8563,119129,9771,99184,37716,39514,10532,221512,258753,218630,55980,23394,32141,61924,66749,32411,3741,36475,26678,77010,44946,91203,128749,116953,20476,49625,53116,13735,102335,29376,51946,83407,67892,59212,34685,21083,1546,112982,32972,74397,1078,190545,16082,86140,58591,89611,101531,10061,105104,76319,20035,17551,52611,169061,190842,100780,23907,90413,115619,9675,34710,193435,49443,129734,11183,258877,16318,136182,126808,44635,27304,192375,2599,125648,47051,12091,23814,721,58800,40137,66726,97930,60877,74487,7942,54326,9841,41428,13762,8211,85383,6950,99177,79806,201786,296464,124087,13144,29741,41721,47634,55088,254286,106408,17041,99064,12942,64086,45233,14005,2612,55827,255,7984,13980,38574,12776,46654,73499,249951,2101,26676,25996,132326,116415,119062,50449,31033,23038,11589,179252,20007,14860,129270,21143,17796,144715,60106,70758,69842,34674,282133,44014,16774,57268,38528,24053,46373,201667,28327,471023,51889,102667,21193,114909,84132,69317,96723,67969,16134,68145,15058,28765,32035,2524,101089,98664,25045,76571,14957,86040,118506,262428,154764,81573,39681,283900,73287,127825,544,80448,52347,38512,175971,15180,45467,33086,46552,48894,81107,43213,36672,54025,76703,8053,7608,13299,56619,20752,238099,54164,105133,1444,32942,953,37564,8e3,66316,119463,106817,404,13667,149108,128597,31267,10269,49836,106150,1484,52330,76965,160486,171648,38456,31263,22424,37738,66245,67467,143369,60471,75610,20895,115528,86070,60854,40796,49347,18989,15030,11371,37578,15779,79867,10187,86462,46402,155626,93200,40229,7090,57547,108053,99598,11088,47505,41218,206017,2173,20988,30219,22919,80563,57566,42369,93141,41675,2407,182519,120495,27154,16702,29456,14349,7958,16688,117177,140375,42467,261919,74916,153569,10836,34742,49526,7621,105997,12212,2270,392377,7755,17959,25086,232152,138791,33847,13860,35316,5811,1344,71259,50452,207539,92635,50359,5821,33674,30255,2086,2587,96264,17543,42,6029,9580,43007,139248,82831,12917,29607,25786,51467,42137,85161,100698,31561,88989,121990,278500,3602,109344,37982,15279,116442,28936,30880,87894,58079,128661,126731,67392,28051,146885,4861,16216,97344,42827,147561,153948,22684,21335,47685,1853,43349,15185,59642,10229,25520,187921,108972,5579,98037,24945,6697,19193,63734,137934,75056,89740,19767,224268,56138,63643,151661,39313,70618,84031,89723,84074,13703,85626,35460,8867,64845,3439,57906,99776,63968,49270,81130,34356,16210,23547,36446,34090,140028,72439,2221,22163,57058,363492,113754,18913,95451,48663,54464,54037,176097,68425,3023,34906,29482,117389,341780,80431,58330,16753,92616,60907,94846,147486,4498,48646,7773,46801,7778,18946,464978,47558,33223,177444,7328,15626,63337,94700,11743,9351,255024,39098,16447,42647,96230,39769,58840,10068,63439,35800,65843,58823,413844,9156,51258,7434,61791,85018,6872,3692,28096,7121,33024,6009,75532,31997,192535,9661,3304,9547,14753,31987,25314,55689,15896,20430,39472,31340,99744,25398,115569,54883,28719,205423,23071,57855,64638,149867,25671,82403,37616,20668,39989,77996,74948,140555,175248,64810,36515,46595,4958,248773,24045,28728,136673,168704,20804,114833,100325,27135,21205,96151,153134,45992,7093,13992,76047,1980,19432,145001,75159,87462,17710,1013,45556,34297,144882,20648,26061,11319,129567,108555,18872,464580,33386,22717,65948,167189,5603,135042,79542,8801,202632,18114,91882,5973,5239,67315,4431,60916,47819,71693,32597,32606,18183,45072,80329,76385,24749,51305,40314,156514,14693,130345,13168,66214,18029,12858,34801,27628,14544,10823,40522,40185,33739,148694,23548,9923,61012,28859,17933,19442,34364,99849,164107,141167,30629,21054,6744,36491,8096,42474,41706,155060,30650,10600,163442,1143,96655,61390,52359,7559,51568,64256,203854,4467,22453,14504,436398,7878,6980,8293,63610,293747,16167,35763,19627,147603,15419,18032,110744,51346,33681,54571,40472,48615,39073,21604,13754,173027,92560,11083,47299,63062,11813,52007,29883,9734,139722,15953,1550,20651,13616,49306,16113,90089,92326,7584,30712,72424,164858,6831,152871,55746,197721,34167,196442,6022,112107,55215,7538,123381,4920,43539,77165,8939,50392,34192,20225,79762,22505,58667,40770,29788,97180,82835,4568,8579,13273,363569,35898,49983,436,36598,3237,131691,62418,35591,8101,4073,379438,65218,76072,33887,2968,27573,212619,288680,68278,72851,150504,217896,6913,121339,22017,35340,51072,43616,75043,31437,10833,81487,4364,22968,41454,106687,85446,19863,109625,149241,524,141850,214404,54376,657,237023,9401,108137,53800,32474,49712,53334,126876,27337,45552,177696,8269,15036,12097,42240,2328,125374,119295,99715,2500,19624,39441,27220,102691,60957,94543,39101,18566,67362,13975,78230,25017,34017,239007,90027,39351,41681,35354,43822,1043,916,58587,141983,94818,38799,75459,41114,67432,16195,36606,59568,22272,126769,31424,68659,12287,134302,257977,5756,207285,95637,47248,117689,19583,77451,22373,12200,54993,117118,34244,29386,34562,53819,71267,64172,77665,49368,7716,59301,25749,45426,194789,17297,2650,1766,32501,45198,20403,20984,6600,14171,94604,19037,5402,29896,9938,59935,109708,88081,145182,44844,39167,352626,164173,35374,45982,6122,154,73419,220487,53834,53601,17992,8609,229321,5610,68098,66815,71012,95069,140968,27396,8957,134489,24656,86659,56598,134852,17316,123838,255436,6613,41610,138033,81452,32023,32396,123687,63398,8693,29712,30407,19296,121188,3551,36099,20032,111948,56624,16547,27453,35916,15378,52039,56849,13489,22214,73177,53097,277349,2157,14029,187886,10260,141743,246460,91880,50869,3788,49486,133566,54950,33120,129337,53768,18333,9525,26902,312251,10297,9020,70759,16647,112432,59260,84609,9818,82766,73569,468,46001,75780,55028,52106,11498,43645,108069,17150,17753,29417,16705,31799,9606,289,122254,115975,8620,6133,255357,56908,14456,133464,43554,79224,11247,29630,160,12756,25464,65960,350428,62521,321796,100359,67358,35169,46172,113128,48988,88868,31094,33266,6847,60887,98188,49659,69117,92977,220228,13947,80181,35103,62170,97351,13475,2440,199768,19498,36597,46971,25234,67806,62881,84717,73648,181966,10488,94149,21550,26655,63436,48375,14405,165650,9621,24439,28043,42735,4490,29963,56674,45373,1934,262446,50855,67098,26898,5261,52696,40644,33900,9440,180286,87162,22940,19704,26936,69769,10254,101759,27406,12243,48e3,73926,113215,54935,5726,192787,4312,106216,9366,11550,52949,23457,212271,277152,133895,108374,6191,96477,29980,218916,58024,54696,40853,91124,65894,91170,65908,252552,6793,29212,15389,44516,122515,52617,35058,9017,103536,39510,49136,19242,130652,662077,74699,47024,31422,8517,73351,24399,13867,128360,4810,4434,61779,111983,61036,17798,110240,59722,102960,39688,10001,23803,23039,176498,56659,44814,134295,17188,77577,74466,226175,102472,154333,63900,111747,18062,41171,79669,32773,408933,42562,28931,30907,107388,43487,2946,240310,23938,24354,319,184983,7927,6488,1422,10790,68809,68209,64775,4361,202,17123,59634,51200,44391,18188,17843,2619,74278,3230,9540,47187,21702,36274,56894,43907,16310,34790,16866,6150,5561,13587,107545,108873,126867,86986,28640,33427,19017,5762,80637,17430,46903,2047,131055,25958,13558,5444,47152,13900,44563,122857,45348,70863,39593,54332,38068,33637,318,40310,143467,18502,24520,11377,62013,28942,27246,28269,83545,17999,59015,90707,30065,15161,34720,1263,37008,2012,6060,98575,92933,5721,299,199555,24578,29223,2985,743,115825,109523,136657,47454,26378,53586,3733,174945,93340,244456,5693,37386,28782,89767,27545,23573,18798,136425,34320,84778,20041,48453,38215,7477,71958,40621,8773,5874,187927,105965,51100,43533,18083,8443,10180,43597,2003,183999,69689,12216,129696,146188,62389,34044,68410,12765,43273,26949,266807,3345,34477,79197,5688,47539,213110,21634,22257,50092,32222,42346,39530,63668,98,134978,74022,5152,59088,174145,37220,9934,9545,118937,5724,87240,19875,15784,40143,23263,87513,181654,285152,37881,263241,4966,43934,10433,186657,6470,74416,225854,25908,142677,246262,32280,6192,75890,45546,143264,135305,29742,47013,77787,11732,126658,8763,37950,21806,57557,113464,89465,108995,164574,23894,22996,23169,15369,23117,17642,130607,40503,36239,280990,44666,9981,40427,147487,26869,168452,32886,32991,46798,240839,15111,70502,65697,88548,44145,28701,48767,31139,206777,35659,181164,166262,14554,171445,31786,66523,76607,17956,6507,31279,90476,116611,167918,6560,1243,115324,80128,41867,55897,187323,37069,32596,189444,145931,13390,105530,65709,26805,6999,55714,41300,22915,68951,22138,21120,22264,10058,19945,33635,56123,99085,10032,5818,6016,46649,57476,35264,94413,112522,262288,93686,83038,14341,23204,28807,66084,77987,6101,126673,7133,38126,5923,122091,170240,97772,46874,215746,43948,41622,3272,55596,8332,146411,251315,13533,8561,81521,115449,48616,175175,2063,186556,3036,134537,75772,29728,82360,22973,186559,86348,89100,38388,82297,45610,2613,87082,9986,177812,57884,23591,47485,42543,33582,44713,74439,257444,252451,31825,35631,38540,33066,5147,13973,4343,51830,70378,22827,26448,95560,36896,241741,48067,203953,298860,61620,20450,3220,67272,6586,107662,100160,108684,6929,57226,4762,7457,1320,40404,77204,99309,62750,208653,59977,44e3,74315,34332,5819,172217,64904,114077,18147,84012,1791,98456,90930,21446,116669,103938,7422,85140,59713,5768,326211,16239,75411,13229,29398,10758,236107,1539,112472,95979,152154,151294,306,21196,38146,10700,6891,84282,109646,56492,40539,6589,119491,51354,30685,140209,136906,29622,73617,49553,70525,51671,166869,139616,74395,37439,49595,45678,11959,33211,86560,52434,9282,62690,112155,130810,5243,108261,99970,265613,72551,80049,6391,33365,90721,66737,69872,87011,1860,9032,112544,60905,37371,89015,140351,19076,850,373531,2802,36725,218795,72062,28990,16550,24614,7815,6187,26336,33373,32162,42791,73555,32062,23386,10244,56392,49442,27076,136262,12412,14883,1134,33675,97153,199281,15608,100152,74072,47942,254301,36451,16026,10687,65067,56708,254030,30290,50490,13864,57941,259331,35588,23485,43486,24869,21620,92971,22072,88645,1048,182050,13343,32452,14825,19509,3325,216938,45740,99716,189082,53740,78245,25609,24311,176777,47340,308354,40669,66085,14102,125339,9225,128709,97207,1271,200933,78439,113451,88975,18324,46521,11819,18570,141756,72512,170020,52754,63550,118515,103073,93330,32736,50499,14722,31600,68452,398867,29316,172786,18417,104924,2606,5670,84818,16288,67106,59580,82929,607401,291,85829,359,15897,35830,50696,65630,52672,22115,356968,29895,40837,231192,34024,38957,26722,406,23335,124952,72068,68804,13268,147101,164740,276569,162596,66943,11569,26654,66358,4777,23229,102127,5848,978,2921,59666,5371,28212,90108,42938,39320,2499,4271,108792,33510,125072,71653,65239,38250,66357,38577,13964,86251,35708,50755,36010,29448,12209,3844,38222,206337,100876,67827,137088,14167,252225,84163,195270,1306,5703,54198,779,46802,22028,51124,86759,70560,113164,35685,162145,45471,34561,422,2611,6464,47486,19223,38246,9191,18331,89942,243642,212364,15893,17518,22617,6409,30046,126182,59716,36560,104428,18846,26592,19458,50793,147333,30826,1388,27647,10922,14495,33545,19269,135828,39727,41601,46931,233379,49169,131130,182112,16276,82381,118209,142445,128310,19672,28740,82907,33436,3118,102206,28723,24819,41937,38854,5157,3881,111491,1142,9776,421673,152241,29309,14961,87854,6054,15424,3796,82656,54996,2108,55367,239450,154525,9643,118103,106041,64601,68549,48707,30266,25772,18740,9462,229669,91798,112152,191327,14493,72828,8175,66636,236474,25817,87351,129027,76653,20422,22983,71240,27846,44661,12399,46158,77704,53101,35032,11072,17300,109294,33638,24408,1895,11241,760,17584,82479,125877,63150,141075,34259,23274,81698,15732,43577,48340,91584,14688,16379,24481,150280,96420,262050,48635,43727,61819,56268,72003,88178,17281,79912,13218,122519,125295,166396,11811,2171,118930,67746,17636,178278,174656,95661,173039,83845,79689,17473,98555,127696,203415,54730,22925,232239,9309,12136,175026,20740,180188,10747,39816,314017,266131,10040,175732,112550,220651,31974,37393,888,23008,86799,4303,64905,148467,75337,251,3284,370102,50264,9835,5438,23655,4481,29851,329,12855,7162,64931,78141,12804,42372,296771,83547,18624,34874,86271,3360,48665,77735,88767,11463,63527,28889,22258,29140,194315,113924,25499,6406,31334,1845,4802,49184,43455,35469,127594,92970,61038,115005,38840,87761,106838,8811,20572,55637,11162,96721,132425,108925,2948,125457,36356,3502,75270,27622,127192,2561,123095,49394,61155,16897,110064,9699,89448,53356,19628,220310,21622,83036,9885,112214,6087,26713,17901,161912,91492,3440,68594,9266,92238,8087,6866,150194,72175,80701,13459,31836,43243,239700,95846,44749,50647,21945,230538,120612,132371,244604,5193,105637,34661,41341,68775,85393,1874,8771,33718,49672,77403,595452,99507,6490,58895,128742,7704,39239,73217,43816,62824,37804,199976,22361,80005,87514,94832,14089,4574,139975,59142,75523,100268,43906,53442,15152,2547,186002,17011,19513,204282,3343,60568,128318,119250,4298,51871,41336,71759,21921,45074,98169,145889,99427,11350,1237,5520,28799,7803,53702,21026,136352,38293,128690,12158,90132,44600,10184,26957,39459,126025,78904,82999,59373,39301,150198,120529,153042,20177,50089,14764,271571,30530,123161,38975,101562,22941,5648,124654,109243,69817,71675,49162,106884,21241,107795,30258,16572,188262,141456,7688,60718,8271,11044,32440,104608,103419,236109,93156,43293,128929,42107,67180,25201,115254,185488,130954,72813,167547,20537,39969,38432,22582,184022,1139,27199,5655,17767,97412,122606,209377,27070,35871,326617,188954,42680,73512,80911,22629,3011,95021,315242,157737,383,41821,41808,19335,27950,15674,25677,110950,35375,76835,59108,57370,35262,16569,160415,37706,78086,32041,49691,137143,9782,172080,50148,77917,6323,10110,69172,17711,21795,59511,76184,135114,31046,132319,59105,157578,20549,80778,57649,158421,65143,4575,72235,21899,10797,92745,34035,106079,80159,4508,78304,25350,75457,46458,32937,25623,47,8531,104751,84953,8138,36508,187199,66310,115274,13253,32461,38536,1916,42007,187160,35055,26325,84394,35963,94216,45590,97782];var W3=15,j3=class{log;peerRouting;routingTable;refreshInterval;refreshQueryTimeout;commonPrefixLengthRefreshedAt;refreshTimeoutId;constructor(e,t){let{peerRouting:n,routingTable:o,refreshInterval:i,refreshQueryTimeout:s,logPrefix:a}=t;this.log=e.logger.forComponent(`${a}:routing-table:refresh`),this.peerRouting=n,this.routingTable=o,this.refreshInterval=i??nP,this.refreshQueryTimeout=s??oP,this.commonPrefixLengthRefreshedAt=[],this.refreshTable=this.refreshTable.bind(this)}async afterStart(){this.log(`refreshing routing table every ${this.refreshInterval}ms`),this.refreshTable(!0)}async stop(){this.refreshTimeoutId!=null&&clearTimeout(this.refreshTimeoutId)}refreshTable(e=!1,t){this.log("refreshing routing table");let n=this._maxCommonPrefix(),o=this._getTrackedCommonPrefixLengthsForRefresh(n);this.log(`max common prefix length ${n}`),this.log(`tracked CPLs [ ${o.map(i=>i.toISOString()).join(", ")} ]`),Promise.all(o.map(async(i,s)=>{try{if(await this._refreshCommonPrefixLength(s,i,e,t),this._numPeersForCpl(n)===0){let a=Math.min(2*(s+1),o.length-1);for(let c=s+1;c<a+1;c++)try{await this._refreshCommonPrefixLength(c,i,e,t)}catch(l){this.log.error("failed to refresh entries with common prefix length %d - %e",c,l)}}}catch(a){this.log.error("failed to refresh entries with common prefix length - %e",a)}})).catch(i=>{this.log.error("failed to refresh table - %e",i)}).then(()=>{this.refreshTimeoutId=setTimeout(this.refreshTable,this.refreshInterval),this.refreshTimeoutId.unref!=null&&this.refreshTimeoutId.unref()}).catch(i=>{this.log.error("failed to set refresh timeout - %e",i)})}async _refreshCommonPrefixLength(e,t,n,o){if(!n&&t.getTime()>Date.now()-this.refreshInterval){this.log("not running refresh for cpl %s as time since last refresh not above interval",e);return}let i=this._generateRandomPeerId(e);this.log("starting refreshing cpl %s with key %p (routing table size was %s)",e,i,this.routingTable.size);let s=ae([o?.signal,AbortSignal.timeout(this.refreshQueryTimeout)]);try{let a=await H3(this.peerRouting.getClosestPeers(i.toMultihash().bytes,{signal:s}));this.log(`found ${a} peers that were close to imaginary peer %p`,i),this.log("finished refreshing cpl %s with key %p (routing table size is now %s)",e,i,this.routingTable.size)}finally{s.clear()}}_getTrackedCommonPrefixLengthsForRefresh(e){e>W3&&(e=W3);let t=[];for(let n=0;n<=e;n++)t[n]=this.commonPrefixLengthRefreshedAt[n]??new Date;return t}_generateRandomPeerId(e){if(this.routingTable.kb==null)throw new Error("Routing table not started");if(this.routingTable.kb.localPeer==null)throw new Error("Local peer not set");let t=kr(2),n=(t[1]<<8)+t[0],o=this._makePeerId(this.routingTable.kb.localPeer.kadId,n,e),i=xe(o);return bt(i)}_makePeerId(e,t,n){if(n>W3)throw new Error(`Cannot generate peer ID for common prefix length greater than ${W3}`);let s=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1)^32768>>n,a=65535<<16-(n+1),c=s&a|t&~a,l=TP[c],u=new ArrayBuffer(34),d=new DataView(u,0,u.byteLength);return d.setUint8(0,ct.code),d.setUint8(1,32),d.setUint32(2,l,!1),new Uint8Array(d.buffer,d.byteOffset,d.byteLength)}_maxCommonPrefix(){let e=0;for(let t of this._prefixLengths())t>e&&(e=t);return e}_numPeersForCpl(e){let t=0;for(let n of this._prefixLengths())n===e&&t++;return t}*_prefixLengths(){if(this.routingTable.kb?.localPeer!=null)for(let{kadId:e}of this.routingTable.kb.toIterable()){let t=To(this.routingTable.kb.localPeer.kadId,e),n=0;for(let o of t)if(o===0)n++;else break;yield n}}};var Y3=class{peerId;providers;peerStore;log;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:add-provider`),this.peerId=e.peerId,this.providers=t.providers,this.peerStore=e.peerStore}async handle(e,t){if(t.key==null||t.key.length===0)throw new he("Missing key");let n;try{n=F.decode(t.key)}catch{throw new he("Invalid CID")}(t.providers==null||t.providers.length===0)&&this.log.error("no providers found in message"),this.log("%p asked us, %p to store provider record for for %c",e,this.peerId,n),await Promise.all(t.providers.map(async o=>{let i=xe(o.id),s=bt(i),a=o.multiaddrs.map(c=>j(c));if(!e.equals(s)){this.log("invalid provider peer %p from %p",o.id,e);return}if(o.multiaddrs.length<1){this.log("no valid addresses for provider %p. Ignore",e);return}this.log.trace("received provider %p for %s (addrs %s)",e,n,a),await this.providers.addProvider(n,s),await this.peerStore.merge(s,{multiaddrs:a})}))}};var X3=class{peerRouting;peerInfoMapper;peerId;addressManager;log;constructor(e,t){let{peerRouting:n,logPrefix:o}=t;this.log=e.logger.forComponent(`${o}:rpc:handlers:find-node`),this.peerId=e.peerId,this.addressManager=e.addressManager,this.peerRouting=n,this.peerInfoMapper=t.peerInfoMapper}async handle(e,t){this.log("incoming request from %p for peers close to %b",e,t.key);try{if(t.key==null)throw new he("Invalid FIND_NODE message received - key was missing");let n=await this.peerRouting.getClosestPeersOffline(t.key,{exclude:[e,this.peerId]});So(this.peerId.toMultihash().bytes,t.key)&&n.push({id:this.peerId,multiaddrs:this.addressManager.getAddresses().map(i=>i.decapsulateCode(421))});let o={type:De.FIND_NODE,clusterLevel:t.clusterLevel,closer:n.map(this.peerInfoMapper).filter(({multiaddrs:i})=>i.length).map(i=>({id:i.id.toMultihash().bytes,multiaddrs:i.multiaddrs.map(s=>s.bytes)})),providers:[]};return o.closer.length===0?this.log("could not find any peers closer to %b for %p",t.key,e):this.log("found %d peers close to %b for %p",o.closer.length,t.key,e),o}catch(n){throw this.log("error during finding peers closer to %b for %p - %e",t.key,e,n),n}}};var Q3=class{peerId;peerRouting;providers;peerStore;peerInfoMapper;log;constructor(e,t){let{peerRouting:n,providers:o,logPrefix:i}=t;this.log=e.logger.forComponent(`${i}:rpc:handlers:get-providers`),this.peerId=e.peerId,this.peerStore=e.peerStore,this.peerRouting=n,this.providers=o,this.peerInfoMapper=t.peerInfoMapper}async handle(e,t){if(t.key==null)throw new he("Invalid GET_PROVIDERS message received - key was missing");let n;try{n=F.decode(t.key)}catch{throw new he("Invalid CID")}this.log("%p asking for providers for %s",e,n);let[o,i]=await Promise.all([Pi(Ct(await this.providers.getProviders(n),async a=>{let c=await this.peerStore.get(a);return{id:c.id,multiaddrs:c.addresses.map(({multiaddr:u})=>u)}})),this.peerRouting.getClosestPeersOffline(t.key)]),s={type:De.GET_PROVIDERS,key:t.key,clusterLevel:t.clusterLevel,closer:i.map(this.peerInfoMapper).filter(({id:a,multiaddrs:c})=>c.length>0).map(a=>({id:a.id.toMultihash().bytes,multiaddrs:a.multiaddrs.map(c=>c.bytes)})),providers:o.map(this.peerInfoMapper).filter(({id:a,multiaddrs:c})=>c.length>0).map(a=>({id:a.id.toMultihash().bytes,multiaddrs:a.multiaddrs.map(c=>c.bytes)}))};return this.log("got %s providers %s closerPeers",s.providers.length,s.closer.length),s}async _getAddresses(e){return[]}};var Z3=class{peerStore;datastore;peerRouting;log;datastorePrefix;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:get-value`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.peerStore=e.peerStore,this.datastore=e.datastore,this.peerRouting=t.peerRouting}async handle(e,t){let n=t.key;if(this.log("%p asked for key %b",e,n),n==null||n.length===0)throw new he("Invalid key");let o={type:De.GET_VALUE,key:n,clusterLevel:t.clusterLevel,closer:[],providers:[]};if(yP(n)){this.log("is public key");let a=wP(n),c;try{let l=await this.peerStore.get(a);if(l.id.publicKey==null)throw new qe("No public key found in key book");c=Ht(l.id.publicKey)}catch(l){if(l.name!=="NotFoundError")throw l}if(c!=null)return this.log("returning found public key"),o.record=new ft(n,c,new Date).serialize(),o}let[i,s]=await Promise.all([this._checkLocalDatastore(n),this.peerRouting.getClosestPeersOffline(n)]);return i!=null&&(this.log("had record for %b in local datastore",n),o.record=i.serialize()),s.length>0&&(this.log("had %s closer peers in routing table",s.length),o.closer=s.map(a=>({id:a.id.toMultihash().bytes,multiaddrs:a.multiaddrs.map(c=>c.bytes)}))),o}async _checkLocalDatastore(e){this.log("checkLocalDatastore looking for %b",e);let t=Ks(this.datastorePrefix,e),n;try{n=await this.datastore.get(t)}catch(i){if(i.name==="NotFoundError")return;throw i}let o=ft.deserialize(n);if(o.timeReceived==null||Date.now()-o.timeReceived.getTime()>v3){await this.datastore.delete(t);return}return o}};var J3=class{log;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:ping`)}async handle(e,t){return this.log("ping from %p",e),t}};var ey=class{components;validators;log;datastorePrefix;constructor(e,t){let{validators:n}=t;this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:put-value`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.validators=n}async handle(e,t){let n=t.key;if(this.log("%p asked us to store value for key %b",e,n),t.record==null)throw this.log.error("empty record from %p",e),new he(`Empty record from: ${e}`);try{let o=ft.deserialize(t.record);await Su(this.validators,o),o.timeReceived=new Date;let i=Ks(this.datastorePrefix,o.key);return await this.components.datastore.put(i,o.serialize().subarray()),this.log("accepted put for key %b under %k",n,i),t}catch(o){throw this.log("failed to accept put for key %b - %e",n,o),o}}};var ty=class{handlers;log;metrics;incomingMessageTimeout;constructor(e,t){this.metrics={operations:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_inbound_rpc_requests_total`),errors:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_inbound_rpc_errors_total`),rpcTime:e.metrics?.registerMetricGroup(`${t.metricsPrefix}_inbound_rpc_time_seconds`,{label:"operation"})},this.log=e.logger.forComponent(`${t.logPrefix}:rpc`),this.incomingMessageTimeout=t.incomingMessageTimeout??1e4,this.handlers={[De.GET_VALUE.toString()]:new Z3(e,t),[De.PUT_VALUE.toString()]:new ey(e,t),[De.FIND_NODE.toString()]:new X3(e,t),[De.ADD_PROVIDER.toString()]:new Y3(e,t),[De.GET_PROVIDERS.toString()]:new Q3(e,t),[De.PING.toString()]:new J3(e,t)}}async handleMessage(e,t){let n=this.handlers[t.type];if(n==null)throw new he(`No handler found for message type: ${t.type}`);try{return this.metrics.operations?.increment({[t.type]:!0}),await n.handle(e,t)}catch(o){throw this.metrics.errors?.increment({[t.type]:!0}),o}}async onIncomingStream(e,t){let n=()=>{e.abort(new Ro)},o=AbortSignal.timeout(this.incomingMessageTimeout);o.addEventListener("abort",n);let i=Xe(e).pb(qs);for(;;){if(e.readStatus!=="readable"){await e.close({signal:o});break}let s=await i.read({signal:o}),a=this.metrics?.rpcTime?.timer(s.type.toString()),c=this.metrics?.rpcTime?.timer(s.type.toString()),l=!1;try{this.log("incoming %s from %p",s.type,t.remotePeer);let u=await this.handleMessage(t.remotePeer,s);u!=null&&await i.write(u,{signal:o})}catch(u){l=!0,c?.(),this.log.error("error handling incoming message - %e",u),e.abort(u);return}finally{l||a?.()}o.removeEventListener("abort",n),o=AbortSignal.timeout(this.incomingMessageTimeout),o.addEventListener("abort",n)}}};var ry=class extends se{log;components;protocol;running;registrarId;constructor(e,t){super();let{protocol:n,logPrefix:o}=t;this.components=e,this.log=e.logger.forComponent(`${o}:topology-listener`),this.running=!1,this.protocol=n}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.registrarId=await this.components.registrar.register(this.protocol,{onConnect:e=>{this.log("observed peer %p with protocol %s",e,this.protocol),this.dispatchEvent(new CustomEvent("peer",{detail:e}))}}))}async stop(){this.running=!1,this.registrarId!=null&&(this.components.registrar.unregister(this.registrarId),this.registrarId=void 0)}};var Pb=class{dht;constructor(e){this.dht=e}async provide(e,t={}){await pr(this.dht.provide(e,t))}async cancelReprovide(e){await this.dht.cancelReprovide(e)}async*findProviders(e,t={}){for await(let n of this.dht.findProviders(e,t))n.name==="PROVIDER"&&(yield*n.providers.map(o=>({...o,routing:"kad-dht"})))}async put(e,t,n){await pr(this.dht.put(e,t,n))}async get(e,t){for await(let n of this.dht.get(e,t))if(n.name==="VALUE")return n.value;throw new qe("Could not find value for key")}},Db=class{dht;constructor(e){this.dht=e}async findPeer(e,t={}){for await(let n of this.dht.findPeer(e,t))if(n.name==="FINAL_PEER")return n.peer;throw new qe("Peer not found")}async*getClosestPeers(e,t={}){for await(let n of this.dht.getClosestPeers(e,t))n.name==="FINAL_PEER"&&(yield n.peer)}},PY=32,DY=64,ny=class extends se{k;a;d;protocol;routingTable;providers;network;peerRouting;validators;selectors;components;log;running;clientMode;queryManager;contentFetching;contentRouting;routingTableRefresh;rpc;topologyListener;querySelf;maxInboundStreams;maxOutboundStreams;dhtContentRouting;dhtPeerRouting;peerInfoMapper;reprovider;onPeerConnectTimeout;constructor(e,t={}){super();let n=t.logPrefix??"libp2p:kad-dht",o=t.datastorePrefix??"/dht",i=t.metricsPrefix??"libp2p_kad_dht",s={queries:e.metrics?.registerMetricGroup(`${i}_operations_total`,{label:"operation"}),errors:e.metrics?.registerCounterGroup(`${i}_operation_errors_total`,{label:"operation"}),queryTime:e.metrics?.registerMetricGroup(`${i}_operation_time_seconds`,{label:"operation"}),errorTime:e.metrics?.registerMetricGroup(`${i}_operation_error_time_seconds`,{label:"operation"})};this.running=!1,this.components=e,this.log=e.logger.forComponent(n),this.k=t.kBucketSize??Bh,this.a=t.alpha??Us,this.d=t.disjointPaths??this.a,this.protocol=t.protocol??jR,this.clientMode=t.clientMode??!0,this.maxInboundStreams=t.maxInboundStreams??PY,this.maxOutboundStreams=t.maxOutboundStreams??DY,this.peerInfoMapper=t.peerInfoMapper??mP,this.onPeerConnectTimeout=t.onPeerConnectTimeout??JR,this.providers=new U3(e,{...t.providers,logPrefix:n,datastorePrefix:o}),this.validators={...pP,...t.validators},this.selectors={...hP,...t.selectors},this.network=new M3(e,{protocol:this.protocol,logPrefix:n,metricsPrefix:i,timeout:t.networkDialTimeout}),this.routingTable=new G3(e,{kBucketSize:this.k,pingOldContactTimeout:t.pingOldContactTimeout,pingOldContactConcurrency:t.pingOldContactConcurrency,pingOldContactMaxQueueSize:t.pingOldContactMaxQueueSize,pingNewContactTimeout:t.pingNewContactTimeout,pingNewContactConcurrency:t.pingNewContactConcurrency,pingNewContactMaxQueueSize:t.pingNewContactMaxQueueSize,protocol:this.protocol,logPrefix:n,metricsPrefix:i,prefixLength:t.prefixLength,splitThreshold:t.kBucketSplitThreshold,network:this.network,routingTableUpdateQueueConcurrency:t.routingTableUpdateQueueConcurrency??Math.max(1,Math.min(this.a*2,16)),routingTableUpdateMaxQueueSize:t.routingTableUpdateMaxQueueSize});let a=me();t.allowQueryWithZeroPeers===!0&&a.resolve(),this.queryManager=new $3(e,{disjointPaths:this.d,alpha:this.a,logPrefix:n,metricsPrefix:i,initialQuerySelfHasRun:a,routingTable:this.routingTable,allowQueryWithZeroPeers:t.allowQueryWithZeroPeers}),this.peerRouting=new F3(e,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,logPrefix:n}),this.contentFetching=new O3(e,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,logPrefix:n,datastorePrefix:o}),this.contentRouting=new B3(e,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,logPrefix:n}),this.routingTableRefresh=new j3(e,{peerRouting:this.peerRouting,routingTable:this.routingTable,logPrefix:n}),this.rpc=new ty(e,{routingTable:this.routingTable,providers:this.providers,peerRouting:this.peerRouting,validators:this.validators,logPrefix:n,metricsPrefix:i,datastorePrefix:o,peerInfoMapper:this.peerInfoMapper}),this.topologyListener=new ry(e,{protocol:this.protocol,logPrefix:n}),this.querySelf=new q3(e,{peerRouting:this.peerRouting,interval:t.querySelfInterval,initialInterval:t.initialQuerySelfInterval,logPrefix:n,initialQuerySelfHasRun:a,operationMetrics:s}),this.reprovider=new V3(e,{...t.reprovide,logPrefix:n,metricsPrefix:i,datastorePrefix:o,contentRouting:this.contentRouting,operationMetrics:s}),this.network.addEventListener("peer",c=>{let l=c.detail;this.onPeerConnect(l).catch(u=>{this.log.error("could not add %p to routing table - %e",l.id,u)}),this.dispatchEvent(new CustomEvent("peer",{detail:l}))}),this.topologyListener.addEventListener("peer",c=>{let l=c.detail;Promise.resolve().then(async()=>{let u=await this.components.peerStore.get(l),d={id:l,multiaddrs:u.addresses.map(({multiaddr:f})=>f),protocols:u.protocols};await this.onPeerConnect(d)}).catch(u=>{this.log.error("could not add %p to routing table - %e",l,u)})}),this.dhtPeerRouting=new Db(this),this.dhtContentRouting=new Pb(this),t.clientMode==null&&e.events.addEventListener("self:peer:update",c=>{this.log("received update of self-peer info"),Promise.resolve().then(async()=>{let l=c.detail.peer.addresses.some(({multiaddr:d})=>!wt(d)&&!Kt.exactMatch(d)),u=this.getMode();l&&u==="client"?await this.setMode("server"):u==="server"&&!l&&await this.setMode("client")}).catch(l=>{this.log.error("error setting dht server mode - %e",l)})}),this.get=Sc(this.get.bind(this),s,"GET_VALUE"),this.findProviders=Sc(this.findProviders.bind(this),s,"FIND_PROVIDERS"),this.findPeer=Sc(this.findPeer.bind(this),s,"FIND_PEER"),this.getClosestPeers=Sc(this.getClosestPeers.bind(this),s,"GET_CLOSEST_PEERS"),this.provide=Sc(this.provide.bind(this),s,"PROVIDE"),this.put=Sc(this.put.bind(this),s,"PUT_VALUE")}[Symbol.toStringTag]="@libp2p/kad-dht";[be]=["@libp2p/content-routing","@libp2p/peer-routing","@libp2p/peer-discovery","@libp2p/kad-dht"];[Zr]=["@libp2p/identify","@libp2p/ping"];get[si](){return this.dhtContentRouting}get[ci](){return this.dhtPeerRouting}get[aa](){return this}async onPeerConnect(e){if(this.log.trace("peer %p connected",e.id,e.multiaddrs),e=this.peerInfoMapper(e),e.multiaddrs.length===0){this.log.trace("ignoring %p as there were no valid addresses in %s after filtering",e.id,e.multiaddrs.map(t=>t.toString()));return}this.routingTable.queueRoutingTableUpdate(e.id,{activeTimeout:this.onPeerConnectTimeout})}isStarted(){return this.running}getMode(){return this.clientMode?"client":"server"}async setMode(e,t){if(e===this.getMode()&&t?.force!==!0){this.log("already in %s mode",e);return}if(await this.components.registrar.unhandle(this.protocol,t),e===this.getMode()&&t?.force!==!0){this.log("already in %s mode",e);return}e==="client"?(this.log("enabling client mode while in %s mode",this.getMode()),this.clientMode=!0):(this.log("enabling server mode while in %s mode",this.getMode()),this.clientMode=!1,await this.components.registrar.handle(this.protocol,this.rpc.onIncomingStream.bind(this.rpc),{signal:t?.signal,maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}))}async start(){this.running||(this.running=!0,await this.setMode(this.clientMode?"client":"server",{force:!0}),await Rt(this.routingTable,this.queryManager,this.network,this.topologyListener,this.routingTableRefresh,this.reprovider),await Rt(this.querySelf))}async stop(){this.running=!1,await Ut(this.querySelf,this.queryManager,this.network,this.routingTable,this.routingTableRefresh,this.topologyListener,this.reprovider)}async*put(e,t,n={}){yield*this.contentFetching.put(e,t,n)}async*get(e,t={}){yield*this.contentFetching.get(e,t)}async*provide(e,t={}){yield*this.contentRouting.provide(e,this.components.addressManager.getAddresses(),t)}async cancelReprovide(e,t){await this.providers.removeProvider(e,this.components.peerId,t)}async*findProviders(e,t={}){yield*this.contentRouting.findProviders(e,t)}async*findPeer(e,t={}){yield*this.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t={}){yield*this.peerRouting.getClosestPeers(e,t)}async refreshRoutingTable(e){this.routingTableRefresh.refreshTable(!0,e)}};var _P;(function(r){r[r.SEND_QUERY=0]="SEND_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADD_PEER=6]="ADD_PEER",r[r.DIAL_PEER=7]="DIAL_PEER",r[r.PATH_ENDED=8]="PATH_ENDED"})(_P||(_P={}));function CP(r={}){return e=>new ny(e,r)}function Ws(r=0){return new Uint8Array(r)}function kP(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var IP=kP("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Lb=kP("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=Ws(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),NY={utf8:IP,"utf-8":IP,hex:oe.base16,latin1:Lb,ascii:Lb,binary:Lb,...oe},oy=NY;function Nb(r,e="utf8"){let t=oy[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function iy(r,e="utf8"){let t=oy[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Le;(function(r){r[r.NEW_STREAM=0]="NEW_STREAM",r[r.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",r[r.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",r[r.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",r[r.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",r[r.RESET_RECEIVER=5]="RESET_RECEIVER",r[r.RESET_INITIATOR=6]="RESET_INITIATOR"})(Le||(Le={}));var Mh=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),Ob=Object.freeze({NEW_STREAM:Le.NEW_STREAM,MESSAGE:Le.MESSAGE_INITIATOR,CLOSE:Le.CLOSE_INITIATOR,RESET:Le.RESET_INITIATOR}),RP=Object.freeze({MESSAGE:Le.MESSAGE_RECEIVER,CLOSE:Le.CLOSE_RECEIVER,RESET:Le.RESET_RECEIVER});var Fh=1<<20,Bb=4<<20,sy=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Fh,t=Bb){this._buffer=new G,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(e==null||e.length===0)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new he("Unprocessed message queue size too large!");let t=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(l){if(l.name==="InvalidMessageError")throw l;break}let{id:n,type:o,length:i,offset:s}=this._headerInfo;if(this._buffer.length-s<i)break;let c={id:n,type:o};(o===Le.NEW_STREAM||o===Le.MESSAGE_INITIATOR||o===Le.MESSAGE_RECEIVER)&&(c.data=this._buffer.sublist(s,s+i)),t.push(c),this._buffer.consume(s+i),this._headerInfo=null}return t}_decodeHeader(e){let{value:t,offset:n}=DP(e),{value:o,offset:i}=DP(e,n),s=t&7;if(Mh[s]==null)throw new Error(`Invalid type received: ${s}`);if(o>this._maxMessageSize)throw new he("Message size too large");return{id:t>>3,type:s,offset:n+i,length:o}}},OY=128,PP=127;function DP(r,e=0){let t=0,n=0,o=e,i,s=r.length;do{if(o>=s||n>49)throw e=0,new RangeError("Could not decode varint");i=r.get(o++),t+=n<28?(i&PP)<<n:(i&PP)*Math.pow(2,n),n+=7}while(i>=OY);return e=o-e,{value:t,offset:e}}var Mb=10*1024,Fb=class{_pool;_poolOffset;constructor(){this._pool=Ws(Mb),this._poolOffset=0}write(e,t){let n=this._pool,o=this._poolOffset;ur(e.id<<3|e.type,n,o),o+=ye(e.id<<3|e.type),(e.type===Le.NEW_STREAM||e.type===Le.MESSAGE_INITIATOR||e.type===Le.MESSAGE_RECEIVER)&&e.data!=null?(ur(e.data.length,n,o),o+=ye(e.data.length)):(ur(0,n,o),o+=ye(0));let i=n.subarray(this._poolOffset,o);Mb-o<100?(this._pool=Ws(Mb),this._poolOffset=0):this._poolOffset=o,t.append(i),(e.type===Le.NEW_STREAM||e.type===Le.MESSAGE_INITIATOR||e.type===Le.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},BY=new Fb;function Uh(r){let e=new G;return BY.write(r,e),e}var Ub=class extends ys{streamId;types;maxDataSize;muxer;constructor(e){super(e),this.types=e.direction==="outbound"?Ob:RP,this.maxDataSize=e.maxDataSize,this.muxer=e.muxer,this.streamId=parseInt(this.id.substring(1)),e.direction==="outbound"&&queueMicrotask(()=>{this.muxer.send(Uh({id:this.streamId,type:Ob.NEW_STREAM,data:new G(Nb(this.id))}))})}sendData(e){let t=new G,n=e.byteLength;for(;e.byteLength>0;){let o=Math.min(e.byteLength,this.maxDataSize),i=e.sublist(0,o);e=e.sublist(o),t.append(Uh({id:this.streamId,type:this.types.MESSAGE,data:i}))}return{sentBytes:n,canSendMore:this.muxer.send(t)}}sendReset(){return this.muxer.send(Uh({id:this.streamId,type:this.types.RESET}))}async sendCloseWrite(e){this.muxer.send(Uh({id:this.streamId,type:this.types.CLOSE})),e?.signal?.throwIfAborted()}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}};function LP(r){let{id:e,muxer:t,direction:n,maxMsgSize:o=Fh}=r;return new Ub({...r,id:n==="outbound"?`i${e}`:`r${e}`,direction:n,maxDataSize:o,muxer:t,log:r.log.newScope(`${n}:${e}`),protocol:""})}var MY=5;function FY(r){let e={...r,type:`${Mh[r.type]} (${r.type})`};return r.type===Le.NEW_STREAM&&(e.data=iy(r.data.subarray())),(r.type===Le.MESSAGE_INITIATOR||r.type===Le.MESSAGE_RECEIVER)&&(e.data=iy(r.data.subarray(),"base16")),e}var ay=class extends gs{_streamId;rateLimiter;maxMessageSize;maxUnprocessedMessageQueueSize;decoder;constructor(e,t){super(e,{...t,protocol:"/mplex/6.7.0",name:"mplex"}),this._streamId=0,this.maxMessageSize=t.maxMessageSize??Fh,this.maxUnprocessedMessageQueueSize=t.maxUnprocessedMessageQueueSize??Bb,this.decoder=new sy(this.maxMessageSize,this.maxUnprocessedMessageQueueSize),this.rateLimiter=new Bl({points:t.disconnectThreshold??MY,duration:1})}onData(e){for(let t of this.decoder.write(e))this.handleMessage(t)}onCreateStream(e){if(this.status!=="open")throw new Xn("Muxer already closed");let t=this._streamId++;return this._newStream(t,"outbound",e)}_newStream(e,t,n){return this.log("new %s stream %s",t,e),LP({...n,id:e,direction:t,maxMsgSize:this.maxMessageSize,log:this.log,muxer:this})}handleMessage(e){if(this.log.enabled&&this.log.trace("incoming message",FY(e)),e.type===Le.NEW_STREAM){try{this.rateLimiter.consume("new-stream",1)}catch{this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}let o=this._newStream(e.id,"inbound",this.streamOptions);this.onRemoteStream(o);return}let t=`${(e.type&1)===1?"i":"r"}${e.id}`,n=this.streams.find(o=>o.id===t);if(n==null){this.log("missing stream %s for message type %s",t,Mh[e.type]);try{this.rateLimiter.consume("missing-stream",1)}catch{this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(new Error("Too many messages for missing streams"));return}return}try{switch(e.type){case Le.MESSAGE_INITIATOR:case Le.MESSAGE_RECEIVER:n.onData(e.data);break;case Le.CLOSE_INITIATOR:case Le.CLOSE_RECEIVER:n.onRemoteCloseWrite();break;case Le.RESET_INITIATOR:case Le.RESET_RECEIVER:n.onRemoteReset();break;default:this.log("unknown message type")}}catch(o){this.log.error("error while processing message - %e",o),n.abort(o)}}};var $b=class{protocol="/mplex/6.7.0";_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@libp2p/mplex";[be]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new ay(e,{...this._init})}};function NP(r={}){return()=>new $b(r)}function OP(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 BP="1.0.0",MP="ping",FP="ipfs";var cy=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(e,t={}){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??FP}/${MP}/${BP}`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[be]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handlePing,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async handlePing(e,t){let n=e.log.newScope("ping");n.trace("ping from %p",t.remotePeer);let o=AbortSignal.timeout(this.timeout);o.addEventListener("abort",()=>{e.abort(new Ro("Ping timed out"))});let i=Date.now();for await(let s of e){if(e.status!=="open"){n("stream status changed to %s",e.status);break}e.send(s)||(n("waiting for stream to drain"),await ke(e,"drain",{rejectionEvents:["close"],signal:o}),n("stream drained"))}n("ping from %p complete in %dms",t.remotePeer,Date.now()-i),await e.close({signal:o})}async ping(e,t={}){let n=kr(32),o=await this.components.connectionManager.openStream(e,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...t}),i=o.log.newScope("ping");try{let s=Date.now(),a=Promise.withResolvers(),c=new G,l=u=>{if(c.append(u.data),c.byteLength===32){o.removeEventListener("message",l);let d=Date.now()-s;Promise.all([o.closeRead(t)]).then(()=>{if(OP(n,c.subarray()))a.resolve(d);else throw new ia(`Received wrong ping ack after ${d}ms`)}).catch(f=>{o.abort(f),a.reject(f)})}};return o.addEventListener("message",l),o.send(n),await o.close(t),await Me(a.promise,t.signal)}catch(s){throw i.error("error while pinging %o - %e",e,s),o?.abort(s),s}finally{o?.close()}}};function $P(r={}){return e=>new cy(e,r)}var xr;(function(r){let e;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(e=r.Flag||(r.Flag={}));let t;(function(a){a[a.FIN=0]="FIN",a[a.STOP_SENDING=1]="STOP_SENDING",a[a.RESET=2]="RESET",a[a.FIN_ACK=3]="FIN_ACK"})(t||(t={})),(function(a){a.codec=()=>Ye(t)})(e=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=re((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),r.Flag.codec().encode(a.flag,c)),a.message!=null&&(c.uint32(18),c.bytes(a.message)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.flag=r.Flag.codec().decode(a);break}case 2:{u.message=a.bytes();break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.flag`,value:r.Flag.codec().decode(a)};break}case 2:{yield{field:`${l}.message`,value:a.bytes()};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return ee(a,r.codec())}r.encode=o;function i(a,c){return J(a,r.codec(),c)}r.decode=i;function s(a,c){return te(a,r.codec(),c)}r.stream=s})(xr||(xr={}));var HP=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Hb=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),qP="libp2p+webrtc+v1/",VP=2*1024*1024,Au=16*1024;function qY(r=Au){let e=ye(r-ye(r)),t=1+ye(Object.keys(xr.Flag).length-1),n=1,o=r-e-t-n,i=ye(o);return e+t+n+i}var KP=qY();var zP=1e4,qb="/webrtc",$h="/webrtc-signaling/0.0.1";function VY(r){return r.buffer instanceof ArrayBuffer}function GP(r){return VY(r)?r:r.slice()}var Vb=class extends ys{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??Au)-KP}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=Nt(),this.maxBufferedAmount=e.maxBufferedAmount??VP,this.finAckTimeout=e.finAckTimeout??zP,this.channel.onclose=()=>{this.log.trace("received datachannel close event"),this.onRemoteCloseWrite(),this.onTransportClosed()},this.channel.onerror=n=>{let o=n.error;this.log.trace("received datachannel error event - %e",o),this.abort(o)},this.channel.onmessage=async n=>{this.log("incoming message %d bytes",n.data.byteLength);let{data:o}=n;o===null||o.byteLength===0||this.incomingData.push(new Uint8Array(o,0,o.byteLength))},this.channel.bufferedAmountLowThreshold=0,this.channel.onbufferedamountlow=()=>{this.writableNeedsDrain&&this.safeDispatchEvent("drain")},Promise.resolve().then(async()=>{for await(let n of za(this.incomingData))this.processIncomingProtobuf(n)}).catch(n=>{this.log.error("error processing incoming data channel messages - %e",n)});let t=()=>{this.channel.readyState==="open"&&(this.log.trace("stream closed, closing underlying datachannel"),this.channel.close())};this.addEventListener("close",t),this.channel.readyState!=="open"&&(this.log('channel ready state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),ke(this.channel,"open",{rejectionEvents:["close","error"]}).then(()=>{this.log('channel ready state is now "%s", dispatching drain',this.channel.readyState),this.safeDispatchEvent("drain")}).catch(n=>{this.abort(n.error??n)}))}sendNewStream(){}_sendMessage(e){if(this.channel.readyState!=="open")throw new Io(`Invalid datachannel state - ${this.channel.readyState}`);this.log.trace('sending message, channel state "%s"',this.channel.readyState);try{for(let t of e)this.channel.send(GP(t))}catch(t){this.log.error("error sending datachannel message - %e",t),this.abort(t)}}sendData(e){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(Si.single(xr.encode({message:e.subarray()}))),{sentBytes:e.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(e){try{this.log.error("sending reset - %e",e),this._sendFlag(xr.Flag.RESET),this.receivedFinAck?.reject(e)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(e){this._sendFlag(xr.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let t=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[ke(this.channel,"close",{signal:t}),ke(this.channel,"error",{signal:t})];await Promise.any([Me(this.receivedFinAck.promise,t),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(xr.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let t=xr.decode(e);t.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new G(t.message)),t.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',t.flag,this.writeStatus,this.readStatus),t.flag===xr.Flag.FIN&&(this._sendFlag(xr.Flag.FIN_ACK),this.onRemoteCloseWrite()),t.flag===xr.Flag.RESET&&(this.receivedFinAck?.reject(new Hc("The stream was reset")),this.onRemoteReset()),t.flag===xr.Flag.STOP_SENDING&&this.onRemoteCloseRead(),t.flag===xr.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(e){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',e.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",e.toString());let t=xr.encode({flag:e}),n=Si.single(t);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",e.toString(),o)}return!1}sendPause(){}sendResume(){}};function Hh(r){let{channel:e,direction:t,isHandshake:n}=r;return new Vb({...r,id:`${e.id}`,log:r.log.newScope(`${n===!0?"handshake":t}:${e.id}`),protocol:""})}var js=class{protocol;peerConnection;metrics;dataChannelOptions;earlyDataChannels;constructor(e){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??qb,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(e){this.earlyDataChannels.push(e.channel)}createStreamMuxer(e){return this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new Kb(e,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},Kb=class extends gs{peerConnection;dataChannelOptions;constructor(e,t){super(e,{...t,name:"muxer"}),this.peerConnection=t.peerConnection,this.protocol=t.protocol??qb,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){t.earlyDataChannels.forEach(n=>{n.close()});return}t.earlyDataChannels.forEach(n=>{this.onDataChannel(n)})})}onDataChannel(e){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",e.id,e.protocol,e.readyState),e.label==="init"){this.log.trace("closing init channel %d",e.id),e.close();return}let t=Hh({...this.streamOptions,...this.dataChannelOptions,channel:e,direction:"inbound",log:this.log});this.onRemoteStream(t)}async onCreateStream(e){let t=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",t.id,e?.protocol),Hh({...e,...this.dataChannelOptions,channel:t,direction:"outbound",log:this.log})}onData(){}};var zb=class extends ps{peerConnection;constructor(e){super(e),this.peerConnection=e.peerConnection;let t=e.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change %s initial state %s",this.peerConnection.connectionState,t),(this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.onTransportClosed(),this.peerConnection.close())}}sendData(e){return{sentBytes:e.byteLength,canSendMore:!0}}async sendClose(e){this.peerConnection.close(),e?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},qh=r=>new zb(r);async function Gb(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??HP.map(e=>({urls:[e]})),r}var WP=(r=32)=>qP+[...Array(r)].map(()=>Hb.at(Math.floor(Math.random()*Hb.length))).join("");var ly=globalThis.RTCPeerConnection,uy=globalThis.RTCSessionDescription,jP=globalThis.RTCIceCandidate;var Ys=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},zn=class extends Ys{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var dy=class extends Ys{constructor(e,t){super(`Invalid fingerprint "${e}" within ${t}`),this.name="WebRTC/InvalidFingerprintError"}};var fy=class extends Ys{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},hy=class extends Ys{constructor(e){super(`unsupported hash algorithm code: ${e} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Wr;(function(r){let e;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.SDP_OFFER=0]="SDP_OFFER",a[a.SDP_ANSWER=1]="SDP_ANSWER",a[a.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(t||(t={})),(function(a){a.codec=()=>Ye(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=re((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.data!=null&&(c.uint32(18),c.string(a.data)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.data=a.string();break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield{field:`${l}.data`,value:a.string()};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return ee(a,r.codec())}r.encode=o;function i(a,c){return J(a,r.codec(),c)}r.decode=i;function s(a,c){return te(a,r.codec(),c)}r.stream=s})(Wr||(Wr={}));var py=async(r,e,t)=>{try{let n=Promise.withResolvers();for(KY(r,n);;){let o=await Promise.race([n.promise,e.read({signal:t.signal})]);if(o==null){t.signal?.throwIfAborted();break}if(o.type!==Wr.Type.ICE_CANDIDATE)throw new he("ICE candidate message expected");let i=JSON.parse(o.data??"null");if(i===""||i===null){t.onProgress?.(new k("webrtc:end-of-ice-candidates")),t.log.trace("end-of-candidates received");continue}let s=new jP(i);t.log.trace("%s received new ICE candidate %o",t.direction,i);try{t.onProgress?.(new k("webrtc:add-ice-candidate",s.candidate)),await r.addIceCandidate(s)}catch(a){t.log.error("%s bad candidate received %o - %e",t.direction,i,a)}}}catch(n){if(t.log.error("%s error parsing ICE candidate - %e",t.direction,n),t.signal?.aborted===!0&&r.connectionState!=="connected")throw n}};function KY(r,e){if(r.connectionState==="connected"){e.resolve();return}r.onconnectionstatechange=t=>{switch(r.connectionState){case"connected":e.resolve();break;case"failed":case"closed":e.reject(new $c(`RTCPeerConnection connection state became "${r.connectionState}"`));break;default:break}}}function my(r){let e;for(let t of r.getComponents())t.name==="p2p"&&(e=Ee(t.value??""));if(e==null)throw new ko("Remote peerId must be present in multiaddr");return e}async function YP({rtcConfiguration:r,dataChannel:e,signal:t,metrics:n,multiaddr:o,connectionManager:i,transportManager:s,log:a,logger:c,onProgress:l}){let{circuitAddress:u,targetPeer:d}=XP(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",u);let f=i.getConnections(d),h;f.length===0?(l?.(new k("webrtc:dial-relay")),h=await s.dial(u,{signal:t,onProgress:l})):(l?.(new k("webrtc:reuse-relay-connection")),h=f[0]),l?.(new k("webrtc:open-signaling-stream"));let p=await h.newStream($h,{signal:t,runOnLimitedConnection:!0}),y=Xe(p).pb(Wr),g=new ly(r);g.addEventListener("connectionstatechange",()=>{g.connectionState==="closed"&&g.close()});let m=new js({peerConnection:g,dataChannelOptions:e});try{let b=g.createDataChannel("init");g.onicecandidate=({candidate:O})=>{if(g.connectionState==="connected"){a.trace("ignore new ice candidate as peer connection is already connected");return}if(O==null||O?.candidate===""){a.trace("initiator detected end of ICE candidates");return}let U=JSON.stringify(O?.toJSON()??null);a.trace("initiator sending ICE candidate %o",O),y.write({type:Wr.Type.ICE_CANDIDATE,data:U},{signal:t}).catch(C=>{a.error("error sending ICE candidate - %e",C)})},g.onicecandidateerror=O=>{a.error("initiator ICE candidate error",O)};let _=await g.createOffer().catch(O=>{throw a.error("could not execute createOffer - %e",O),new zn("Failed to set createOffer")});a.trace("initiator send SDP offer %s",_.sdp),l?.(new k("webrtc:send-sdp-offer")),await y.write({type:Wr.Type.SDP_OFFER,data:_.sdp},{signal:t}),await g.setLocalDescription(_).catch(O=>{throw a.error("could not execute setLocalDescription - %e",O),new zn("Failed to set localDescription")}),l?.(new k("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let R=await y.read({signal:t});if(R.type!==Wr.Type.SDP_ANSWER)throw new zn("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",R.data);let D=new uy({type:"answer",sdp:R.data});return await g.setRemoteDescription(D).catch(O=>{throw a.error("could not execute setRemoteDescription - %e",O),new zn("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new k("webrtc:read-ice-candidates")),await py(g,y,{direction:"initiator",signal:t,log:a,onProgress:l}),a.trace("initiator connected"),b.readyState!=="open"&&(a.trace("wait for init channel to open"),await ke(b,"open",{signal:t})),a.trace("closing init channel"),b.close(),a.trace("waiting for init channel to close"),await ke(b,"close",{signal:t}),l?.(new k("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await p.close({signal:t}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:g,muxerFactory:m}}catch(b){throw a.error("outgoing signaling error - %e",b),g.close(),p.abort(b),b}finally{g.onicecandidate=null,g.onicecandidateerror=null}}var QP=Be(Tl.matchers[0],Oe(290)),gy=class r extends se{transportManager;shutdownController;events;constructor(e,t){super(),this.transportManager=e.transportManager,this.events=e.events,this.shutdownController=t.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(e){e.detail.getAddrs().filter(n=>QP.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(e=>!(e instanceof r)).map(e=>e.getAddrs().filter(t=>QP.exactMatch(t)).map(t=>t.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function ZP(r,e,{peerConnection:t,signal:n,log:o}){o.trace("new inbound signaling stream");let i=Xe(r).pb(Wr);try{t.onicecandidate=({candidate:d})=>{if(t.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(d==null||d?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let f=JSON.stringify(d?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),i.write({type:Wr.Type.ICE_CANDIDATE,data:f},{signal:n}).catch(h=>{o.error("error sending ICE candidate - %e",h)})},o.trace("recipient read SDP offer");let c=await i.read({signal:n});if(c.type!==Wr.Type.SDP_OFFER)throw new zn(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let l=new uy({type:"offer",sdp:c.data});await t.setRemoteDescription(l).catch(d=>{throw o.error("could not execute setRemoteDescription - %e",d),new zn("Failed to set remoteDescription")});let u=await t.createAnswer().catch(d=>{throw o.error("could not execute createAnswer - %e",d),new zn("Failed to create answer")});o.trace("recipient send SDP answer %s",u.sdp),await i.write({type:Wr.Type.SDP_ANSWER,data:u.sdp},{signal:n}),await t.setLocalDescription(u).catch(d=>{throw o.error("could not execute setLocalDescription - %e",d),new zn("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await py(t,i,{direction:"recipient",signal:n,log:o})}catch(c){if(t.connectionState!=="connected")throw o.error("error while handling signaling stream from peer %a - %e",e.remoteAddr,c),t.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",e.remoteAddr,c)}let s=my(e.remoteAddr),a=j(`/webrtc/p2p/${s}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:s}}var yy=class{components;init;log;_started=!1;metrics;shutdownController;constructor(e,t={}){this.components=e,this.init=t,this.log=e.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[Xi]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[be]=["@libp2p/transport"];[Zr]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle($h,(e,t)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(e,t,n).catch(o=>{this.log.error("failed to handle incoming connect from %p - %e",t.remotePeer,o)}).finally(()=>{n.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle($h),this._started=!1}createListener(e){return new gy(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Ua.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,t){this.log.trace("dialing address: %a",e);let{remoteAddress:n,peerConnection:o,muxerFactory:i}=await YP({rtcConfiguration:await Gb(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:t.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:t.onProgress}),s=qh({peerConnection:o,remoteAddr:n,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")}),a=await t.upgrader.upgradeOutbound(s,{skipProtection:!0,skipEncryption:!0,remotePeer:my(e),muxerFactory:i,onProgress:t.onProgress,signal:t.signal});return this._closeOnShutdown(o,s),a}async _onProtocol(e,t,n){let o=new ly(await Gb(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let i=new js({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:s,remotePeer:a}=await ZP(e,t,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=qh({peerConnection:o,remoteAddr:s,metrics:this.metrics?.listenerEvents,direction:"inbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")});await this.components.upgrader.upgradeInbound(c,{skipEncryption:!0,skipProtection:!0,remotePeer:a,muxerFactory:i,signal:n}),this._closeOnShutdown(o,c)}catch(s){throw this.log.error("incoming signaling error - %e",s),o.close(),e.abort(s),s}}_closeOnShutdown(e,t){let n=()=>{t.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function XP(r){let e=r.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new E("Destination peer id was missing");return{circuitAddress:j(r.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:Ee(e)}}function wy(r=0){return new Uint8Array(r)}function zY(r){return r?.buffer instanceof ArrayBuffer}function JP(r){if(zY(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Wb(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=wy(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return JP(t)}function tD(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var eD=tD("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),jb=tD("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=wy(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),GY={utf8:eD,"utf-8":eD,hex:oe.base16,latin1:jb,ascii:jb,binary:jb,...oe},rD=GY;function Yb(r,e="utf8"){let t=rD[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Xb=Object.values(oe).map(r=>r.decoder).reduce((r,e)=>r.or(e)),WY=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function nD(r){return r?.match(WY)?.groups?.fingerprint}function Qb(r){let t=r.getComponents().find(n=>n.code===466)?.value;if(t===void 0||t==="")throw new E(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return t}function jY(r){return Ve.decode(Xb.decode(r))}function YY(r){let e=jY(Qb(r)),t=XY(e.code),n=e.digest.reduce((i,s)=>i+s.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new dy(n,r.toString());return`${t} ${o.join(":").toUpperCase()}`}function oD(r){let e=r.split(":").map(o=>parseInt(o,16)),t=Uint8Array.from(e),n=Cr(ct.code,t);return j(`/certhash/${ud.encode(n.bytes)}`)}function XY(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new hy(r)}}function iD(r,e){let{host:t,port:n,type:o}=ie(r);if(o!=="ip4"&&o!=="ip6")throw new E(`Multiaddr ${r} was not an IPv4 or IPv6 address`);let i=YY(r);return{type:"answer",sdp:`v=0
65
+ `))}var Hj=["BINARY","TEXT","CONTINUATION"],qj=10485760;var Vj="/http/1.1",s3=class extends se{binaryType="arraybuffer";bufferedAmount=0;extensions="";protocol="";readyState;url;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;_onclose;_onerror;_onmessage;_onopen;sentClose;isClient;buffer;maxMessageSize;_url;closeController;constructor(e,t={}){super(),this.readyState=this.CONNECTING,this.url=e.pathname,this.sentClose=!1,this.isClient=t.isClient??!0,this.buffer=new G,this.closeController=new AbortController,this.maxMessageSize=t.maxMessageSize??qj}send(e){if(this.readyState!==this.OPEN)throw new Error("WebSocket was not open");let t=ER(e);ms(t)?t.then(n=>{this._send("BINARY",n)}).catch(n=>{this._errored(n)}):this._send("BINARY",t)}_send(e,t){if(this.readyState!==this.OPEN)return;let n=xR(e,t,this.isClient),o=n.byteLength;this.bufferedAmount+=o,this._write(n,i=>{this.bufferedAmount-=o,i!=null&&this._errored(i)})}close(e,t){if(this.readyState!==this.OPEN)throw new Error("WebSocket was not open");this.readyState=this.CLOSING,this.sentClose=!0,this._send("CONNECTION_CLOSE")}_errored(e){this.readyState=this.CLOSED,this.dispatchEvent(new i3(e))}set onclose(e){this._onclose=e,this.addEventListener("close",e)}get onclose(){return this._onclose??null}set onerror(e){this._onerror=e,this.addEventListener("error",e)}get onerror(){return this._onerror??null}set onmessage(e){this._onmessage=e,this.addEventListener("message",e)}get onmessage(){return this._onmessage??null}set onopen(e){this._onopen=e,this.addEventListener("open",e)}get onopen(){return this._onopen??null}_push(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxMessageSize){this.close(Ch.MESSAGE_TOO_BIG,"Max message size exceeded");return}for(;;){let t=wR(this.buffer);if(t==null)break;if(Hj.includes(t.type)&&t.data!=null){let n;this.binaryType==="blob"?n=new Blob([t.data]):t.data.byteOffset===0&&t.data.byteLength===t.data.buffer.byteLength?n=t.data.buffer:(n=new ArrayBuffer(t.data.byteLength),new Uint8Array(n,0,n.byteLength).set(t.data)),this.dispatchEvent(new MessageEvent("message",{data:n,origin:this._url?.hostname}))}t.type==="PING"&&this._send("PONG",t.data),t.type==="CONNECTION_CLOSE"&&(this.sentClose||this.close(),this.closeController.abort(),this._close(void 0,()=>{this.readyState=this.CLOSED,this.dispatchEvent(new _h("close"))}))}}_remoteClosed(e){this.readyState=this.CLOSING,this._close(e,()=>{this.readyState=this.CLOSED,this.dispatchEvent(new _h("close"))})}};var Ih=class extends s3{writer;writable;constructor(e,t,n={}){if(super(new URL(e.url),{...n,isClient:!1}),e.body==null)throw new E("Request body cannot be null");this.readyState=this.OPEN,this.writable=t,this.writer=t.getWriter();let o=e.body.getReader();Promise.resolve().then(async()=>{for(this.dispatchEvent(new Event("open"));;){let{value:i,done:s}=await o.read();if(i!=null&&this._push(i),s){this._remoteClosed();break}}}).catch(i=>{this._errored(i)})}_write(e,t){this.writer?.write(e).then(()=>{t()},n=>{t(n)})}_close(e,t){e!=null?this.writable.abort(e).then(()=>{t()},()=>{t()}):this.writable.close().then(()=>{t()},()=>{t()})}},kh=class extends s3{stream;handshakeTimeout;drainTimeout;constructor(e,t,n,o){super(t,{...o,isClient:!0}),this.handshakeTimeout=o.handshakeTimeout??1e4,this.drainTimeout=o.drainTimeout??1e4,Promise.resolve().then(async()=>{let i=AbortSignal.timeout(this.handshakeTimeout);this.stream=await n.openStream(e,Vj,{...o,signal:i});for await(let a of SR(t,o.protocols,ti(o)))this.stream.send(a)||await this.stream.onDrain({signal:i});let s=await vR(this.stream,{signal:i});if(s.status!==101)throw new Error("Invalid WebSocket handshake - response status "+s.status);await o.onHandshakeResponse?.(s,{signal:i}),this.protocol=s.headers.get("Sec-WebSocket-Protocol")??"",this.readyState=this.OPEN,this.dispatchEvent(new Event("open"));for await(let a of this.stream)this._push(a)}).catch(i=>{this._errored(i)})}_write(e,t){if(this.stream==null){t(new Error("WebSocket was not open"));return}this.stream.send(e)?t():this.stream.onDrain({signal:AbortSignal.timeout(this.drainTimeout)}).then(()=>{t()},n=>{t(n)})}_close(e,t){if(this.stream==null){t();return}if(e!=null){this.stream.abort(e),t();return}this.stream.close().catch(n=>{this.stream?.abort(n)}).finally(()=>{t()})}};var Rh="/http/1.1";var a3=Symbol.for("@libp2p/http/websocket-handler");var RR=Yt(IR(),1),l3=class{log;cookies;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:http:cookies"),this.cookies=new Map}async prepareRequest(e,t){if((t.credentials??"same-origin")==="omit")return;let o=t.headers.get("origin");if(o==null||o==="null")return;let i=Ah(e,t.headers),s=(this.cookies.get(i.hostname)??[]).filter(a=>!(a.expires!=null&&a.expires<Date.now()||a.path!=null&&!i.pathname.startsWith(a.path))).map(a=>`${a.name}=${a.value}`).join("; ");s.length>0&&t.headers.set("cookie",s)}async processResponse(e,t,n){if((t.credentials??"same-origin")==="omit"){kR(n);return}let i=t.headers.get("origin");if(i==null||i==="null")return;let s=Ah(e,t.headers);for(let a of n.headers.getSetCookie()){let c=[...this.cookies.get(s.hostname)??[],...Zj(RR.default.parse(a))];this.cookies.set(s.hostname,c)}kR(n)}};function kR(r){return r.headers.has("set-cookie")&&r.headers.delete("set-cookie"),r}function Zj(r){let e={},t=[];return Object.entries(r).forEach(([n,o])=>{n.toLowerCase()==="domain"&&o!=null&&(e.domain=o),n.toLowerCase()==="max-age"&&o!=null&&(e.expires=Date.now()+parseInt(o,10)*1e3),!Jj.includes(n.toLowerCase())&&o!=null&&t.push({name:n,value:o})}),t.map(n=>({...n,...e}))}var Jj=["domain","expires","httponly","max-age","partitioned","path","samesite","secure"];var u3=class{async prepareRequest(e,t){if(t.headers.get("origin")!=null||t.mode==="no-cors")return;let n=Ah(e,t.headers);t.headers.set("origin",`${n.protocol}//${n.host}`)}};function eY(r){return typeof r.init=="function"}function d3(r,e){if(eY(r)){let t=r;return t.handler=r.init(e),delete t.init,t}return r}function PR(r){let e=n3(r.method,["GET"]);if(r.fallback==null&&e.filter(n=>n!=="GET").length>0)throw new E("WebSocket handlers only support the GET HTTP method");let t={...r,init:n=>{let o=d3(r,n);return t[a3]=o.handler,async i=>{if(!Jg(i.method,i.headers))return r?.fallback!=null?r.fallback(i):new ri(null,{status:400});let s=new TransformStream;try{let a=new ri(s.readable,{status:101,headers:await db(i.headers)}),c=new Ih(i,s.writable,r);return o.handler(c),a}catch{return new ri(null,{status:500})}}}};return t}var f3="/.well-known/libp2p/protocols";function DR(r){return PR({path:f3,method:["GET"],cors:!0,handler:e=>{let t=JSON.stringify(r.getProtocolMap());e.send(t),e.close()},fallback:async e=>{let t=JSON.stringify(r.getProtocolMap());return new Response(t,{headers:{"Content-Type":"application/json","Content-Length":`${t.length}`}})}})}var h3=class{log;components;protocols;endpoint;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:http:registrar"),this.protocols=[],this.onStream=this.onStream.bind(this),this.endpoint=t.server,this.handle("",DR(this))}async start(){await this.components.registrar.handle(Rh,this.onStream.bind(this))}async stop(){await this.components.registrar.unhandle(Rh)}async onStream(e,t){let n=await lR(e);if(this.canHandle(n)){this.log("handling incoming request %s %s",n.method,n.url);let o=await this.onRequest(sR(n,e));await aR(o,e),await e.close();return}if(this.endpoint==null){this.log("cannot handle incoming request %s %s and no endpoint configured",n.method,n.url),e.send(cR),await e.close();return}this.log("passing incoming request %s %s to endpoint",n.method,n.url),this.endpoint.inject(n,e,t).catch(o=>{this.log.error("error injecting request to endpoint - %e",o),e.abort(o)})}canHandle(e){let t=ub(e).pathname;return this.protocols.find(n=>n.route.path===t)!=null?(this.log.trace("can handle %s",t),!0):(this.log.trace("cannot handle %s",t),!1)}async onRequest(e){this.log("incoming request %s %s",e.method,e.url);let t=this.findHandler(e.url);if(t==null)return new Response(null,{status:404});let n;return t.route.method.includes(e.method)?n=await t.route.handler(e):e.method==="OPTIONS"?n=new Response(null,{status:204}):n=new Response(null,{status:405}),tY(n,e,t),this.log("%s %s %d %s",e.method,e.url,n.status,n.statusText),n}onWebSocket(e){let t=this.findHandler(e.url);if(t!=null){let n=t.route[a3];if(n!=null){n(e);return}}e.close(Ch.NORMAL_CLOSURE)}findHandler(e){let t=e.startsWith("/")?e:new URL(e).pathname;this.log("search for handler on path %s",t);let n=this.protocols.find(o=>o.route.path===t);return n!=null&&this.log("found handler for HTTP protocol %s on path %s",n.protocol,e),n}handle(e,t){if(t.path=t.path??e,this.protocols.find(n=>n.protocol===e)!=null)throw new E(`HTTP protocol handler for ${e} already registered`);(t.path===""||!t.path.startsWith("/"))&&(t.path=`/${t.path}`),t.cors=t.cors??!0,t.method=n3(t.method),t=d3(t,this.components),this.protocols.push({protocol:e,route:t}),this.protocols.sort(({route:{path:n}},{route:{path:o}})=>o.length-n.length)}unhandle(e){this.protocols=this.protocols.filter(t=>t.protocol===e)}getProtocolMap(){let e={};for(let t of this.protocols)t.protocol!==""&&(e[t.protocol]={path:t.route.path});return e}};function tY(r,e,t){let n=[...new Set(["OPTIONS",...t.route.method])].join(", ");t.route.cors&&(e.headers.get("Access-Control-Request-Method")!=null&&r.headers.set("access-control-allow-methods",n),e.headers.get("Access-Control-Request-Headers")!=null&&r.headers.set("access-control-allow-headers",e.headers.get("Access-Control-Request-Headers")??""),e.headers.get("Origin")!=null&&(r.headers.set("access-control-allow-origin",e.headers.get("Origin")??""),r.headers.set("vary","Origin"))),e.method==="OPTIONS"&&r.headers.set("allow",n)}async function LR(r,e,t){for(let n of e.middleware)await n.prepareRequest?.(r,e);return t()}async function NR(r,e,t){for(let n of e.middleware)await n.prepareRequest?.(r,e);return t()}async function OR(r,e,t){for(let n of e.middleware)await n.processResponse?.(r,e,t);return t}var p3=class{log;components;httpRegistrar;origin;cookies;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:http"),this.httpRegistrar=new h3(e,t),this.origin=new u3,this.cookies=new l3(e,t)}[Symbol.toStringTag]="@libp2p/http";[be]=["@libp2p/http"];async start(){await Rt(this.httpRegistrar)}async stop(){await Ut(this.httpRegistrar)}agent(...e){throw new ed("This method is not supported in browsers")}dispatcher(...e){throw new ed("This method is not supported in browsers")}async connect(e,t={}){let n=Eu(e),o=ti(t),i={...t,headers:o,method:"GET",middleware:t.middleware?.map(s=>s(this.components))??[]};return o.set("connection","upgrade"),o.set("upgrade","websocket"),NR(n,i,async()=>{if(n instanceof URL){let c=new globalThis.WebSocket(n,t.protocols);return c.binaryType="arraybuffer",c}let{addresses:s,httpPath:a}=r3(n);return new kh(s,new URL(`http://${t3(n,i.headers)}${decodeURIComponent(a)}`),this.components.connectionManager,i)})}async fetch(e,t={}){let n=Eu(e),o={...t,headers:ti(t),method:"GET",middleware:[this.origin,this.cookies,...t.middleware?.map(s=>s(this.components))??[]]},i=await LR(n,o,async()=>this.sendRequest(n,t));return OR(n,o,i)}async connectProtocol(e,t,n){let o=await this.getProtocolPath(e,t,n),i=Eu(e,o);return this.connect(i,n)}async fetchProtocol(e,t,n={}){let o=await this.getProtocolPath(e,t,n),i=Eu(e,o);return this.fetch(i,n)}async getSupportedProtocols(e,t={}){let n=Eu(e,f3),o=await this.fetch(n,{method:"GET",headers:{Accept:"application/json"},signal:t.signal});if(o.status!==200)throw new Error(`Unexpected status code: ${o.status}`);return o.json()}async getProtocolPath(e,t,n={}){let o=await this.getSupportedProtocols(e,n);if(o[t]==null)throw new Error(`Peer does not serve protocol: ${t}`);return o[t].path}canHandle(e){return this.httpRegistrar.canHandle(e)}async onRequest(e){return this.httpRegistrar.onRequest(e)}onWebSocket(e){this.httpRegistrar.onWebSocket(e)}handle(e,t){this.httpRegistrar.handle(e,t)}unhandle(e){this.httpRegistrar.unhandle(e)}getProtocolMap(){return this.httpRegistrar.getProtocolMap()}async sendRequest(e,t){if(e instanceof URL)return this.log("making request to %s with global fetch"),globalThis.fetch(e,t);this.log("making request to %s with libp2p fetch",e);let n=t3(e,ti(t)),{addresses:o,httpPath:i}=r3(e),a=await(await this.components.connectionManager.openConnection(o,{signal:t.signal??void 0})).newStream(Rh,{signal:t.signal??void 0});return yR(a,new URL(`http://${n}${decodeURIComponent(i)}`),t)}};function BR(r={}){return e=>new p3(e,r)}function MR(r=0){return new Uint8Array(r)}function UR(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var FR=UR("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),gb=UR("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=MR(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),rY={utf8:FR,"utf-8":FR,hex:oe.base16,latin1:gb,ascii:gb,binary:gb,...oe},m3=rY;function Ms(r,e="utf8"){let t=m3[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function yb(r,e="utf8"){let t=m3[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var $R="0.1.0";var HR="id/push",qR="1.0.0",VR="1.0.0";var Fs;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.protocolVersion!=null&&(s.uint32(42),s.string(i.protocolVersion)),i.agentVersion!=null&&(s.uint32(50),s.string(i.agentVersion)),i.publicKey!=null&&(s.uint32(10),s.bytes(i.publicKey)),i.listenAddrs!=null&&i.listenAddrs.length>0)for(let c of i.listenAddrs)s.uint32(18),s.bytes(c);if(i.observedAddr!=null&&(s.uint32(34),s.bytes(i.observedAddr)),i.protocols!=null&&i.protocols.length>0)for(let c of i.protocols)s.uint32(26),s.string(c);i.signedPeerRecord!=null&&(s.uint32(66),s.bytes(i.signedPeerRecord)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={listenAddrs:[],protocols:[]},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 5:{c.protocolVersion=i.string();break}case 6:{c.agentVersion=i.string();break}case 1:{c.publicKey=i.bytes();break}case 2:{if(a.limits?.listenAddrs!=null&&c.listenAddrs.length===a.limits.listenAddrs)throw new le('Decode error - repeated field "listenAddrs" had too many elements');c.listenAddrs.push(i.bytes());break}case 4:{c.observedAddr=i.bytes();break}case 3:{if(a.limits?.protocols!=null&&c.protocols.length===a.limits.protocols)throw new le('Decode error - repeated field "protocols" had too many elements');c.protocols.push(i.string());break}case 8:{c.signedPeerRecord=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={listenAddrs:0,protocols:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 5:{yield{field:`${a}.protocolVersion`,value:i.string()};break}case 6:{yield{field:`${a}.agentVersion`,value:i.string()};break}case 1:{yield{field:`${a}.publicKey`,value:i.bytes()};break}case 2:{if(c.limits?.listenAddrs!=null&&l.listenAddrs===c.limits.listenAddrs)throw new le('Streaming decode error - repeated field "listenAddrs" had too many elements');yield{field:`${a}.listenAddrs[]`,index:l.listenAddrs,value:i.bytes()},l.listenAddrs++;break}case 4:{yield{field:`${a}.observedAddr`,value:i.bytes()};break}case 3:{if(c.limits?.protocols!=null&&l.protocols===c.limits.protocols)throw new le('Streaming decode error - repeated field "protocols" had too many elements');yield{field:`${a}.protocols[]`,index:l.protocols,value:i.string()},l.protocols++;break}case 8:{yield{field:`${a}.signedPeerRecord`,value:i.bytes()};break}default:{i.skipType(d&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Fs||(Fs={}));var zr={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function zR(r){return r.bytes.length===0}function wb(r){if(r!=null&&r.length>0)try{let e=j(r);if(!zR(e))return e}catch{}}async function g3(r,e,t,n,o){if(t("received identify from %p",n.remotePeer),o==null)throw new he("message was null or undefined");let i={},s=o.listenAddrs.map(wb).filter(l=>l!=null);if(o.listenAddrs.length>0&&(i.addresses=s.map(l=>({isCertified:!1,multiaddr:l}))),o.protocols.length>0&&(i.protocols=o.protocols),o.publicKey!=null){let l=Et(o.publicKey);if(!zo(l).equals(n.remotePeer))throw new he("public key did not match remote PeerId");i.publicKey=l}let a;if(o.signedPeerRecord!=null){t.trace("received signedPeerRecord from %p",n.remotePeer);let l=o.signedPeerRecord,u=await gn.openAndCertify(l,Or.DOMAIN),d=Or.createFromProtobuf(u.payload),f=Lr(u.publicKey.toCID());if(!d.peerId.equals(f))throw new he("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(d.peerId))throw new he("signing key does not match remote PeerId");let h;try{h=await r.get(d.peerId)}catch(y){if(y.name!=="NotFoundError")throw y}if(h!=null&&(i.metadata=h.metadata,h.peerRecordEnvelope!=null)){let y=gn.createFromProtobuf(h.peerRecordEnvelope),g=Or.createFromProtobuf(y.payload);g.seqNumber>=d.seqNumber&&(t("sequence number was lower or equal to existing sequence number - stored: %d received: %d",g.seqNumber,d.seqNumber),d=g,l=h.peerRecordEnvelope)}i.peerRecordEnvelope=l;let p=d.multiaddrs.filter(y=>!zR(y));i.addresses=p.map(y=>({isCertified:!0,multiaddr:y})),a={seq:d.seqNumber,addresses:p}}else t("%p did not send a signed peer record",n.remotePeer);if(t.trace("patching %p with",n.remotePeer,i),await r.patch(n.remotePeer,i),o.agentVersion!=null||o.protocolVersion!=null){let l={};o.agentVersion!=null&&(l.AgentVersion=Ms(o.agentVersion)),o.protocolVersion!=null&&(l.ProtocolVersion=Ms(o.protocolVersion)),t.trace("merging %p metadata",n.remotePeer,l),await r.merge(n.remotePeer,{metadata:l})}let c={peerId:n.remotePeer,protocolVersion:o.protocolVersion,agentVersion:o.agentVersion,publicKey:o.publicKey,listenAddrs:s,observedAddr:o.observedAddr==null?void 0:j(o.observedAddr),protocols:o.protocols,signedPeerRecord:a,connection:n};return e.safeDispatchEvent("peer:identify",{detail:c}),c}function y3(r){let e={...r[0]};for(let t of r.slice(1))t.protocolVersion!=null&&(e.protocolVersion=t.protocolVersion),t.agentVersion!=null&&(e.agentVersion=t.agentVersion),t.publicKey!=null&&(e.publicKey=t.publicKey),t.observedAddr!=null&&(e.observedAddr=t.observedAddr),t.signedPeerRecord!=null&&(e.signedPeerRecord=t.signedPeerRecord),e.listenAddrs=[...e.listenAddrs,...t.listenAddrs],e.protocols=[...new Set([...e.protocols,...t.protocols])];return e}async function w3(r,e,t,n){let o=Xe(r,{maxDataLength:e}).pb(Fs),i=[];for(let s=0;s<10;s++)try{i.push(await o.read(t))}catch(a){if(i.length===0)throw a;n.trace("stopped reading identify - %e",a);break}i.length>=10&&n("reached MAX_IDENTIFY_MESSAGES, returning truncated identify");try{await r.close(t)}catch(s){n.trace("error closing identify stream after read - %e",s),r.abort(s)}return i}var vu=class{host;components;protocol;started;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;runOnLimitedConnection;log;constructor(e,t){this.protocol=t.protocol,this.started=!1,this.components=e,this.log=t.log,this.timeout=t.timeout??zr.timeout,this.maxInboundStreams=t.maxInboundStreams??zr.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??zr.maxOutboundStreams,this.maxMessageSize=t.maxMessageSize??zr.maxMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??zr.maxObservedAddresses,this.runOnLimitedConnection=t.runOnLimitedConnection??zr.runOnLimitedConnection,this.host={protocolVersion:`${t.protocolPrefix??zr.protocolPrefix}/${$R}`,agentVersion:e.nodeInfo.userAgent},this.handleProtocol=this.handleProtocol.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.merge(this.components.peerId,{metadata:{AgentVersion:Ms(this.host.agentVersion),ProtocolVersion:Ms(this.host.protocolVersion)}}),await this.components.registrar.handle(this.protocol,this.handleProtocol,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}};var b3=class extends vu{connectionManager;concurrency;_push;constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??zr.protocolPrefix}/${HR}/${VR}`,log:e.logger.forComponent("libp2p:identify-push")}),this.connectionManager=e.connectionManager,this.concurrency=t.concurrency??zr.concurrency,this._push=Ei(this.sendPushMessage.bind(this),t.debounce??1e3),(t.runOnSelfUpdate??zr.runOnSelfUpdate)&&e.events.addEventListener("self:peer:update",n=>{this.push().catch(o=>{this.log.error("error pushing updates to peers - %e",o)})})}[be]=["@libp2p/identify-push"];async push(){this._push()}async sendPushMessage(){if(this.isStarted())try{let e=this.components.addressManager.getAddresses().map(u=>u.decapsulateCode(421)),t=new Or({peerId:this.components.peerId,multiaddrs:e}),n=await gn.seal(t,this.components.privateKey),o=this.components.registrar.getProtocols(),i=await this.components.peerStore.get(this.components.peerId),s=yb(i.metadata.get("AgentVersion")??Ms(this.host.agentVersion)),a=yb(i.metadata.get("ProtocolVersion")??Ms(this.host.protocolVersion)),c=this;async function*l(){for(let u of c.connectionManager.getConnections())(await c.components.peerStore.get(u.remotePeer)).protocols.includes(c.protocol)&&(yield async()=>{let f,h=AbortSignal.timeout(c.timeout);try{f=await u.newStream(c.protocol,{signal:h,runOnLimitedConnection:c.runOnLimitedConnection}),await Xe(f,{maxDataLength:c.maxMessageSize}).pb(Fs).write({listenAddrs:e.map(y=>y.bytes),signedPeerRecord:n.marshal(),protocols:o,agentVersion:s,protocolVersion:a},{signal:h}),await f.close({signal:h})}catch(p){f?.log.newScope("identify-push")?.error("could not push identify update to peer",p),f?.abort(p)}})}await pr(yn(l(),{concurrency:this.concurrency}))}catch(e){this.log.error("error pushing updates to peers - %e",e)}}async handleProtocol(e,t){let n=e.log.newScope("identify-push");if(this.components.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let o={signal:AbortSignal.timeout(this.timeout)},i=await w3(e,this.maxMessageSize,o,n);await g3(this.components.peerStore,this.components.events,n,t,y3(i)),n.trace("handled push from %p",t.remotePeer)}};var x3=class extends vu{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??zr.protocolPrefix}/${"id"}/${qR}`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??zr.runOnConnectionOpen)&&e.events.addEventListener("connection:open",n=>{let o=n.detail;this.identify(o).catch(()=>{})})}[be]=["@libp2p/identify"];async _identify(e,t={}){let n,o;if(t.signal==null){let i=AbortSignal.timeout(this.timeout);t={...t,signal:i}}this.log("run identify on new connection %a",e.remoteAddr);try{n=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),o=n.log.newScope("identify");let i=await w3(n,this.maxMessageSize,t,o);return y3(i)}catch(i){throw o?.error("identify failed - %e",i),n?.abort(i),i}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:o,protocols:i,observedAddr:s}=n;if(o==null)throw new he("Public key was missing from identify message");let a=Et(o),c=Lr(a.toCID());if(!e.remotePeer.equals(c))throw new he("Identified peer does not match the expected peer");if(this.components.peerId.equals(c))throw new he("Identified peer is our own peer id?");return this.maybeAddObservedAddress(s),this.log("completed for peer %p and protocols %o",c,i),g3(this.components.peerStore,this.components.events,this.log,e,n)}maybeAddObservedAddress(e){let t=wb(e);if(t==null||(this.log.trace("our observed address was %a",t),wt(t)))return;let n=t.getComponents();if((n[0].code===41||n[0].code===42&&n[1].code===41)&&!ym(t)){this.log.trace("our observed address was IPv6 but not a global unicast address");return}bi.exactMatch(t)||(this.log.trace("storing the observed address"),this.components.addressManager.addObservedAddr(t))}async handleProtocol(e,t){let n=e.log.newScope("identify");n("responding to identify");let o=AbortSignal.timeout(this.timeout);let i=await this.components.peerStore.get(this.components.peerId,{signal:o}),s=this.components.addressManager.getAddresses().map(u=>u.decapsulateCode(421)),a=i.peerRecordEnvelope;if(s.length>0&&a==null){let u=new Or({peerId:this.components.peerId,multiaddrs:s});a=(await gn.seal(u,this.components.privateKey,{signal:o})).marshal().subarray()}let c=t.remoteAddr.bytes;jS.matches(t.remoteAddr)||(c=void 0);let l=Xe(e).pb(Fs);n("send response"),await l.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Ht(this.components.privateKey.publicKey),listenAddrs:s.map(u=>u.bytes),signedPeerRecord:a,observedAddr:c,protocols:i.protocols},{signal:o}),n("close write"),await l.unwrap().unwrap().close({signal:o})}};function GR(r={}){return e=>new x3(e,r)}function WR(r={}){return e=>new b3(e,r)}var xc=1e3,bb=60*xc,E3=60*bb,jR="/ipfs/kad/1.0.0",v3=48*E3;var YR=24*E3,XR=10,QR=16384,ZR=E3,xb=E3,oke=10*xc,JR=10*xc;var S3=20,Us=10,eP=5*bb,tP=xc,rP=5*xc,nP=5*bb,oP=30*xc,iP=180*xc,Eb=`${ca}-kad-dht`;function vb(r=0){return new Uint8Array(r)}var Ph;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.key!=null&&i.key.byteLength>0&&(s.uint32(10),s.bytes(i.key)),i.value!=null&&i.value.byteLength>0&&(s.uint32(18),s.bytes(i.value)),i.timeReceived!=null&&i.timeReceived!==""&&(s.uint32(42),s.string(i.timeReceived)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={key:vb(0),value:vb(0),timeReceived:""},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.key=i.bytes();break}case 2:{c.value=i.bytes();break}case 5:{c.timeReceived=i.string();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.key`,value:i.bytes()};break}case 2:{yield{field:`${a}.value`,value:i.bytes()};break}case 5:{yield{field:`${a}.timeReceived`,value:i.string()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Ph||(Ph={}));function sP(r){let e=r.getUTCFullYear(),t=String(r.getUTCMonth()+1).padStart(2,"0"),n=String(r.getUTCDate()).padStart(2,"0"),o=String(r.getUTCHours()).padStart(2,"0"),i=String(r.getUTCMinutes()).padStart(2,"0"),s=String(r.getUTCSeconds()).padStart(2,"0"),a=r.getUTCMilliseconds(),c=String(a*1e3*1e3).padStart(9,"0");return`${e}-${t}-${n}T${o}:${i}:${s}.${c}Z`}function aP(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),o=parseInt(t[2],10)-1,i=parseInt(t[3],10),s=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),l=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,o,i,s,a,c,l))}var ft=class r{key;value;timeReceived;constructor(e,t,n){if(!(e instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(t instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=e,this.value=t,this.timeReceived=n}serialize(){return Ph.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:sP(this.timeReceived)}}static deserialize(e){let t=Ph.decode(e);return new r(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){let t=aP(e.timeReceived);if(e.key==null)throw new Error("key missing from deserialized object");if(e.value==null)throw new Error("value missing from deserialized object");return new r(e.key,e.value,t)}};function So(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 $s=class extends Error{constructor(e="Query error"){super(e),this.name="QueryError"}},A3=class extends Error{constructor(e="Invalid record"){super(e),this.name="InvalidRecordError"}},T3=class extends Error{constructor(e="No selector function configured for prefix"){super(e),this.name="MissingSelectorError"}};function Sb(r=0){return new Uint8Array(r)}function Ec(r=0){return new Uint8Array(r)}var cP;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.key!=null&&(s.uint32(10),s.bytes(i.key)),i.value!=null&&(s.uint32(18),s.bytes(i.value)),i.author!=null&&(s.uint32(26),s.bytes(i.author)),i.signature!=null&&(s.uint32(34),s.bytes(i.signature)),i.timeReceived!=null&&(s.uint32(42),s.string(i.timeReceived)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.key=i.bytes();break}case 2:{c.value=i.bytes();break}case 3:{c.author=i.bytes();break}case 4:{c.signature=i.bytes();break}case 5:{c.timeReceived=i.string();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.key`,value:i.bytes()};break}case 2:{yield{field:`${a}.value`,value:i.bytes()};break}case 3:{yield{field:`${a}.author`,value:i.bytes()};break}case 4:{yield{field:`${a}.signature`,value:i.bytes()};break}case 5:{yield{field:`${a}.timeReceived`,value:i.string()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(cP||(cP={}));var De;(function(r){r.PUT_VALUE="PUT_VALUE",r.GET_VALUE="GET_VALUE",r.ADD_PROVIDER="ADD_PROVIDER",r.GET_PROVIDERS="GET_PROVIDERS",r.FIND_NODE="FIND_NODE",r.PING="PING"})(De||(De={}));var _3;(function(r){r[r.PUT_VALUE=0]="PUT_VALUE",r[r.GET_VALUE=1]="GET_VALUE",r[r.ADD_PROVIDER=2]="ADD_PROVIDER",r[r.GET_PROVIDERS=3]="GET_PROVIDERS",r[r.FIND_NODE=4]="FIND_NODE",r[r.PING=5]="PING"})(_3||(_3={}));(function(r){r.codec=()=>Ye(_3)})(De||(De={}));var vc;(function(r){r.NOT_CONNECTED="NOT_CONNECTED",r.CONNECTED="CONNECTED",r.CAN_CONNECT="CAN_CONNECT",r.CANNOT_CONNECT="CANNOT_CONNECT"})(vc||(vc={}));var Ab;(function(r){r[r.NOT_CONNECTED=0]="NOT_CONNECTED",r[r.CONNECTED=1]="CONNECTED",r[r.CAN_CONNECT=2]="CAN_CONNECT",r[r.CANNOT_CONNECT=3]="CANNOT_CONNECT"})(Ab||(Ab={}));(function(r){r.codec=()=>Ye(Ab)})(vc||(vc={}));var Hs;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.id!=null&&i.id.byteLength>0&&(s.uint32(10),s.bytes(i.id)),i.multiaddrs!=null&&i.multiaddrs.length>0)for(let c of i.multiaddrs)s.uint32(18),s.bytes(c);i.connection!=null&&(s.uint32(24),vc.codec().encode(i.connection,s)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={id:Sb(0),multiaddrs:[]},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.id=i.bytes();break}case 2:{if(a.limits?.multiaddrs!=null&&c.multiaddrs.length===a.limits.multiaddrs)throw new le('Decode error - repeated field "multiaddrs" had too many elements');c.multiaddrs.push(i.bytes());break}case 3:{c.connection=vc.codec().decode(i);break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={multiaddrs:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${a}.id`,value:i.bytes()};break}case 2:{if(c.limits?.multiaddrs!=null&&l.multiaddrs===c.limits.multiaddrs)throw new le('Streaming decode error - repeated field "multiaddrs" had too many elements');yield{field:`${a}.multiaddrs[]`,index:l.multiaddrs,value:i.bytes()},l.multiaddrs++;break}case 3:{yield{field:`${a}.connection`,value:vc.codec().decode(i)};break}default:{i.skipType(d&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Hs||(Hs={}));var qs;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{if(a.lengthDelimited!==!1&&s.fork(),i.type!=null&&_3[i.type]!==0&&(s.uint32(8),De.codec().encode(i.type,s)),i.clusterLevel!=null&&(s.uint32(80),s.int32(i.clusterLevel)),i.key!=null&&(s.uint32(18),s.bytes(i.key)),i.record!=null&&(s.uint32(26),s.bytes(i.record)),i.closer!=null&&i.closer.length>0)for(let c of i.closer)s.uint32(66),Hs.codec().encode(c,s);if(i.providers!=null&&i.providers.length>0)for(let c of i.providers)s.uint32(74),Hs.codec().encode(c,s);a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={type:De.PUT_VALUE,closer:[],providers:[]},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.type=De.codec().decode(i);break}case 10:{c.clusterLevel=i.int32();break}case 2:{c.key=i.bytes();break}case 3:{c.record=i.bytes();break}case 8:{if(a.limits?.closer!=null&&c.closer.length===a.limits.closer)throw new le('Decode error - repeated field "closer" had too many elements');c.closer.push(Hs.codec().decode(i,i.uint32(),{limits:a.limits?.closer$}));break}case 9:{if(a.limits?.providers!=null&&c.providers.length===a.limits.providers)throw new le('Decode error - repeated field "providers" had too many elements');c.providers.push(Hs.codec().decode(i,i.uint32(),{limits:a.limits?.providers$}));break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l={closer:0,providers:0},u=s==null?i.len:i.pos+s;for(;i.pos<u;){let d=i.uint32();switch(d>>>3){case 1:{yield{field:`${a}.type`,value:De.codec().decode(i)};break}case 10:{yield{field:`${a}.clusterLevel`,value:i.int32()};break}case 2:{yield{field:`${a}.key`,value:i.bytes()};break}case 3:{yield{field:`${a}.record`,value:i.bytes()};break}case 8:{if(c.limits?.closer!=null&&l.closer===c.limits.closer)throw new le('Streaming decode error - repeated field "closer" had too many elements');for(let f of Hs.codec().stream(i,i.uint32(),`${a}.closer[]`,{limits:c.limits?.closer$}))yield{...f,index:l.closer};l.closer++;break}case 9:{if(c.limits?.providers!=null&&l.providers===c.limits.providers)throw new le('Streaming decode error - repeated field "providers" had too many elements');for(let f of Hs.codec().stream(i,i.uint32(),`${a}.providers[]`,{limits:c.limits?.providers$}))yield{...f,index:l.providers};l.providers++;break}default:{i.skipType(d&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(qs||(qs={}));function Tb(r,e={}){let t={...r,name:"SEND_QUERY",type:0,messageName:r.type,messageType:r.type};return e.onProgress?.(new CustomEvent("kad-dht:query:send-query",{detail:t})),t}function Dh(r,e={}){let t={...r,name:"PEER_RESPONSE",type:1,messageName:r.messageType,closer:r.closer??[],providers:r.providers??[]};return e.onProgress?.(new CustomEvent("kad-dht:query:peer-response",{detail:t})),t}function C3(r,e={}){let t={...r,name:"FINAL_PEER",type:2};return e.onProgress?.(new CustomEvent("kad-dht:query:final-peer",{detail:t})),t}function Ao(r,e={}){let t={...r,name:"QUERY_ERROR",type:3};return e.onProgress?.(new CustomEvent("kad-dht:query:query-error",{detail:t})),t}function _b(r,e={}){let t={...r,name:"PROVIDER",type:4};return e.onProgress?.(new CustomEvent("kad-dht:query:provider",{detail:t})),t}function Lh(r,e={}){let t={...r,name:"VALUE",type:5};return e.onProgress?.(new CustomEvent("kad-dht:query:value",{detail:t})),t}function Cb(r,e={}){let t={...r,name:"DIAL_PEER",type:7};return e.onProgress?.(new CustomEvent("kad-dht:query:dial-peer",{detail:t})),t}function lP(r,e={}){let t={...r,name:"PATH_ENDED",type:8};return e.onProgress?.(new CustomEvent("kad-dht:query:path-ended",{detail:t})),t}function dP(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var uP=dP("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ib=dP("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=Ec(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),cY={utf8:uP,"utf-8":uP,hex:oe.base16,latin1:Ib,ascii:Ib,binary:Ib,...oe},I3=cY;function br(r,e="utf8"){let t=I3[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}async function fP(r,e,t){if(t.length===0)throw new E("No records given");let o=br(e).split("/");if(o.length<3)throw new E("Record key does not have a selector function");let i=r[o[1].toString()];if(i==null)throw new T3(`No selector function configured for key type "${o[1]}"`);return t.length===1?0:i(e,t)}function lY(r,e){return 0}var hP={pk:lY};async function Su(r,e,t){let n=e.key,i=br(n).split("/");if(i.length<3)throw new E("Record key is missing a namespace");let s=r[i[1].toString()];if(s==null)throw new E(`No validator available for key type "${i[1]}"`);await s(n,e.value,t)}var uY=async(r,e,t)=>{if(!(r instanceof Uint8Array))throw new E('"key" must be a Uint8Array');if(r.byteLength<5)throw new E("Invalid public key record");if(br(r.subarray(0,4))!=="/pk/")throw new E("key was not prefixed with /pk/");let o=Et(e),i=r.slice(4);if(!So(i,o.toMultihash().bytes))throw new E("public key does not match passed in key")},pP={pk:uY};function dY(r){return r?.buffer instanceof ArrayBuffer}function k3(r){if(dY(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function kb(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=Ec(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return k3(t)}function R3(r,e="utf8"){let t=I3[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var fY=R3("/pk/");function mP(r){return{...r,multiaddrs:r.multiaddrs.filter(e=>!wt(e))}}async function Vs(r,e){let t=await ct.digest(r);return e?.signal?.throwIfAborted(),t.digest}async function Gr(r,e){return Vs(r.toMultihash().bytes,e)}function Ks(r,e){return new He(`${r}/${br(e,"base32")}`,!1)}function gP(r){return kb([fY,r.toMultihash().bytes])}function yP(r){return br(r.subarray(0,4))==="/pk/"}function wP(r){let e=xe(r.subarray(4));return bt(e)}function Rb(r,e){let t=new Date;return new ft(r,e,t).serialize()}function P3(r){let e=r.toString().split("/"),t=e.pop(),n=e.pop();if(t==null||n==null)throw new Error(`incorrectly formatted provider entry key in datastore: ${r.toString()}`);return{cid:F.createV1(Ie,xe(R3(n,"base32"))),peerId:Ee(t)}}function D3(r,e,t){let n=typeof e=="string"?e:br(e.multihash.bytes,"base32"),o=[r,n];return t!=null&&o.push(t.toString()),new He(o.join("/"))}function L3(r){return new Date(No(r))}function Sc(r,e,t){return async function*(...n){let o=e.queryTime?.timer(t),i=e.errorTime?.timer(t),s=!1;try{e.queries?.increment({[t]:!0}),yield*r(...n)}catch(a){throw s=!0,i?.(),e.errors?.increment({[t]:!0}),a}finally{e.queries?.decrement({[t]:!0}),s||o?.()}}}function N3(r,e,t){return async function(...n){let o=e?.queryTime?.timer(t),i=e?.errorTime?.timer(t),s=!1;try{return e.queries?.increment({[t]:!0}),await r(...n)}catch(a){throw s=!0,i?.(),e.errors?.increment({[t]:!0}),a}finally{e.queries?.decrement({[t]:!0}),s||o?.()}}}var O3=class{log;components;validators;selectors;peerRouting;queryManager;network;datastorePrefix;constructor(e,t){let{validators:n,selectors:o,peerRouting:i,queryManager:s,network:a,logPrefix:c}=t;this.components=e,this.log=e.logger.forComponent(`${c}:content-fetching`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.validators=n,this.selectors=o,this.peerRouting=i,this.queryManager=s,this.network=a,this.get=e.metrics?.traceFunction("libp2p.kadDHT.get",this.get.bind(this),{optionsIndex:1})??this.get,this.put=e.metrics?.traceFunction("libp2p.kadDHT.put",this.put.bind(this),{optionsIndex:2})??this.put}async getLocal(e,t){this.log("getLocal %b",e);let n=Ks(this.datastorePrefix,e);this.log("fetching record for key %k",n);let o=await this.components.datastore.get(n,t);this.log("found %k in local datastore",n);let i=ft.deserialize(o);return await Su(this.validators,i,t),i}async*sendCorrectionRecord(e,t,n,o){this.log("sendCorrection for %b",e);let i=Rb(e,n);for(let{value:s,from:a}of t){if(So(s,n)){this.log("record was ok");continue}if(this.components.peerId.equals(a)){try{let u=Ks(this.datastorePrefix,e);this.log(`Storing corrected record for key ${u.toString()}`),await this.components.datastore.put(u,i.subarray(),o)}catch(u){this.log.error("failed error correcting self - %e",u)}continue}let c=!1,l={type:De.PUT_VALUE,key:e,record:i};for await(let u of this.network.sendRequest(a,l,o))u.name==="PEER_RESPONSE"&&u.record!=null&&So(u.record.value,ft.deserialize(i).value)&&(c=!0),yield u;if(!c)throw new $s("Could not send correction");this.log.error("failed error correcting entry")}}async*put(e,t,n){this.log("put key %b value %b",e,t);let o=Rb(e,t),i=Ks(this.datastorePrefix,e);this.log(`storing record for key ${i.toString()}`),await this.components.datastore.put(i,o.subarray(),n),yield*on(this.peerRouting.getClosestPeers(e,{...n,signal:n.signal}),s=>Ct(s,a=>async()=>{if(a.name!=="FINAL_PEER")return[a];let c=[],l={type:De.PUT_VALUE,key:e,record:o};this.log("send put to %p",a.peer.id);for await(let u of this.network.sendRequest(a.peer.id,l,{...n,path:a.path}))c.push(u),u.name==="PEER_RESPONSE"&&(u.record!=null&&So(u.record.value,ft.deserialize(o).value)||c.push(Ao({from:a.peer.id,error:new $s("Value not put correctly"),path:u.path},n)));return c}),s=>yn(s,{ordered:!1,concurrency:Us}),async function*(s){for await(let a of s)yield*a})}async*get(e,t){this.log("get %b",e);let n=[];for await(let a of this.getMany(e,t)){if(a.name==="VALUE"){n.push(a);continue}yield a}if(n.length===0)return;let o=n.map(a=>a.value),i=0;try{i=await fP(this.selectors,e,o)}catch(a){if(a.name!=="InvalidParametersError")throw a}let s=o[i];if(this.log("GetValue %b %b",e,s),s==null)throw new qe("Best value was not found");yield*this.sendCorrectionRecord(e,n,s,{...t,path:{index:-1,queued:0,running:0,total:0}}),yield n[i]}async*getMany(e,t={}){this.log("getMany values for %b",e);try{let i=await this.getLocal(e,t);yield Lh({value:i.value,from:this.components.peerId,path:{index:-1,running:0,queued:0,total:0}},t)}catch(i){this.log("error getting local value for %b",e,i)}let n=this,o=async function*({peer:i,signal:s,path:a}){for await(let c of n.peerRouting.getValueOrPeers(i.id,e,{...t,signal:s,path:a}))yield c,c.name==="PEER_RESPONSE"&&c.record!=null&&(yield Lh({from:i.id,value:c.record.value,path:a},t))};yield*this.queryManager.run(e,o,t)}};function bP(r,e){return{id:r.id.toMultihash().bytes,multiaddrs:(r.multiaddrs??[]).map(n=>n.bytes),connection:e}}function Nh(r){if(r.id==null)throw new Error("Invalid peer in message");let e=xe(r.id);return{id:bt(e),multiaddrs:(r.multiaddrs??[]).map(t=>j(t))}}var B3=class{log;components;network;peerRouting;queryManager;routingTable;providers;constructor(e,t){let{network:n,peerRouting:o,queryManager:i,routingTable:s,providers:a,logPrefix:c}=t;this.components=e,this.log=e.logger.forComponent(`${c}:content-routing`),this.network=n,this.peerRouting=o,this.queryManager=i,this.routingTable=s,this.providers=a,this.findProviders=e.metrics?.traceFunction("libp2p.kadDHT.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(l,u)=>(l.name==="PROVIDER"&&(u.providers??=[],u.providers.push(...l.providers.map(d=>d.id.toString()))),u)})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.kadDHT.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(l,u)=>(l.name==="PEER_RESPONSE"&&l.messageName==="ADD_PROVIDER"&&(u.providers??=[],u.providers.push(l.from.toString())),u)})??this.provide}async*provide(e,t,n={}){this.log("provide %s",e);let o=e.multihash.bytes;await this.providers.addProvider(e,this.components.peerId,n);let i={type:De.ADD_PROVIDER,key:o,providers:[bP({id:this.components.peerId,multiaddrs:t})]},s=0,a=this;async function*c(d){try{a.log("sending provider record for %s to %p",e,d.peer.id);for await(let f of a.network.sendMessage(d.peer.id,i,{...n,path:d.path}))f.name==="PEER_RESPONSE"&&(a.log("sent provider record for %s to %p",e,d.peer.id),s++),yield f}catch(f){a.log.error("error sending provide record to peer %p - %e",d.peer.id,f),yield Ao({from:d.peer.id,error:f,path:d.path},n)}}let l=Nt({objectMode:!0}),u=new vt({concurrency:Us});u.addEventListener("idle",()=>{l.end()}),u.addEventListener("failure",d=>{this.log.error("error publishing provider record to peer - %e",d.detail.error)}),u.add(async()=>{let d=[];for await(let f of this.peerRouting.getClosestPeers(o,n))l.push(f),f.name==="FINAL_PEER"&&d.push(f);d.forEach(f=>{u.add(async()=>{for await(let h of c(f))l.push(h)}).catch(h=>{this.log.error("error publishing provider record to peer - %e",h)})})}).catch(d=>{l.end(d)}),yield*l,this.log("sent provider records to %d peers",s)}async*findProviders(e,t){let n=this.routingTable.kBucketSize,o=0,i=e.multihash.bytes,s=this;this.log("findProviders %c",e);let a=await this.providers.getProviders(e,t);if(a.length>0){let u=[];for(let d of a.slice(0,n))try{let f=await this.components.peerStore.get(d,t);u.push({id:d,multiaddrs:f.addresses.map(({multiaddr:h})=>h)})}catch(f){if(f.name!=="NotFoundError")throw f;this.log("no peer store entry for %p",d)}if(yield Dh({from:this.components.peerId,messageType:De.GET_PROVIDERS,providers:u,path:{index:-1,queued:0,running:0,total:0}},t),yield _b({from:this.components.peerId,providers:u,path:{index:-1,queued:0,running:0,total:0}},t),o+=u.length,o>=n)return}let c=async function*({peer:u,signal:d,path:f}){let h={type:De.GET_PROVIDERS,key:i};yield*s.network.sendRequest(u.id,h,{...t,signal:d,path:f})},l=new fn(a);for await(let u of this.queryManager.run(i,c,t))if(yield u,u.name==="PEER_RESPONSE"){this.log("Found %d provider entries for %c and %d closer peers",u.providers.length,e,u.closer.length);let d=[];for(let f of u.providers)l.has(f.id)||(l.add(f.id),d.push(f));if(d.length>0&&(yield _b({from:u.from,providers:d,path:u.path},t),o+=d.length,o>=n))return}}};var M3=class extends se{log;protocol;running;components;timeout;metrics;constructor(e,t){super(),this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:network`),this.running=!1,this.protocol=t.protocol,this.timeout=new ho({...t.timeout??{},metrics:e.metrics,metricName:`${t.metricsPrefix}_network_message_send_times_milliseconds`}),this.metrics={operations:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_outbound_rpc_requests_total`),errors:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_outbound_rpc_errors_total`)},this.sendRequest=e.metrics?.traceFunction("libp2p.kadDHT.sendRequest",this.sendRequest.bind(this),{optionsIndex:2,getAttributesFromArgs([n,o],i){return{...i,to:n.toString(),"message type":`${o.type}`}},getAttributesFromYieldedValue:(n,o)=>(n.name==="PEER_RESPONSE"&&(n.providers.length>0&&n.providers.forEach((i,s)=>{o[`providers-${s}`]=i.id.toString()}),n.closer.length>0&&n.closer.forEach((i,s)=>{o[`closer-${s}`]=i.id.toString()})),o)})??this.sendRequest,this.sendMessage=e.metrics?.traceFunction("libp2p.kadDHT.sendMessage",this.sendMessage.bind(this),{optionsIndex:2,getAttributesFromArgs([n,o],i){return{...i,to:n.toString(),"message type":`${o.type}`}},getAttributesFromYieldedValue:(n,o)=>(n.name==="PEER_RESPONSE"&&(n.providers.length>0&&n.providers.forEach((i,s)=>{o[`providers-${s}`]=i.id.toString()}),n.closer.length>0&&n.closer.forEach((i,s)=>{o[`closer-${s}`]=i.id.toString()})),o)})??this.sendMessage}async start(){this.running||(this.running=!0)}async stop(){this.running=!1}isStarted(){return this.running}async*sendRequest(e,t,n){if(!this.running)return;let o=t.type;if(o==null)throw new E("Message type was missing");let i,s=this.timeout.getTimeoutSignal(n);n={...n,signal:s};try{this.metrics.operations?.increment({[o]:!0}),this.log("dialling %p",e),yield Cb({peer:e,path:n.path},n),i=await this.components.connectionManager.openStream(e,this.protocol,n),this.log("sending %s to %p",t.type,e),yield Tb({to:e,type:o,path:n.path},n);let a=await this._writeReadMessage(i,t,n);i.close(n).catch(c=>{this.log.error("error closing stream to %p - %e",e,c),i?.abort(c)}),yield Dh({from:e,messageType:a.type,closer:a.closer.map(Nh),providers:a.providers.map(Nh),record:a.record==null?void 0:ft.deserialize(a.record),path:n.path},n)}catch(a){this.metrics.errors?.increment({[o]:!0}),i?.abort(a),n.signal?.aborted!==!0&&this.log.error("could not send %s to %p - %e",t.type,e,a),yield Ao({from:e,error:a,path:n.path},n)}finally{this.timeout.cleanUp(s)}}async*sendMessage(e,t,n){if(!this.running)return;let o=t.type;if(o==null)throw new E("Message type was missing");let i,s=this.timeout.getTimeoutSignal(n);n={...n,signal:s};try{this.metrics.operations?.increment({[o]:!0}),this.log("dialling %p",e),yield Cb({peer:e,path:n.path},n),i=await this.components.connectionManager.openStream(e,this.protocol,n),this.log("sending %s to %p",t.type,e),yield Tb({to:e,type:o,path:n.path},n),await this._writeMessage(i,t,n),i.close(n).catch(a=>{this.log.error("error closing stream to %p - %e",e,a),i?.abort(a)}),yield Dh({from:e,messageType:o,path:n.path},n)}catch(a){this.metrics.errors?.increment({[o]:!0}),i?.abort(a),yield Ao({from:e,error:a,path:n.path},n)}finally{this.timeout.cleanUp(s)}}async _writeMessage(e,t,n){await Xe(e).write(t,qs,n)}async _writeReadMessage(e,t,n){let o=Xe(e);await o.write(t,qs,n);let i=await o.read(qs,n);return i.closer.forEach(s=>{this.safeDispatchEvent("peer",{detail:Nh(s)})}),i.providers.forEach(s=>{this.safeDispatchEvent("peer",{detail:Nh(s)})}),i}};function To(r,e){if(r.length!==e.length)throw new Error("Inputs should have the same length");let t=Ec(r.length);for(let n=0;n<r.length;n++)t[n]=r[n]^e[n];return k3(t)}function zs(r,e){if(r.byteLength!==e.byteLength)throw new Error("Inputs should have the same length");for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}var Gs=class{originDhtKey;capacity;peerDistances;constructor(e,t){this.originDhtKey=e,this.capacity=t,this.peerDistances=[]}get length(){return this.peerDistances.length}get peers(){return[...this.peerDistances]}async add(e,t={index:-1,queued:0,running:0,total:0},n){let o=await Gr(e.id,n);this.addWithKadId(e,o,t)}addWithKadId(e,t,n={index:-1,queued:0,running:0,total:0}){if(this.peerDistances.find(s=>s.peer.id.equals(e.id))!=null)return;let o={peer:e,distance:To(this.originDhtKey,t),path:n};if(this.peerDistances.length===this.capacity){let s=this.peerDistances[this.peerDistances.length-1];if(s!=null&&zs(o.distance,s.distance)!==-1)return}let i=!1;for(let s=0;s<this.peerDistances.length;s++){let a=zs(this.peerDistances[s].distance,o.distance);if(a===0||a===1){i=!0,this.peerDistances.splice(s,0,o);break}}i||this.peerDistances.push(o),this.peerDistances=this.peerDistances.slice(0,this.capacity)}async isCloser(e,t){if(this.length===0)return!0;let n=await Gr(e,t),o=To(n,this.originDhtKey),i=this.peerDistances[this.peerDistances.length-1].distance;return zs(o,i)===-1}async anyCloser(e,t){return e.length===0?!1:Promise.any(e.map(async n=>this.isCloser(n,t)))}};var F3=class{log;routingTable;network;validators;queryManager;components;constructor(e,t){this.routingTable=t.routingTable,this.network=t.network,this.validators=t.validators,this.queryManager=t.queryManager,this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:peer-routing`),this.findPeer=e.metrics?.traceFunction("libp2p.kadDHT.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.kadDHT.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async findPeerLocal(e,t){let n,o=await this.routingTable.find(e,t);if(o!=null){this.log("findPeerLocal found %p in routing table",e);try{n=await this.components.peerStore.get(o,t)}catch(i){if(i.name!=="NotFoundError")throw i}}if(n==null)try{n=await this.components.peerStore.get(e,t)}catch(i){if(i.name!=="NotFoundError")throw i}if(n!=null)return this.log("findPeerLocal found %p in peer store",e),{id:n.id,multiaddrs:n.addresses.map(i=>i.multiaddr)}}async*_getValueSingle(e,t,n){let o={type:De.GET_VALUE,key:t};yield*this.network.sendRequest(e,o,n)}async*getPublicKeyFromNode(e,t={}){let n=gP(e),o={index:-1,queued:0,running:0,total:0};for await(let i of this._getValueSingle(e,n,{...t,path:o}))if(yield i,i.name==="PEER_RESPONSE"&&i.record!=null){let s=Et(i.record.value),a=zo(s);if(!a.equals(e))throw new ai("public key does not match id");if(a.publicKey==null)throw new ai("public key missing");yield Lh({from:e,value:i.record.value,path:o},t)}throw new $s(`Node not responding with its public key: ${e.toString()}`)}async*findPeer(e,t={}){if(this.log("findPeer %p",e),t.useCache!==!1){let o=await this.findPeerLocal(e,t);if(o!=null){this.log("found local"),yield C3({from:this.components.peerId,peer:o,path:{index:-1,queued:0,running:0,total:0}},t);return}}let n=!1;if(t.useNetwork!==!1){let o=this,i=async function*({peer:s,signal:a,path:c}){let l={type:De.FIND_NODE,key:e.toMultihash().bytes};for await(let u of o.network.sendRequest(s.id,l,{...t,signal:a,path:c}))if(yield u,u.name==="PEER_RESPONSE"){let d=u.closer.find(f=>f.id.equals(e));d!=null&&(yield C3({from:u.from,peer:d,path:u.path},t))}};for await(let s of this.queryManager.run(e.toMultihash().bytes,i,t))s.name==="FINAL_PEER"&&(n=!0),yield s}if(!n)throw new qe("Not found")}async*getClosestPeers(e,t={}){this.log("getClosestPeers to %b",e);let n=await Vs(e,t),o=new Gs(n,this.routingTable.kBucketSize),i=this,s=async function*({peer:a,path:c,peerKadId:l,signal:u}){i.log("getClosestPeers asking %p",a.id);let d={type:De.FIND_NODE,key:e};yield*i.network.sendRequest(a.id,d,{...t,signal:u,path:c}),o.addWithKadId(a,l,c)};yield*this.queryManager.run(e,s,t),this.log("found %d peers close to %b",o.length,e);for(let{peer:a,path:c}of o.peers)yield C3({from:this.components.peerId,peer:a,path:{index:c.index,queued:0,running:0,total:0}},t)}async*getValueOrPeers(e,t,n){for await(let o of this._getValueSingle(e,t,n)){if(o.name==="PEER_RESPONSE"&&o.record!=null)try{await this._verifyRecordOnline(o.record,n)}catch{let s="invalid record received, discarded";this.log(s),yield Ao({from:o.from,error:new $s(s),path:n.path},n);continue}yield o}}async _verifyRecordOnline(e,t){if(e.timeReceived==null)throw new A3("invalid record received");await Su(this.validators,new ft(e.key,e.value,e.timeReceived),t)}async getClosestPeersOffline(e,t){let n=[];try{let s=xe(e),a=bt(s),c=await this.components.peerStore.get(a,t);n.push({id:c.id,multiaddrs:c.addresses.map(({multiaddr:l})=>l)})}catch{}let o=await Vs(e,t),i=this.routingTable.closestPeers(o,t);for(let s of i)try{n.push(await this.components.peerStore.getInfo(s,t))}catch(a){if(a.name!=="NotFoundError")throw a}return n.length>0?this.log("getClosestPeersOffline returning the %d closest peer(s) we know to %b",n.length,e):this.log("getClosestPeersOffline could not any peers close to %b with %d peers in the routing table",e,this.routingTable.size),n}};var U3=class{log;datastore;datastorePrefix;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:providers`),this.datastorePrefix=`${t.datastorePrefix}/provider`,this.datastore=e.datastore}async addProvider(e,t,n){this.log.trace("%p provides %s",t,e),await this.writeProviderEntry(e,t,n)}async removeProvider(e,t,n){let o=D3(this.datastorePrefix,e,t);this.log.trace("%p no longer provides %s",t,e),await this.datastore.delete(o,n)}async getProviders(e,t){this.log.trace("get providers for %c",e);let n=await this.loadProviders(e,t);return this.log.trace("got %d providers for %c",n.size,e),[...n.keys()]}async writeProviderEntry(e,t,n){let o=D3(this.datastorePrefix,e,t),i=ur(n?.time?.getTime()??Date.now());await this.datastore.put(o,i,n)}async loadProviders(e,t){let n=new mr,o=D3(this.datastorePrefix,e);for await(let i of this.datastore.query({prefix:o.toString()},t)){let{peerId:s}=P3(i.key);n.set(s,L3(i.value))}return n}};async function*xP(r){let{key:e,startingPeers:t,ourPeerId:n,query:o,alpha:i,path:s,numPaths:a,log:c,peersSeen:l,connectionManager:u,signal:d}=r,f=Nt({objectMode:!0}),h=new vt({concurrency:i,sort:(y,g)=>zs(y.options.distance,g.options.distance)});h.addEventListener("idle",()=>{f.push(lP({path:{index:s,queued:h.queued,running:h.running,total:h.size}},r)),f.end()}),h.addEventListener("failure",y=>{c.error("error during query - %e",y.detail.error)});let p=()=>{h.abort(),f.end(new Tr)};d.addEventListener("abort",p);try{let g=function(m,b){if(m==null)return;l.add(m.id.toMultihash().bytes);let T=To(b,y);h.add(async()=>{try{for await(let R of o({...r,key:e,peer:m,path:{index:s,queued:h.queued,running:h.running,total:h.size},numPaths:a,peerKadId:b,signal:d})){if(R.name==="PEER_RESPONSE")for(let D of R.closer){if(l.has(D.id.toMultihash().bytes)){c("already seen %p in query",D.id);continue}if(n.equals(D.id)){c("not querying ourselves");continue}let O=await Gr(D.id,{signal:d}),U=To(O,y);if(zs(U,T)!==-1){c("skipping %p as they are not closer to %b than %p",D.id,e,m.id);continue}if(!await u.isDialable(D.multiaddrs,{signal:d})){c("not querying undialable peer");continue}c("querying closer peer %p",D.id),g(D,O)}f.push({...R,path:{index:s,queued:h.queued,running:h.running,total:h.size}})}}catch(R){f.push(Ao({from:m.id,error:R,path:{index:s,queued:h.queued,running:h.running-1,total:h.size-1}},r))}},{distance:T}).catch(R=>{c.error("error during query - %e",R)})},y=await Vs(e,{signal:d});await Promise.all(t.map(async m=>{g({id:m,multiaddrs:[]},await Gr(m,{signal:d}))})),yield*f}finally{d.removeEventListener("abort",p)}}var $3=class{disjointPaths;alpha;shutDownController;running;logger;peerId;connectionManager;routingTable;initialQuerySelfHasRun;logPrefix;allowQueryWithZeroPeers;constructor(e,t){this.logPrefix=t.logPrefix,this.disjointPaths=t.disjointPaths??S3,this.alpha=t.alpha??Us,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun,this.routingTable=t.routingTable,this.logger=e.logger,this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.allowQueryWithZeroPeers=t.allowQueryWithZeroPeers??!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.running=!1}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.shutDownController=new AbortController,this.shutDownController.signal,void 0)}async stop(){this.running=!1,this.shutDownController.abort()}async*run(e,t,n={}){if(!this.running)throw new Error("QueryManager not started");if(n.signal==null){let c=AbortSignal.timeout(iP);n={...n,signal:c}}let o=new AbortController,i=ae([this.shutDownController.signal,o.signal,n.signal]);o.signal;let s=this.logger.forComponent(`${this.logPrefix}:query:`+br(e,"base58btc")),a=!1;try{this.routingTable.size===0&&!this.allowQueryWithZeroPeers&&(s("routing table was empty, waiting for some peers before running%s query",n.isSelfQuery===!0?" self":""),await ke(this.routingTable,"peer:add",{signal:i,filter:h=>!this.peerId.equals(h.detail)}),s("routing table has peers, continuing with%s query",n.isSelfQuery===!0?" self":"")),n.isSelfQuery!==!0&&this.initialQuerySelfHasRun!=null&&(s("waiting for initial self query before continuing"),await Me(this.initialQuerySelfHasRun.promise,i),this.initialQuerySelfHasRun=void 0),s("query:start");let c=await Vs(e,{signal:i}),l=this.routingTable.closestPeers(c,{count:this.routingTable.kBucketSize}),u=l.sort(()=>Math.random()>.5?1:-1).reduce((h,p,y)=>(h[y%this.disjointPaths].push(p),h),new Array(this.disjointPaths).fill(0).map(()=>[])).filter(h=>h.length>0);if(l.length===0){s.error("running query with no peers");return}let d=Lt(1024),f=u.map((h,p)=>xP({...n,key:e,startingPeers:h,ourPeerId:this.peerId,signal:i,query:t,path:p,numPaths:u.length,alpha:this.alpha,log:s,peersSeen:d,onProgress:n.onProgress,connectionManager:this.connectionManager}));for await(let h of Rr(...f))h.name==="QUERY_ERROR"&&s.error("query error - %e",h.error),h.name==="PEER_RESPONSE"&&this.routingTable.queueRoutingTableUpdate(h.from),i.throwIfAborted(),yield h;a=!0}catch(c){if(this.running)throw c}finally{a||(s("query exited early"),o.abort()),i.clear(),s("query finished")}}};function pY(r){return r[Symbol.asyncIterator]!=null}function mY(r){if(pY(r))return(async()=>{let e=0;for await(let t of r)e++;return e})();{let e=0;for(let t of r)e++;return e}}var H3=mY;var q3=class{log;peerId;peerRouting;events;count;interval;initialInterval;queryTimeout;running;timeoutId;controller;initialQuerySelfHasRun;querySelfPromise;constructor(e,t){this.peerId=e.peerId,this.log=e.logger.forComponent(`${t.logPrefix}:query-self`),this.events=e.events,this.running=!1,this.peerRouting=t.peerRouting,this.count=t.count??S3,this.interval=t.interval??eP,this.initialInterval=t.initialInterval??tP,this.queryTimeout=t.queryTimeout??rP,this.initialQuerySelfHasRun=t.initialQuerySelfHasRun,this.querySelf=N3(this.querySelf.bind(this),t.operationMetrics,"SELF_QUERY")}isStarted(){return this.running}start(){this.running||(this.running=!0,clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.querySelf().catch(e=>{this.log.error("error running self-query - %e",e)})},this.initialInterval))}stop(){this.running=!1,this.timeoutId!=null&&clearTimeout(this.timeoutId),this.controller!=null&&this.controller.abort()}async querySelf(){if(!this.running){this.log("skip self-query because we are not started");return}if(this.querySelfPromise!=null)return this.log("joining existing self query"),this.querySelfPromise.promise;if(this.querySelfPromise=me(),this.running){this.controller=new AbortController;let e=[this.controller.signal];if(this.initialQuerySelfHasRun==null){let n=AbortSignal.timeout(this.queryTimeout);e.push(n)}let t=ae(e);this.controller.signal;try{this.log("run self-query, look for %d peers timing out after %dms",this.count,this.queryTimeout);let n=Date.now(),o=await on(this.peerRouting.getClosestPeers(this.peerId.toMultihash().bytes,{signal:t,isSelfQuery:!0}),s=>vs(s,this.count),async s=>H3(s));t?.throwIfAborted();let i=Date.now()-n;this.log("self-query found %d peers in %dms",o,i),this.events.dispatchEvent(new CustomEvent("kad-dht:query:self",{detail:{peers:o,duration:i}}))}catch(n){this.log.error("self-query error - %e",n)}finally{t.clear(),this.initialQuerySelfHasRun!=null&&(this.initialQuerySelfHasRun.resolve(),this.initialQuerySelfHasRun=void 0)}}this.querySelfPromise.resolve(),this.querySelfPromise=void 0,this.running&&(this.timeoutId=setTimeout(()=>{this.querySelf().catch(e=>{this.log.error("error running self-query - %e",e)})},this.interval))}};var V3=class extends se{log;reprovideQueue;maxQueueSize;datastore;timeout;reprovideTimeout;running;shutdownController;reprovideThreshold;contentRouting;datastorePrefix;addressManager;validity;interval;peerId;constructor(e,t){super(),this.log=e.logger.forComponent(`${t.logPrefix}:reprovider`),this.peerId=e.peerId,this.reprovideQueue=new vt({concurrency:t.concurrency??XR,metrics:e.metrics,metricName:`${t.metricsPrefix}_reprovide_queue`}),this.reprovideTimeout=new ho({...t.timeout??{},metrics:e.metrics,metricName:`${t.metricsPrefix}_reprovide_timeout_milliseconds`}),this.datastore=e.datastore,this.addressManager=e.addressManager,this.datastorePrefix=`${t.datastorePrefix}/provider`,this.reprovideThreshold=t.threshold??YR,this.maxQueueSize=t.maxQueueSize??QR,this.validity=t.validity??v3,this.interval=t.interval??ZR,this.contentRouting=t.contentRouting,this.running=!1,this.reprovide=N3(this.reprovide.bind(this),t.operationMetrics,"PROVIDE")}start(){this.running||(this.running=!0,this.shutdownController=new AbortController,this.shutdownController.signal,this.timeout=setTimeout(()=>{this.processRecords({signal:AbortSignal.timeout(xb)}).catch(e=>{this.log.error("error running process to reprovide/cleanup - %e",e)})},this.interval))}stop(){this.running=!1,this.reprovideQueue.clear(),clearTimeout(this.timeout),this.shutdownController?.abort()}async processRecords(e){try{this.safeDispatchEvent("reprovide:start"),this.log("starting reprovide/cleanup");for await(let t of this.datastore.query({prefix:this.datastorePrefix},e))try{let{cid:n,peerId:o}=P3(t.key),s=L3(t.value).getTime()+this.validity,a=Date.now(),c=a>s,l=this.peerId.equals(o);this.log.trace("comparing: %d (now) < %d (expires) = %s %s",a,s,c,c?"(expired)":"(valid)"),c&&!l&&await this.datastore.delete(t.key,e),this.shouldReprovide(l,s)&&(this.log("reproviding %c as it is within the reprovide threshold (%d)",n,this.reprovideThreshold),this.queueReprovide(n).catch(u=>{this.log.error("could not reprovide %c - %e",n,u)}))}catch(n){this.log.error("error processing datastore key %s - %s",t.key,n.message)}this.log("reprovide/cleanup successful")}finally{this.safeDispatchEvent("reprovide:end"),this.running&&(this.log("queuing next re-provide/cleanup run in %d ms",this.interval),this.timeout=setTimeout(()=>{this.processRecords({signal:AbortSignal.timeout(xb)}).catch(t=>{this.log.error("error running re-provide - %e",t)})},this.interval))}}shouldReprovide(e,t){if(!e)return!1;let n=Date.now();return t<n?!0:t-n<this.reprovideThreshold}async queueReprovide(e,t){if(!this.running)return;this.log.trace("waiting for queue capacity before adding %c to re-provide queue",e),await this.reprovideQueue.onSizeLessThan(this.maxQueueSize,t);let n=this.reprovideQueue.queue.find(o=>o.options.cid.equals(e));if(n!=null)return this.log.trace("not adding %c to re-provide queue - already in queue",e),n.join();this.log.trace("adding %c to re-provide queue",e),this.reprovideQueue.add(async o=>{if(o.signal?.throwIfAborted(),!this.running)return;this.log.trace("re-providing %c",e);let i=this.reprovideTimeout.getTimeoutSignal(o);try{await this.reprovide(o.cid,o)}finally{this.reprovideTimeout.cleanUp(i)}this.log.trace("re-provided %c",e)},{signal:this.shutdownController?.signal,cid:e}).catch(o=>{this.log.error("could not re-provide key %c - %e",e,o)})}async reprovide(e,t){await pr(this.contentRouting.provide(e,this.addressManager.getAddresses(),t))}};var gY=20,yY=5e3,wY="kad-close",bY=50,K3=class{routingTable;components;closestPeers;newPeers;refreshInterval;peerSetSize;timeout;closeTagName;closeTagValue;log;running;constructor(e,t){this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:routing-table`),this.routingTable=t.routingTable,this.refreshInterval=t.refreshInterval??yY,this.peerSetSize=t.peerSetSize??gY,this.closeTagName=t.closeTagName??wY,this.closeTagValue=t.closeTagValue??bY,this.closestPeers=new fn,this.onPeerPing=this.onPeerPing.bind(this),this.running=!1}async start(){if(this.running)return;this.running=!0;let e=await Gr(this.components.peerId);this.newPeers=new Gs(e,this.peerSetSize),this.routingTable.addEventListener("peer:ping",this.onPeerPing),this.timeout=setInterval(()=>{this.updatePeerTags().catch(t=>{this.log.error("error updating peer tags - %e",t)})},this.refreshInterval)}stop(){this.running=!1,this.routingTable.removeEventListener("peer:ping",this.onPeerPing),clearTimeout(this.timeout)}onPeerPing(e){this.newPeers?.add({id:e.detail,multiaddrs:[]}).catch(t=>{this.log.error("error adding peer to distance list - %e",t)})}async updatePeerTags(){let e=new fn(this.newPeers?.peers.map(({peer:o})=>o.id)),t=e.difference(this.closestPeers),n=this.closestPeers.difference(e);this.closestPeers=e,await Promise.all([...[...t].map(async o=>{await this.components.peerStore.merge(o,{tags:{[this.closeTagName]:{value:this.closeTagValue},[Eb]:{value:1}}})}),...[...n].map(async o=>{await this.components.peerStore.merge(o,{tags:{[this.closeTagName]:void 0,[Eb]:void 0}})})])}};function Oh(r){return Array.isArray(r?.peers)}var z3=class{peerId;root;localPeer;prefixLength;splitThreshold;kBucketSize;numberOfNodesToPing;lastPingThreshold;ping;verify;onAdd;onRemove;onMove;addingPeerMap;constructor(e,t){this.peerId=e.peerId,this.prefixLength=t.prefixLength??EP,this.kBucketSize=t.kBucketSize??Bh,this.splitThreshold=t.splitThreshold??this.kBucketSize,this.numberOfNodesToPing=t.numberOfOldContactsToPing??vP,this.lastPingThreshold=t.lastPingThreshold??SP,this.ping=t.ping,this.verify=t.verify,this.onAdd=t.onAdd,this.onRemove=t.onRemove,this.addingPeerMap=Ai({name:`${t.metricsPrefix}_adding_peer_map`,metrics:e.metrics}),this.root={prefix:"",depth:0,peers:[]}}async start(){await this.addSelfPeer(this.peerId)}stop(){this.addingPeerMap.clear(),this.root={prefix:"",depth:0,peers:[]}}async addSelfPeer(e,t){this.localPeer={peerId:e,kadId:await Gr(e,t),lastPing:Date.now()}}async add(e,t){let n={peerId:e,kadId:await Gr(e,t),lastPing:0},o=this.addingPeerMap.get(e);if(o!=null)return o;try{let i=this._add(n,t);this.addingPeerMap.set(e,i),await i}finally{this.addingPeerMap.delete(e)}}async _add(e,t){let n=this._determineBucket(e.kadId);if(this._indexOf(n,e.kadId)>-1)return;if(n.peers.length===this.splitThreshold&&n.depth<this.prefixLength){await this._split(n,t),await this._add(e,t);return}if(n.peers.length<this.kBucketSize){if(!EY(e,this.lastPingThreshold)){n.peers.push(e),await this.onAdd?.(e,n,t);return}await this.verify(e,t)&&(e.lastPing=Date.now(),await this._add(e,t));return}let o=n.peers.filter(s=>!(s.peerId.equals(this.localPeer?.peerId)||s.lastPing>Date.now()-this.lastPingThreshold)).sort((s,a)=>s.lastPing<a.lastPing?-1:s.lastPing>a.lastPing?1:0).slice(0,this.numberOfNodesToPing),i=!1;for await(let s of this.ping(o,t))i=!0,await this.remove(s.kadId,t);i&&await this._add(e,t)}*closest(e,t){let n=new Gs(e,t?.count??this.kBucketSize);for(let o of this.toIterable())t?.exclude?.some(i=>i.equals(o.peerId))!==!0&&n.addWithKadId({id:o.peerId,multiaddrs:[]},o.kadId);yield*Ct(n.peers,({peer:o})=>o.id)}count(){function e(t){if(Oh(t))return t.peers.length;let n=0;return t.left!=null&&(n+=e(t.left)),t.right!=null&&(n+=e(t.right)),n}return e(this.root)}get(e){let t=this._determineBucket(e),n=this._indexOf(t,e);return t.peers[n]}async remove(e,t){let n=this._determineBucket(e),o=this._indexOf(n,e);if(o>-1){let i=n.peers.splice(o,1)[0];await this.onRemove?.(i,n,t)}}*toIterable(){function*e(t){if(Oh(t)){yield*t.peers;return}yield*e(t.left),yield*e(t.right)}yield*e(this.root)}distance(e,t){return BigInt("0x"+br(To(e,t),"base16"))}_determineBucket(e){let t=br(e,"base2");function n(o,i=0){return Oh(o)?o:t[i]==="0"?n(o.left,i+1):n(o.right,i+1)}return n(this.root)}_indexOf(e,t){return e.peers.findIndex(n=>So(n.kadId,t))}async _split(e,t){let n={prefix:"0",depth:e.depth+1,peers:[]},o={prefix:"1",depth:e.depth+1,peers:[]};for(let i of e.peers)br(i.kadId,"base2")[e.depth]==="0"?(n.peers.push(i),await this.onMove?.(i,e,n,t)):(o.peers.push(i),await this.onMove?.(i,e,o,t));xY(e,n,o)}};function xY(r,e,t){return delete r.peers,r.left=e,r.right=t,r.prefix===""&&(delete r.depth,delete r.prefix),!0}function EY(r,e){return r.lastPing<Date.now()-e}var Bh=20,EP=6;var vY=20,SY=100,AY=16,TY=16384,vP=3;var _Y=20,CY=100,AP="kad-peer",IY=1,SP=6e5,kY=!0,RY=1e3,G3=class extends se{kBucketSize;kb;network;closestPeerTagger;log;components;running;pingNewContactTimeout;pingNewContactQueue;pingOldContactTimeout;pingOldContactQueue;routingTableUpdateQueue;populateFromDatastoreOnStart;populateFromDatastoreLimit;protocol;peerTagName;peerTagValue;metrics;shutdownController;constructor(e,t){super(),this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:routing-table`),this.kBucketSize=t.kBucketSize??Bh,this.running=!1,this.protocol=t.protocol,this.network=t.network,this.peerTagName=t.peerTagName??AP,this.peerTagValue=t.peerTagValue??IY,this.pingOldContacts=this.pingOldContacts.bind(this),this.verifyNewContact=this.verifyNewContact.bind(this),this.peerAdded=this.peerAdded.bind(this),this.peerRemoved=this.peerRemoved.bind(this),this.populateFromDatastoreOnStart=t.populateFromDatastoreOnStart??kY,this.populateFromDatastoreLimit=t.populateFromDatastoreLimit??RY,this.shutdownController=new AbortController,this.shutdownController.signal,this.routingTableUpdateQueue=new Gt({concurrency:t.routingTableUpdateQueueConcurrency??AY,metricName:`${t.metricsPrefix}_routing_table_update_queue`,metrics:this.components.metrics,maxSize:t.routingTableUpdateMaxQueueSize??TY}),this.pingOldContactQueue=new Gt({concurrency:t.pingOldContactConcurrency??_Y,metricName:`${t.metricsPrefix}_ping_old_contact_queue`,metrics:this.components.metrics,maxSize:t.pingOldContactMaxQueueSize??CY}),this.pingOldContactTimeout=new ho({...t.pingOldContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_old_contact_time_milliseconds`}),this.pingNewContactQueue=new Gt({concurrency:t.pingNewContactConcurrency??vY,metricName:`${t.metricsPrefix}_ping_new_contact_queue`,metrics:this.components.metrics,maxSize:t.pingNewContactMaxQueueSize??SY}),this.pingNewContactTimeout=new ho({...t.pingNewContactTimeout??{},metrics:this.components.metrics,metricName:`${t.metricsPrefix}_routing_table_ping_new_contact_time_milliseconds`}),this.kb=new z3(e,{kBucketSize:t.kBucketSize,prefixLength:t.prefixLength,splitThreshold:t.splitThreshold,numberOfOldContactsToPing:t.numberOfOldContactsToPing,lastPingThreshold:t.lastPingThreshold,ping:this.pingOldContacts,verify:this.verifyNewContact,onAdd:this.peerAdded,onRemove:this.peerRemoved,metricsPrefix:t.metricsPrefix}),this.closestPeerTagger=new K3(this.components,{logPrefix:t.logPrefix,routingTable:this,peerSetSize:t.closestPeerSetSize,refreshInterval:t.closestPeerSetRefreshInterval,closeTagName:t.closeTagName,closeTagValue:t.closeTagValue}),this.components.metrics!=null&&(this.metrics={routingTableSize:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_size`),routingTableKadBucketTotal:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_total`),routingTableKadBucketAverageOccupancy:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_average_occupancy`),routingTableKadBucketMinOccupancy:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_min_occupancy`),routingTableKadBucketMaxOccupancy:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_max_occupancy`),routingTableKadBucketMaxDepth:this.components.metrics.registerMetric(`${t.metricsPrefix}_routing_table_kad_bucket_max_depth`),kadBucketEvents:this.components.metrics.registerCounterGroup(`${t.metricsPrefix}_kad_bucket_events_total`)})}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.shutdownController=new AbortController,this.shutdownController.signal,await Rt(this.closestPeerTagger,this.kb))}async afterStart(){let e=0;Promise.resolve().then(async()=>{if(!this.populateFromDatastoreOnStart)return;let t=ae([this.shutdownController.signal,AbortSignal.timeout(2e4)]);try{for(let n of await this.components.peerStore.all({filters:[o=>o.protocols.includes(this.protocol)&&o.tags.has(AP)],limit:this.populateFromDatastoreLimit,signal:t})){if(!this.running)return;try{await this.add(n.id,{signal:t}),e++}catch{this.log("failed to add peer %p to routing table, removing kad-dht peer tags - %e"),await this.components.peerStore.merge(n.id,{tags:{[this.peerTagName]:void 0}})}}}finally{t.clear()}this.log("added %d peer store peers to the routing table",e)}).catch(t=>{this.log.error("error adding %d, peer store peers to the routing table - %e",e,t)})}async stop(){this.running=!1,await Ut(this.closestPeerTagger,this.kb),this.routingTableUpdateQueue.abort(),this.pingOldContactQueue.abort(),this.pingNewContactQueue.abort(),this.shutdownController.abort()}queueRoutingTableUpdate(e,t={}){let n=this.routingTableUpdateQueue.find(e);if(n!=null){n.join(t).catch(()=>{});return}this.routingTableUpdateQueue.add(async o=>{let i=o,s;t.activeTimeout!=null&&(s=ae([o.signal,AbortSignal.timeout(t.activeTimeout)]),i={...o,signal:s});try{await this.add(e,i)}finally{s?.clear()}},{peerId:e,signal:this.shutdownController.signal}).catch(o=>{this.shutdownController.signal.aborted||o?.name==="AbortError"||this.log.error("could not update routing table for peer %p - %e",e,o)})}async peerAdded(e,t,n){this.components.peerId.equals(e.peerId)||await this.components.peerStore.merge(e.peerId,{tags:{[this.peerTagName]:{value:this.peerTagValue}}},n),this.updateMetrics(),this.metrics?.kadBucketEvents.increment({peer_added:!0}),this.safeDispatchEvent("peer:add",{detail:e.peerId})}async peerRemoved(e,t,n){this.components.peerId.equals(e.peerId)||await this.components.peerStore.merge(e.peerId,{tags:{[this.peerTagName]:void 0}},n),this.updateMetrics(),this.metrics?.kadBucketEvents.increment({peer_removed:!0}),this.safeDispatchEvent("peer:remove",{detail:e.peerId})}async*pingOldContacts(e,t){if(!this.running)return;let n=[];for(let o of e){if(this.kb.get(o.kadId)==null){this.log("asked to ping contact %p that was not in routing table",o.peerId);continue}this.metrics?.kadBucketEvents.increment({ping_old_contact:!0}),n.push(async()=>{let i=this.pingOldContactQueue.find(o.peerId);if(i!=null)return this.log("asked to ping contact %p was already being pinged",o.peerId),await i.join(t)?void 0:o;if(!await this.pingOldContactQueue.add(async a=>{let c=this.pingOldContactTimeout.getTimeoutSignal(),l=ae([c,this.shutdownController.signal,a?.signal]);try{return await this.pingContact(o,a)}catch{return this.metrics?.kadBucketEvents.increment({ping_old_contact_error:!0}),!0}finally{this.pingOldContactTimeout.cleanUp(c),l.clear()}},{peerId:o.peerId,signal:t?.signal}))return o})}for await(let o of yn(n))o!=null&&(yield o)}async verifyNewContact(e,t){let n=this.pingNewContactTimeout.getTimeoutSignal(),o=ae([n,this.shutdownController.signal,t?.signal]);try{let i=this.pingNewContactQueue.find(e.peerId);return i!=null?(this.log("joining existing ping to add new peer %p to routing table",e.peerId),await i.join({signal:o})):await this.pingNewContactQueue.add(async s=>(this.metrics?.kadBucketEvents.increment({ping_new_contact:!0}),this.log("pinging new peer %p before adding to routing table",e.peerId),this.pingContact(e,s)),{peerId:e.peerId,signal:o})}catch{return this.log.trace("tried to add peer %p but they were not online",e.peerId),this.metrics?.kadBucketEvents.increment({ping_new_contact_error:!0}),!1}finally{this.pingNewContactTimeout.cleanUp(n),o.clear()}}async pingContact(e,t){let n;try{return this.log("pinging contact %p",e.peerId),await this.components.ping.ping(e.peerId,t),this.log("contact %p ping ok",e.peerId),this.safeDispatchEvent("peer:ping",{detail:e.peerId}),!0}catch(o){return this.log("error pinging old contact %p - %e",e.peerId,o),n?.abort(o),!1}}get size(){return this.kb==null?0:this.kb.count()}async find(e,t){let n=await Gr(e,t);return this.kb.get(n)?.peerId}closestPeer(e){let t=this.closestPeers(e,{count:1});if(t.length>0)return t[0]}closestPeers(e,t){return this.kb==null?[]:[...this.kb.closest(e,t)]}async add(e,t){if(this.kb==null)throw new Error("RoutingTable is not started");await this.kb.add(e,t)}async remove(e,t){if(this.kb==null)throw new Error("RoutingTable is not started");let n=await Gr(e,t);await this.kb.remove(n,t)}updateMetrics(){if(this.metrics==null||this.kb==null)return;let e=0,t=0,n=0,o=20,i=0;function s(a){if(Oh(a)){a.depth>n&&(n=a.depth),t++,e+=a.peers.length,a.peers.length<o&&(o=a.peers.length),a.peers.length>i&&(i=a.peers.length);return}s(a.left),s(a.right)}s(this.kb.root),this.metrics.routingTableSize.update(e),this.metrics.routingTableKadBucketTotal.update(t),this.metrics.routingTableKadBucketAverageOccupancy.update(Math.round(e/t)),this.metrics.routingTableKadBucketMinOccupancy.update(o),this.metrics.routingTableKadBucketMaxOccupancy.update(i),this.metrics.routingTableKadBucketMaxDepth.update(n)}};var TP=[77591,22417,43971,28421,740,29829,71467,228973,196661,78537,27689,36431,44415,14362,19456,106025,96308,2882,49509,21149,87173,131409,75844,23676,121838,30291,17492,2953,7564,110620,129477,127283,53113,72417,165166,109690,21200,102125,24049,71504,90342,25307,72039,26812,26715,32264,133800,71161,88956,171987,51779,24425,16671,30251,186294,247761,14202,2121,8465,35024,4876,85917,169730,3638,256836,96184,943,18678,6583,52907,35807,112254,214097,18796,11595,9243,23554,887,268203,382004,24590,111335,11625,16619,29039,102425,69006,97976,92362,32552,63717,41433,128974,137630,59943,10019,13986,35430,33665,108037,43799,43280,38195,29078,58629,18265,14425,46832,235538,40830,77881,110717,58937,3463,325358,51300,47623,117252,19007,10170,20540,91237,294813,4951,79841,56232,36270,128547,69209,66275,100156,32063,73531,34439,80937,28892,44466,88595,216307,32583,49620,16605,82127,45807,21630,78726,20235,40163,111007,96926,5567,72083,21665,58844,39419,179767,48328,42662,51550,5251,37811,49608,81056,50854,55513,20922,18891,197409,164656,32593,71449,220474,58919,85682,67854,13758,35066,3565,61905,214793,119572,141419,21504,10302,27354,67003,46131,32668,15165,64871,34450,17821,2757,11452,34189,5160,12257,85523,560,53385,65887,119549,135620,312353,115979,122356,10867,193231,124537,54783,90675,120791,4715,142253,50943,17271,43358,25331,4917,120566,34580,12878,33786,160528,32523,4869,301307,104817,81491,23276,8832,97911,31265,52065,7998,49622,9715,43998,34091,84587,20664,69041,29419,53205,10838,58288,116145,6185,5154,141795,35924,21307,144738,43730,12085,8279,10002,119,133779,199668,72938,31768,39176,67875,38453,9700,44144,4121,116048,41733,12868,82669,92308,128,34262,11332,7712,90764,36141,13553,71312,77470,117314,96549,49135,23602,54468,28605,6327,62308,17171,67531,21319,14105,894,107722,46157,8503,51069,100472,45138,15246,14577,35609,191464,1757,13364,161349,32067,91705,81144,52339,5408,91066,21983,14157,100545,4372,26630,129112,1423,29676,213626,4397,88436,99190,6877,49958,26122,114348,60661,29818,293118,50042,179738,16400,163423,89627,31040,43973,36638,45952,5153,1894,109322,1898,134021,12402,112077,68309,190269,69866,31938,107383,11522,105232,11248,14868,39852,71707,186525,16530,38162,106212,11700,5130,16608,26998,59586,108399,230033,43683,48135,82179,2073,5015,196684,189293,16378,23452,8301,35640,11632,214551,29240,57644,33137,91949,55157,52384,117313,5090,17717,89668,49363,82238,241035,66216,29066,184088,97206,62820,26595,4241,135635,173672,8202,459,71355,146294,29587,3008,135385,141203,14803,6634,45094,69362,50925,546,51884,62011,83296,234584,44515,56050,89476,87751,19373,12691,149923,19794,13833,35846,87557,58339,2884,19145,25647,12224,11024,77338,64608,122297,53025,7205,36189,36294,170779,21750,7739,173883,75192,35664,224240,113121,30181,26267,27036,117827,92015,106516,55628,203549,67949,60462,60844,35911,20457,1820,920,19773,8738,73173,181993,38521,98254,76257,46008,92796,5384,26868,151566,22124,2411,15919,186872,180021,28099,152961,78811,80237,62352,102653,74259,184890,16792,123702,224945,29940,19512,75283,14059,112691,92811,233329,20411,138569,53341,109802,50600,134528,66747,5529,166531,31578,64732,67189,1596,126357,967,167999,206598,109752,119431,207825,78791,91938,10301,27311,24233,252343,28831,32812,66002,112267,90895,8786,8095,16824,22866,21813,60507,174833,19549,130985,117051,52110,6938,81923,123864,38061,919,18680,53534,46739,112893,161529,85429,26761,11900,81121,91968,15390,217947,56524,1713,6654,37089,85630,138866,61850,16491,75577,16884,98296,73523,6140,44645,6062,36366,29844,57946,37932,42472,5266,20834,19309,33753,127182,134259,35810,41805,45878,312001,14881,47757,49251,120050,44252,3708,25856,107864,120347,1228,36550,41682,34496,47025,8393,173365,246526,12894,161607,35670,90785,126572,2095,124731,157033,58694,554,12786,9642,4817,16136,47864,174698,66992,4639,69284,10625,40710,27763,51738,30404,264105,137904,109882,52487,42824,57514,2740,10479,146799,107390,16586,88038,174951,9410,16185,44158,5568,40658,46108,12763,97385,26175,108859,664,230732,67470,46663,14395,50750,141320,93140,15361,47997,55784,6791,307840,118569,107326,18056,58281,260415,54691,8790,73332,45633,7511,45674,143373,14031,11799,94491,35646,96544,14560,26049,32983,25791,83814,42094,231370,63955,139212,2359,169908,3108,183486,105867,28197,32941,124968,26402,88267,149768,23053,3078,19091,52924,25383,19209,111548,97361,3959,24880,235061,9099,24921,161254,151405,20508,7159,34381,20133,11434,74036,19974,34769,36585,1076,22454,17354,38727,235160,111547,96454,117448,156940,91330,37299,7310,26915,117060,51369,22620,61861,322264,106850,111694,15091,2624,40345,300446,177064,1707,27389,54792,327783,132669,183543,59003,17744,20603,151134,106923,53084,71803,279424,319816,11579,21946,16728,38274,72711,5085,83391,88646,40159,25027,34680,10752,12988,54126,30365,18338,100445,230674,44874,84974,143877,123253,139372,28082,91477,144002,13096,219729,46016,50029,42377,14601,6660,58244,58978,23918,88206,113611,64452,17541,41032,10942,12021,49189,10978,40175,37156,10947,71709,106894,112538,57007,137486,150608,152719,40615,7746,279716,13101,19524,28708,40578,72320,1096,182051,94527,51275,22833,45164,81917,77519,48508,5421,140302,37845,149830,5587,27579,5357,428725,248187,6326,206760,39814,32585,89923,44341,288753,284443,96368,31201,94189,119504,20359,52073,103216,179,27934,32801,96035,34111,34309,101326,18198,20704,210266,37643,27880,141873,106e3,19414,56614,167714,66483,107885,86602,4379,20796,75467,4987,5017,118857,26003,34308,114428,29198,6686,29697,73632,3739,69795,16798,41504,7207,30722,21436,36735,28067,28545,3239,11221,36031,41889,100010,19247,317673,29495,174554,6424,129725,53845,94986,7955,59676,2604,191497,19735,102214,62954,23844,11872,179525,261436,34492,428,78404,142035,16747,17246,27578,37021,33672,57944,26056,135760,2369,61674,122066,31327,19374,157065,40553,130982,69619,71290,38855,72100,92903,95940,51422,165999,65713,57873,50726,7288,20272,2081,42326,22624,81120,57914,79352,19447,1684,72302,11774,302559,161481,96396,13692,414988,3721,79066,56627,46883,21150,11747,12184,5856,113458,176117,84416,52079,27933,3354,59765,141359,2212,216309,2555,23458,196722,142463,45701,44548,28798,19418,215,29916,9396,10574,114226,84475,13520,18694,34056,4524,90302,62930,13539,19407,77209,7728,38088,9535,2263,23875,183945,17750,26274,67172,10585,28042,22199,7478,51331,66030,26774,192929,31434,25850,50197,52926,178158,4679,181256,70184,229600,9959,105594,72158,73974,2726,35085,78087,23284,35568,51713,155676,5401,27254,11966,17569,223253,71993,103357,111477,55722,30504,26034,46774,35392,36285,214814,41143,163465,1051,16094,81044,6636,76489,179102,20712,39178,35683,125177,54219,30617,52994,25324,50123,2543,87529,58995,10688,125199,12388,60158,125481,131646,7642,133350,65874,3438,97277,101450,10075,56344,116821,50778,60547,98016,106135,13859,14255,16300,77373,173521,8285,45932,37426,4054,114295,55947,7703,39114,52,51119,128135,19714,60715,9554,50492,88180,2823,118271,52993,122625,97919,23859,37895,25040,33614,32102,20431,3577,9275,15686,43031,157741,110358,1884,40291,125391,13736,5008,64881,87336,77381,70711,43032,49155,118587,70494,4318,10168,30126,12580,10524,280104,104001,145413,2862,84140,6603,106005,13566,12780,11251,42830,571,179910,82443,13146,469,42714,32591,265217,424024,92553,54721,134100,6007,15242,114681,59030,16718,85465,200214,85982,55174,165013,23493,56964,82529,109150,32706,27568,82442,5350,14976,13165,44890,60021,21343,33978,17264,4655,22328,27819,75730,16567,55483,14510,17926,45827,150609,3704,7385,272531,161543,76904,122163,52405,2039,19165,41623,14423,228354,3369,176360,85491,7122,35789,303724,4465,13628,2233,55311,118771,20713,10006,221519,45115,71021,35650,29775,7337,10864,20665,21142,1746,15080,1624,32449,10905,105743,229797,7701,3940,22997,178467,57208,389057,39683,59403,63344,63125,54847,69691,18336,56448,3362,37202,18282,29648,138224,35867,10495,5911,28814,26653,31514,176702,26550,45621,11734,4525,40543,73944,121080,27858,155561,14887,44670,30742,8796,107455,113472,56369,75581,183777,240095,133699,153299,8768,160464,26058,49078,103971,21875,71486,44888,17156,9678,89541,123019,102337,3972,83930,21245,87852,109660,287918,183019,686,10100,39177,283941,11274,24736,26793,26214,25995,77011,141580,4070,23742,46285,46632,30700,26669,19056,35951,115575,174034,56097,35463,87425,24575,44245,38701,82317,85922,281616,100333,147697,61503,7730,84330,8530,59917,61597,17173,9092,32658,90288,193136,39023,20381,56654,31132,7779,1919,1375,117128,30819,11169,40938,23935,115201,101155,151034,4835,11231,74550,89388,59951,91704,107312,167882,115062,12732,72738,88703,464019,158267,57995,60496,737,14371,123867,4174,243339,159946,7568,16025,134556,110916,38103,191,80226,88794,29688,27230,10454,76308,57647,77409,113483,66864,14745,19808,12023,46583,84805,16015,17102,2231,20611,3547,95740,250131,34559,108894,8498,15853,159169,148920,20942,2813,93160,45188,210613,45531,52587,149062,39782,28194,57849,60965,84954,89766,84453,100927,16501,27658,165311,103841,54192,207341,19558,20084,319622,5672,205467,98462,61849,36279,13609,147177,24726,165015,209489,59591,31157,6551,117580,75060,141146,277310,21072,22023,106474,63041,137443,122965,68371,5383,42146,98961,113467,30863,23794,4843,99630,30392,82679,13699,241612,33601,93146,24319,18643,32155,95669,40440,15333,34089,67799,142144,58245,38633,114531,117400,77861,188726,5507,2568,8853,10987,107222,2663,2421,11530,13345,30075,41785,118661,104786,17459,12490,16281,71936,193555,17431,5944,71758,26485,77317,20803,367167,158,7362,93430,11735,172445,46002,11532,54482,930,62911,2235,23004,179236,4764,101859,208113,22477,55163,95579,14098,67320,162556,90709,156949,3826,57492,4025,34092,87442,104565,6718,186015,28214,14209,10039,107186,233912,58877,81637,55265,39828,6194,145813,50831,105849,4974,88319,122296,10272,197216,95714,51540,72418,23324,91555,8743,140452,250249,51666,34124,7229,38592,129641,78169,174242,22464,149964,51450,14034,10026,95376,26190,120062,14401,8700,265,31386,143573,7203,229889,61567,4227,140981,2466,72052,10787,10062,30958,6099,38471,30103,23202,208101,70847,467,58934,32271,32984,36637,24107,30771,17109,73353,13650,2098,157040,67366,66904,106018,265380,107238,18535,44025,32681,144983,62505,91295,56120,3082,77508,10322,63023,36700,81885,224127,16721,45023,239261,111272,13852,7866,149243,204199,32309,22084,42029,38316,126644,104973,14406,43454,67322,61310,15789,40285,24026,181047,6301,70927,23319,115823,27248,66693,115875,278566,63007,146844,56841,59007,87368,180001,22370,42114,80605,12022,10374,308,25079,14689,12618,63368,7936,264973,212291,136713,95999,105801,18965,32075,48700,52230,35119,96912,32992,8586,16606,101333,101812,14969,39930,759,193090,27387,42914,12937,5058,62646,64528,38624,25743,37502,3716,4435,30352,178687,26461,132611,42002,138442,35833,59582,16345,8048,60319,49349,309,47800,49739,90482,26405,34470,63786,32479,85028,39866,47846,11649,23934,29466,2816,42864,31828,7410,74885,49632,47629,111801,90749,19536,18767,105764,59606,21223,10746,76298,22220,39408,7190,79654,64856,11602,82156,272765,17079,70089,245473,51813,184407,384678,1576,122249,5064,27481,6188,25790,74361,27541,318284,45430,31488,620,93579,45723,192118,22670,51913,4162,70244,35966,26397,16199,50899,209613,121702,287507,2993,36101,132229,67345,33062,76295,118628,78705,52316,34375,107083,107454,44863,127561,33964,3073,154010,190914,55967,39074,6272,31047,5550,41123,26154,98638,47110,19998,148091,50229,31329,59900,195442,19106,61347,73497,70015,682,45850,25776,38022,148951,6288,37411,232526,109277,27286,32342,9262,5220,16651,23175,46740,129438,78614,121925,66914,88710,127952,5563,21500,34521,10739,14863,191006,62956,17359,16749,67027,56284,69134,43301,35039,58883,54466,60823,404451,75743,59856,86979,7923,34273,83785,32142,7693,268986,197428,282681,17049,22346,22990,92245,107180,3357,37104,96724,49153,7683,31197,43267,82231,164276,23696,20848,188364,22309,24821,158707,1018,22514,70922,27792,45589,59709,10765,736,35218,63479,51987,24275,63588,55361,92929,81964,4658,20122,12330,44058,13065,311456,72224,8337,211229,38979,22590,138478,52757,32595,133600,8838,31549,94412,43391,90056,1585,94802,127271,6223,31889,137038,132910,2165,57616,230152,6080,10748,36737,74579,134062,50525,180532,119270,34556,76155,82394,52595,29258,31435,87820,67996,26943,183878,38007,2410,13526,180297,69856,3503,187396,167700,7838,16701,9199,56267,3661,37407,65994,23767,5708,62508,221700,67088,86978,46776,84434,32088,5612,9149,88244,21685,95151,46750,189612,2979,506311,2594,3628,40074,105039,78243,28523,6651,38058,71999,30992,12764,68261,108991,6165,26450,61961,13400,22426,7490,60890,109623,2070,12958,50355,67979,257096,7213,42578,52121,35716,65461,7516,124758,39268,302,64712,14977,1467,219452,2840,34229,11121,21602,19270,63574,8024,1532,17331,79839,78885,52029,180767,57957,6069,91265,61380,55767,8927,32881,287603,22149,35029,68876,6428,199567,46926,13412,104132,21434,366616,45060,110046,81924,128910,45886,52821,130416,29416,77342,21762,67329,121432,79924,11724,38625,81006,102033,28338,13326,3250,82056,82526,38212,21112,12382,111495,3263,7414,86274,93490,40844,30224,45212,24019,48411,71367,24941,76729,57776,3769,38114,202019,197745,31953,237533,33270,201580,255648,100798,44741,32241,98468,106931,10085,15090,170358,33154,66787,18819,69760,25061,234005,82660,6295,131975,16874,9076,4094,25005,17740,40908,19533,220019,44330,99792,50040,19619,13950,55228,24423,31253,95308,103177,184795,28590,82285,5059,3210,75525,49894,70007,56178,10580,36051,139681,21617,98736,3555,106306,164189,37352,63915,47824,24883,145530,61904,28444,11483,19837,145446,30420,112972,85939,11835,191233,2262,20705,58630,1753,148334,1197,144714,6887,11223,107667,60879,77914,4151,57417,81594,96681,169430,1784,20444,95138,254041,27038,596,7117,72808,13759,3353,126776,21074,55322,27081,36942,39547,139830,179275,4453,713,8722,71399,19204,25785,22794,23923,104114,11291,25458,102309,88396,75288,230440,206396,104551,58447,130857,37247,94734,31548,176529,226077,65159,20104,10096,66881,94191,237909,27109,37404,1520,27421,25220,113003,23423,24884,50585,6286,231877,150800,11789,3226,90004,60642,5053,202400,61442,132531,175329,57138,30116,103847,9973,75367,16452,32360,59119,21246,10191,164804,23305,61051,37348,154530,13214,5468,50403,66754,130976,50559,80515,14436,155492,84017,5472,43107,41240,2890,90431,70188,382,76234,48040,50211,281038,237007,32115,142178,1536,22761,96429,1811,31243,1679,49143,55209,17402,235054,61494,7462,77030,34925,87609,78002,9499,9027,73289,201078,101379,63544,27666,5469,10642,30029,49816,132979,95620,58086,351930,116300,2110,2043,30845,6154,11279,16727,4122,2277,27281,4971,3650,39060,61970,65951,39674,75686,38151,11370,130809,177895,32665,63725,122267,7857,39618,118483,44792,157755,178624,136994,24260,41308,22471,12404,21707,12486,30473,52781,50246,20247,39065,909,56825,103158,128603,31542,1089,41935,32744,12428,37963,84420,33134,72921,208449,42622,168151,127335,147107,46699,38216,12591,94342,85814,31423,24944,2605,87542,67473,192551,4496,56321,91819,17630,6300,256183,114569,202090,33209,35289,34897,24967,40520,43470,5344,10199,34810,14283,10381,10017,62923,49924,23233,64539,13051,35686,19698,11570,135555,120868,44924,87065,52318,52335,47586,140906,245885,109834,78668,9065,46990,25258,72022,61243,40838,4545,146387,10537,11557,17470,36930,68104,46711,24264,79401,81043,18225,120488,24746,84338,81652,28266,13776,21878,46973,1047,230465,73357,95777,24973,210160,62210,58404,110633,169651,6937,41870,9909,26822,191062,76553,27519,96256,239070,2478,205678,67955,58532,20601,50120,19148,78501,195724,110740,8249,109665,27446,30568,57631,31425,49752,32820,65504,50079,3663,102256,219898,23849,211315,14645,4359,91767,9528,12449,49366,7941,49763,107848,8930,27086,50686,9744,10447,81935,39513,46514,1670,29229,6172,22312,137280,97759,9806,14445,22976,56458,73391,34983,93760,174219,52573,33149,59747,2429,136277,75123,165263,91040,7446,57632,48633,97140,246081,84766,151684,79918,93268,120346,54059,54875,77858,32996,103590,45276,11968,19600,25849,17159,132907,42828,16817,4913,99462,103303,27395,5737,74184,20749,21160,14377,77062,131403,158735,10999,27799,77785,9320,34366,51593,61070,33746,47048,29268,36675,30262,53297,9832,82e3,20188,122292,39917,7331,18160,68301,185935,134830,15031,4935,10004,165845,185534,46923,30109,44134,122631,18874,22903,112790,26561,18549,348902,82871,140345,255565,135390,63556,103747,145055,179600,145662,296111,61661,211987,23952,52342,126343,48450,32919,44277,82185,9591,62139,205363,376969,394874,108461,18040,120885,14798,39863,16571,16794,58271,81025,55206,14640,118656,6361,44092,85970,6262,153863,108244,180200,72264,79947,38044,10050,5735,61221,80712,5471,115689,11391,11661,184257,20010,60116,30320,19327,134598,45455,27542,18004,125092,452272,1549,91523,46567,180063,156026,2608,11174,58848,37788,65907,80194,30490,5786,40775,119519,106241,11323,156297,8425,61495,2617,29675,2425,59886,112582,49142,59618,4863,50597,86710,50650,168632,27693,85641,83643,18993,25768,84284,28090,93592,36627,312804,43381,9887,9402,100931,97165,3311,173330,66805,28935,4963,184460,3201,78102,19126,21607,37496,24938,22615,16153,32862,134792,153318,61120,6067,2812,12826,12792,23825,37559,64662,202250,102694,155488,85881,149193,46233,65383,15521,106982,11358,176786,25752,39717,34208,24510,32464,77742,39371,72028,138229,60688,71386,102834,132477,2208,11548,63670,271279,28351,30338,38620,32491,99845,143885,152266,13252,2825,178663,108097,1775,78201,14897,113573,163346,62292,171129,22183,96598,38733,64971,166776,117445,9968,146393,44677,74867,20908,97328,12761,25656,26785,9148,112344,26115,99176,110121,22437,49547,6180,79320,5835,31392,43328,33377,75870,119860,69497,80273,7325,155219,43167,111173,28347,20222,3763,71752,55041,47252,14618,28088,15012,97805,194698,54636,2036,41349,6173,96604,61530,51859,43782,13361,24334,22668,24792,7070,23441,16789,3209,36211,208475,26242,32880,122181,182407,21444,31060,88459,29929,77907,12716,10934,97005,20599,31690,8403,58445,30303,22700,10336,86731,103115,337709,72556,46788,112566,47684,67089,53548,36874,56487,41387,125985,26893,40071,106683,73712,18787,40105,72992,67246,137276,50802,36790,70328,138827,22466,39263,183295,29858,50975,9322,57397,10654,24364,30383,55799,41600,23584,127295,296610,129078,143558,244131,86397,36049,1085,80677,3820,108139,5476,34767,24683,7758,13060,7239,131671,250593,59556,103392,29810,4188,252323,39404,116877,7651,43600,40338,13554,157253,39196,25978,144387,61211,234,50104,6129,10449,93777,9240,356378,274148,4439,72970,3724,147770,78680,62570,115877,40027,40547,36817,224392,64609,34795,165027,67440,2477,37206,23431,50754,164797,46018,94995,170982,27051,7957,22767,3674,27900,56419,18930,60701,41302,2692,84749,339721,61996,111094,80221,50129,1045,8153,62945,19202,8250,37208,37418,32560,79477,41106,88569,33963,36693,5892,30570,1581,66471,49647,11922,160717,29442,5643,114865,82962,95982,132098,22633,22838,94726,54556,28566,205039,162340,33216,16849,35847,221339,94851,26533,71469,1805,3804,12935,45483,71020,36310,65381,192960,34240,35165,59773,1248,46954,155332,96864,4246,388800,16129,57133,74592,44807,442014,38203,42574,80818,91592,26377,36424,65760,977,77387,22628,147610,28018,30561,98454,6969,119628,63648,18170,36854,26601,64018,22027,37279,51395,152934,21153,9430,58760,194742,5330,55115,34158,28917,174111,13171,122326,1526,43896,66094,25325,4234,148354,11450,275,18999,112191,44365,22723,68409,8733,57746,96565,75007,14196,108844,29475,88599,177563,100792,106156,86323,93726,14248,135341,194131,40126,47099,14779,8272,39597,95983,171398,65882,28052,10393,47213,40689,22120,72212,106829,34964,109146,753,648,21660,30047,17527,181025,5619,145357,4085,216883,9359,186951,24779,53931,24545,36197,223296,62628,168101,4243,107313,30321,26642,13049,51059,31027,107912,807,73550,26551,84369,122422,165872,49754,74213,234264,33151,52014,33100,87183,22365,52500,40013,23302,5652,72723,21404,26107,48434,587,94049,168493,96418,32871,70860,31709,25128,443,71597,166253,15670,70994,26341,133675,28280,75491,54756,47955,56028,26182,11952,113272,472197,64640,110753,17919,337,50642,22576,142,87371,53391,93210,126694,15285,19642,85667,14148,1506,42092,52962,33243,11970,20734,135843,57044,58880,13002,219134,22876,64754,232519,4257,43120,321573,24799,64526,124728,52579,81472,70831,276848,17403,74359,23021,182101,74597,23744,148267,12055,7976,5349,11772,67540,167347,65318,18720,127832,108238,22828,90233,9987,259080,118185,73209,79270,13775,90100,137742,90799,70569,15699,19961,9087,67475,57872,39731,8810,134897,131868,146849,19898,3334,2281,167061,91073,60356,467742,74712,188,53179,137679,92769,29241,9537,132595,80119,1041,88962,5976,40171,44911,102859,139059,104558,98987,47761,19272,71472,113864,175377,73338,10857,23402,23758,1591,139864,5644,4076,118760,16427,134198,18853,20291,100849,37423,22038,36677,19071,195521,57445,11069,31869,55718,66882,148490,44,41296,75242,49704,166810,9906,20943,122258,49112,105667,15969,10344,6408,187694,21399,72742,58970,14867,14376,81889,41856,23225,15042,56993,16074,131389,74276,72407,53875,383108,53597,37363,68993,44854,122548,430927,198279,38430,80409,12245,2981,628,2818,17760,37437,238229,7968,46892,2200,3730,34190,65983,37959,112291,87850,70827,6522,20750,73913,111621,41652,19587,2780,58668,25916,85259,18200,168962,95781,42445,102050,7776,57662,103313,47742,96358,41964,66174,100396,29069,204735,19679,27978,7479,40264,22534,61183,36081,107436,58223,14680,23002,101311,24716,124108,12908,5646,31750,40380,14215,232799,102772,14122,96775,61398,50917,12096,149880,67833,598749,124194,155871,49216,790,14677,65319,56917,7440,145744,95701,12206,49405,129269,76199,45732,9767,11058,9047,210885,11051,7392,26307,2130,8132,147526,20802,232698,115660,50060,59789,57344,107623,80343,112676,23291,9866,160971,34032,118291,15719,59730,164911,28975,2659,58046,78480,21854,66209,53863,109085,116045,29021,46481,107552,22130,18764,70254,31272,11300,52460,43933,84738,20721,53869,190840,79673,105300,7561,321817,66924,13940,33281,101046,183181,32176,71878,5678,62924,79535,56646,40303,19559,27703,93042,73368,42187,3670,37376,46440,7023,36816,109628,20680,5940,276440,275233,170848,112093,136996,14984,20226,111441,77693,112960,48577,39370,55707,50314,123404,26570,54281,61372,123391,4857,35928,246740,132507,106646,44241,7196,92258,9825,37688,51197,303141,5590,15476,132986,10955,85782,34486,26696,7991,28813,18858,39546,11703,11365,38185,5716,93555,11925,40121,60002,6985,10976,171384,3887,43394,13337,56346,6381,252336,39573,75042,53711,1028,31781,44295,95925,131713,7214,68125,43571,70954,213234,1628,8760,13391,65485,17320,56038,1710,25248,60803,57399,19839,3870,326,281556,50945,72400,21460,316244,75619,56246,98775,481,13513,55765,50427,7388,123519,32929,57908,27124,61316,101097,57467,30228,48792,10788,20402,37318,50526,155730,34456,158065,145305,17832,43733,64052,4506,35072,205355,177028,184004,187081,68616,35938,83703,10367,36892,93186,260137,51934,89970,4985,23445,26755,21558,7948,78741,23376,124405,85594,68596,57536,49351,12619,56593,132668,99924,109728,71844,71935,196018,65464,17617,14987,89701,143773,33997,8687,22701,33258,2914,4436,72108,85610,9671,49067,2327,82988,1361,1672,44033,35777,30269,24057,10605,82236,616,15793,13919,47249,112086,116698,9484,80207,90574,33304,68624,93127,56101,42210,160929,4827,38995,38095,4701,125119,5027,33680,9236,231236,14135,87837,23318,70261,78893,30151,81482,14332,1084,74256,27532,46644,79185,3148,62615,6981,55672,31668,36825,1849,14536,37446,14738,23779,43058,162749,72199,1168,21346,5592,85932,85302,9668,18351,57135,150360,2080,228015,77953,34670,119302,151751,31009,106725,84265,45214,59289,74178,113071,263206,111009,4021,44449,188119,192629,123592,392506,292847,114487,12831,205858,9852,20780,79648,75767,357014,97721,18166,21005,67950,33226,204009,16536,2987,11335,66717,144910,47950,17262,55060,15063,2934,51038,26775,178497,66008,3427,49433,128592,20036,157553,63861,3089,23015,51210,28696,35933,49942,71135,231518,99620,17248,21835,176536,20676,16944,38700,165831,233253,295625,36723,13023,52745,10907,19423,67972,125868,95473,82875,1183,108455,52685,33417,64095,21433,52438,33191,127809,44505,211823,7810,2752,95548,162031,7185,91196,47563,61721,33359,17897,23682,42806,178101,22874,49707,199897,75419,82456,8618,11171,79712,116847,18783,44190,46564,5346,59046,95032,7893,14916,3214,26800,24172,121453,34362,10250,17408,18888,4840,68696,22831,13162,36005,32512,14800,62357,41723,45046,27247,37486,5372,2564,34261,298500,66509,133920,89138,31305,117697,19097,108304,81386,84106,23802,46411,63304,946,51417,41777,41041,19501,115864,60743,294354,37955,94165,18116,1156,17937,20645,57114,90804,58042,48643,92288,9861,2557,88546,61333,101008,12853,5148,87856,4152,144503,73841,18718,9789,147565,10846,42085,12789,30223,8993,56352,67203,2448,28215,6052,23540,126319,75933,36689,80235,23231,23561,21383,38800,77548,102798,21234,31468,158608,46188,63960,191679,8051,67014,11185,170078,42186,28827,34777,41930,212079,12421,34750,24111,110344,73918,45171,70826,141949,40063,23979,24254,37309,26724,27179,24718,83648,54938,14591,17425,29525,102675,48975,48654,12316,8929,60640,41709,50168,63264,89812,50716,48632,38755,138583,160123,55579,71829,24230,233277,46322,39650,166388,34718,24108,98252,7031,106695,62498,18258,35062,217827,78731,34824,33354,19520,60852,2432,60224,8587,2836,62955,702,20227,42285,40560,95592,62486,11094,53035,143291,18842,46177,77994,1770,9657,107422,172915,32655,128716,25886,25164,156740,119928,165875,85817,11007,89110,33956,12652,65156,180266,8494,36889,19958,20955,96,1264,118288,135769,44754,86671,5632,19026,168220,289120,33569,93821,66144,70635,7687,5642,2714,55445,56636,71545,184182,93133,7332,37389,12643,52315,22729,11014,158742,17050,152889,50178,34601,41945,52136,9948,26914,63548,95721,115951,40759,8960,158258,38938,49232,48325,42234,81523,253019,66128,40978,20048,238048,38760,62928,122560,118532,43687,137472,163689,26680,9878,17448,51035,16211,60834,36749,29178,14241,59868,150086,2305,26477,42422,34342,165341,83279,33894,14257,29928,12743,13957,125571,89134,66712,10952,16507,147839,30146,7249,16565,45399,39874,114565,215780,31990,230881,171477,102,196546,44538,10880,84948,281705,86651,10617,31395,2342,453658,43569,60561,132901,21845,17727,58556,258242,22262,58728,4008,77997,11806,37431,30599,81375,109137,185787,114085,217292,97453,169085,30593,60212,11544,102056,65580,2384,91655,4855,95725,7295,157994,16228,20669,53276,141590,105246,17334,25440,76067,17967,39321,38911,11362,28559,63807,21627,26468,85816,40120,1025,15234,58319,69516,66512,124548,75845,78873,22137,46681,51242,85683,32909,76747,35555,43396,101465,1765,73094,1077,2962,39028,66777,57831,42048,15828,13962,36041,63657,52412,5242,58846,2141,5506,219012,134451,3936,182230,17558,17153,152237,22621,49377,170216,35257,68233,65374,6510,11126,212151,7184,2480,22517,3437,33073,30156,16557,3768,55067,86829,91e3,12350,148650,66017,79424,70885,49066,28250,21369,51213,34533,11510,3258,18176,18465,84413,6315,36411,163765,4346,356,107618,598,13727,285026,162695,8749,14583,7132,63521,184253,32378,25991,5604,30961,53675,4874,84693,5086,34811,26978,56564,7904,33519,51221,113942,69253,6664,125563,22055,220680,102008,742,51930,19494,176108,44424,35123,13025,75685,11759,74335,22250,181453,131147,16984,132115,154311,11991,76452,52609,85351,196,30969,9198,74919,2529,56838,71779,29187,116304,3504,62330,41190,86153,28393,254926,104228,105189,13264,84359,3574,12415,8534,57147,10175,188174,59504,60932,66318,16407,107921,17638,99103,49278,28403,39786,145865,8462,3558,43406,142271,29139,21989,36552,93955,72365,7176,13556,106185,37957,321774,17782,129017,51154,27938,24952,1935,39366,2791,33489,41582,56078,24558,9311,5449,218786,27808,190429,68013,36020,86003,29735,3404,87348,119357,115714,2324,86796,81973,40992,43376,93621,28784,16808,36367,2517,2909,191926,24978,55303,53308,205724,60068,3098,21375,64784,23949,26579,63121,12319,80145,39967,97861,6757,70143,67642,37082,34698,69140,122883,46151,62187,80934,429,19437,135071,137885,222647,13331,154065,327,61778,74257,40116,37493,14855,85079,237641,42342,102164,199965,71204,4662,29368,5042,113914,122214,8955,13149,102503,43173,5659,163787,69003,307084,63392,171080,21390,81918,86666,36622,24126,28887,5736,28054,207170,163428,79891,346467,95363,38980,111806,80828,9200,19288,294896,114468,87405,111715,141705,7015,72754,68463,48738,243147,33397,101210,37051,98801,82847,20397,4940,185559,18716,54718,83491,11725,40803,1128,12128,23060,5174,7745,67007,46701,1571,27807,180186,256996,18975,16837,7877,212758,250379,15440,87954,57755,24719,124057,83461,258,50864,8874,29038,71289,31627,15429,9005,4061,113851,107716,82819,13651,79656,117851,17539,111446,12938,39724,190787,4352,15402,21070,62708,8539,23777,73853,13552,38810,86117,16285,56400,1718,75342,142863,29033,378,110113,180321,32586,23606,26393,160984,207987,23783,8406,16904,24596,47274,11693,46539,60524,78595,48423,31718,20170,9009,146268,15183,191060,172765,1349,138436,37365,10970,40509,225817,20021,70394,152138,21541,66559,66544,89352,2725,17258,91345,7313,3815,115868,8660,40362,4071,103524,39388,118275,21950,6549,38226,32754,209574,29201,43495,18028,20296,40597,18370,47520,202450,24134,2219,8195,69545,38041,136934,46374,19041,159811,84865,58620,846,98749,13569,30714,97246,32186,4479,27355,92973,35214,151491,75963,37631,1561,27200,238083,23182,60756,12291,25766,39355,102333,87362,65741,59906,19538,201575,48772,102938,24438,292580,39964,66366,9004,61379,50548,37622,38732,28379,68180,76622,17488,69849,5963,7219,48143,43413,55358,540,58691,29506,19245,52193,48621,5518,13048,118625,44755,191081,42061,89197,2259,60665,66994,71210,51232,3585,142096,55024,7892,8345,58653,463307,65658,64319,137941,136323,53499,12746,43492,6978,95163,29925,60175,5128,7352,41463,184756,121146,20473,18426,4598,5309,54580,14277,121151,10691,56711,43880,63409,76682,11830,172218,264898,32632,66536,81062,31649,25788,92774,60222,11100,63159,9432,224657,25240,53613,152,138620,163829,2397,85345,12501,37507,64932,38575,43522,65789,80198,78796,35226,3851,108891,73311,3060,28391,93671,39663,46142,30982,66041,37281,68157,26553,71872,81142,211527,39747,118119,22695,2859,11066,20232,168911,7933,197005,17066,111071,44434,133994,120798,12766,227798,45756,132852,29917,36076,55352,65281,129800,41958,18944,84678,18580,168093,132621,39997,54092,27740,32354,3770,114118,103242,43918,15899,18574,145944,3190,123469,219903,24169,100571,62403,16776,92779,14535,17168,16475,14304,37231,1712,28218,242754,61688,28980,1318,51359,222657,99200,67989,31772,23932,35351,201251,49041,27306,19128,40135,3986,77333,19649,120683,151927,21081,7076,78375,77501,101599,8011,89585,96715,58179,5378,102138,106793,26051,217276,4197,16297,27014,46721,13322,22806,5278,29629,70632,9647,71519,58818,40603,128530,8903,36770,56900,31483,26935,43845,34265,34920,87658,6114,84767,64250,47318,50720,19264,162514,33357,13117,6705,46696,75032,71054,87004,42035,69138,11903,99854,102328,19611,34525,69312,6431,49842,101600,133178,108751,41829,89939,225664,48916,99556,9195,130387,5960,36857,116724,53518,94002,39077,53996,6945,22261,64291,8314,152785,57588,16522,9091,5048,87671,35441,39509,1945,12423,158923,178413,37549,14095,1475,73188,62878,4819,24012,68534,42606,4010,120809,57497,59564,101758,103718,32701,80116,12345,95834,46918,21468,53213,15665,31200,3867,5140,96013,250744,21016,10069,13968,35449,180829,27683,39704,59956,22893,3115,26293,32785,75934,62445,141162,62720,2018,83638,19949,114012,95006,3330,99829,130935,309272,9565,55874,121727,37017,23586,319858,40970,27602,8625,112329,61060,100088,118525,25922,16232,1907,60671,51583,44553,80993,5262,94679,8676,940,20736,11823,3020,16476,12340,152600,97416,3703,25744,66826,16245,16876,46446,84798,74227,176020,45192,61955,75496,23946,23626,40372,26036,6149,11822,30582,16541,41914,82385,232823,40921,80773,14930,3631,7517,39619,4348,36180,126106,138939,62611,1477,113512,47321,25052,14546,118881,29060,23589,128322,36795,18401,137921,104699,267929,36194,172791,18113,4766,188215,30083,332586,94089,5805,77909,22194,68234,154976,43220,40660,70001,184893,138095,11128,103010,22663,5108,212615,8485,5565,49222,54614,26530,42639,16319,55062,152662,105595,21114,22216,10294,68158,10436,86950,7206,62115,3977,3657,59874,456,118617,18156,106663,112229,80992,17442,8217,55551,5133,34344,251927,51153,39364,201321,7816,66803,23057,156724,145664,14276,95705,979,2796,6875,13429,212525,50602,26276,28284,3424,19465,52397,46963,31420,51399,206476,92317,48851,637,100820,83349,10317,60227,21972,6908,282439,32857,224767,95629,83882,42106,87338,69757,29840,68709,37665,45244,114577,49188,175943,54009,186746,106158,70168,3358,234002,50555,9221,129338,9562,20118,32923,78479,118280,65752,4977,10474,102174,60947,129006,10570,83451,8598,8078,159367,123785,80438,16742,5905,5281,181513,42402,6977,163136,93179,42191,14968,50421,112401,105440,33456,57347,121611,4221,94954,36517,24046,27796,6255,33394,72990,135408,116627,1233,57874,25654,95419,68156,401399,313338,55208,45573,93124,119251,47200,38196,11909,130667,45391,73904,64964,167846,4137,115606,52036,62214,7969,160925,7187,1132,134835,40309,73195,64494,80472,444841,61111,26500,45323,40743,53625,52797,22659,15631,29739,36706,28841,39147,102836,26794,10536,14845,87305,45874,12241,127587,83833,57183,79722,30844,41304,84655,20825,92500,3722,25655,27811,10157,81634,31362,34088,92487,70123,22190,185100,72658,139035,192523,88241,2078,230490,44528,85638,100198,22088,29982,291233,241062,13865,4445,137791,37835,107218,31726,19718,38234,72528,23046,19177,66695,5109,17251,28077,5617,21554,47839,72425,133825,1486,73065,181275,141508,21768,62971,63082,2512,34200,9904,120309,6392,91243,68416,268253,41199,116757,138551,185526,41246,28986,4093,19057,17295,4148,245766,122360,35356,112075,20301,75441,10998,7977,19769,62922,937,63547,100196,26427,157820,20983,236696,22935,8140,90315,156004,47204,140973,7726,45097,52725,22636,23436,257282,105247,522,88389,216031,202204,46812,211666,19693,68828,81691,45925,11256,30292,372,5236,167826,88328,232776,151611,5360,82104,18841,80393,25465,18285,20320,72377,31730,33160,45803,38715,27705,37379,24163,18360,103586,4015,32305,269494,91252,20080,36567,54650,7797,57073,12650,31164,42209,6375,261663,105528,81661,106002,2800,5375,17247,43151,4442,15727,194619,100855,144898,62320,78465,39929,16454,1967,28311,61363,17219,9395,8745,121445,76939,80385,162380,22009,54191,44248,16299,122830,48151,74429,78291,64755,14238,44966,2511,17712,67954,93583,829,105899,49935,84750,11591,33185,85447,42717,27409,208542,28965,62052,52525,5597,25694,65594,16343,63224,276188,12475,9331,127507,38522,57287,24128,133161,79723,105548,133695,48917,27558,43278,46520,13778,141954,110785,83366,17715,46317,105763,66298,147013,41086,94180,16478,220447,44611,730,19722,78975,117889,125643,26254,16574,18480,65006,15806,38549,246418,46052,36056,8440,34984,30170,3163,59800,4458,115442,4283,41970,33507,104078,1653,22,121158,276486,3655,6338,24048,133421,23641,2161,24422,36006,8086,10675,181474,12307,29514,59143,14729,52509,87128,122470,19446,80852,33314,24573,119864,14237,9652,57779,6612,51851,15284,98871,90581,124466,156831,21190,22015,71380,161906,87247,69201,18392,17908,108470,72962,40719,14338,17911,95260,43339,20610,78916,20710,72451,11315,31448,17263,58853,178878,48111,116002,45497,80506,82605,85880,36300,121755,25215,36118,301929,88728,405223,276136,553,34704,212438,49970,78329,922,20711,25036,257130,38295,145369,18128,15385,30829,55656,48345,8012,3561,28004,122041,192900,58338,112508,41085,29976,87040,47117,23905,4336,92061,138880,97407,42083,172121,6256,25192,172671,5,93568,1420,12677,31605,56743,40620,6015,78415,231077,31298,80026,13902,19048,24924,170586,32955,176119,87859,36731,6773,27711,24658,26475,115216,133207,93250,95820,88522,8317,5714,124047,55219,86860,19677,23961,22928,162209,8904,225992,359835,56084,96201,29392,96558,86071,93643,55114,13347,8183,95129,82012,2017,123336,34219,115554,157159,47747,101684,41008,18735,193781,104151,226906,7552,179874,124113,31159,21162,44010,14771,51268,166128,31382,73124,77438,92830,205709,12113,1292,38937,13114,1334,2118,15597,69581,14449,21934,76618,48728,67038,14967,51495,24243,87736,147249,26720,11119,46063,43749,5843,44147,152629,133428,65703,14269,45604,57982,28672,55616,45957,8438,95433,37698,220862,132034,39456,61870,4161,26501,73560,56418,9845,4654,20916,10456,88920,119358,9015,65931,96507,48029,38534,21676,109081,43078,34943,25089,6131,28766,23665,5477,10255,16695,67,45778,42443,42770,29534,23733,100513,62617,42630,48746,14191,43753,50295,26007,8792,57243,43119,54725,164253,58250,112304,131796,25165,4651,3188,24831,47748,3705,19540,13211,102095,5593,18699,23666,32005,117571,33541,60584,74573,86311,99443,25172,27222,168938,7143,11853,53560,18834,19960,86522,28217,53266,117700,72989,34323,18721,66450,34346,74056,47217,202002,46269,9429,68582,75458,37823,82843,96652,32549,145144,27958,19820,158086,31955,201406,135379,31207,192545,12950,51704,9094,248263,76147,64028,110009,79407,89345,99284,223492,47966,26848,15359,201137,2861,110507,71231,72297,31851,118777,71039,151051,240855,16333,50766,14727,7939,4149,80908,418780,88378,59276,1327,7284,38576,79814,65820,42199,84860,49574,62596,12396,70598,40117,8648,7994,16836,7630,14047,359699,106878,525,29037,28064,13380,11675,50669,74216,103539,180314,27449,56299,172344,19274,7301,246099,32043,19422,36506,129317,6806,30140,4614,46639,66926,932,86600,6322,27847,233103,10541,39025,34887,3517,12972,26220,2031,66561,115015,48658,47596,12714,33845,3893,16165,35237,89983,14769,11962,147224,47018,29977,27979,5552,82338,86023,131368,1218,24853,237840,132193,15455,40873,3668,65351,53388,15229,59889,272245,47934,11858,34347,18038,90853,86981,300602,19343,114181,29362,84921,6095,106059,79472,38015,1206,48741,6208,8e4,21916,17423,6002,108083,24479,34931,56661,9511,26995,100694,163853,35997,81254,58321,18919,171890,86877,91341,74503,70477,53412,7027,59281,39892,131302,5864,15947,61301,67466,162369,47956,27874,35624,282324,21270,111847,102548,41482,30955,116737,28264,8592,55458,22301,75090,29821,30697,51709,3041,19208,8038,24634,30467,87509,126428,19389,18814,152686,20701,83474,45832,80891,105808,11378,153223,120770,98186,150633,49838,9141,12755,30962,5260,74490,21256,31678,65062,33326,289838,187831,20595,89768,2805,58535,10844,70085,12090,2451,138068,98544,24461,4511,6754,41684,28203,3383,65355,82833,30161,83924,234361,128424,28921,222594,33975,125491,34069,11508,67464,144226,41850,98703,34371,7901,21254,38398,65651,23549,53883,213340,123269,12028,71764,177701,28758,2623,68395,11549,15232,68603,9660,63116,36079,57093,31198,20475,48467,89984,35619,186847,107469,31389,43631,73867,41949,68841,114250,1605,30564,63403,17588,27680,99533,12641,70325,50428,73426,78379,11855,91651,72081,91720,60198,15743,12065,83398,140046,6761,46598,45900,5068,886,62448,148968,37347,19405,9680,15819,43496,63370,75667,163700,37639,3633,22774,34341,183131,134335,37200,23915,7054,14194,12970,26438,13350,285521,25594,8219,104410,91039,168804,138480,149734,15907,33818,61132,60082,4622,110187,56736,13551,73571,3945,73463,65498,17758,263266,17593,2710,27585,54469,38200,45367,63754,28881,3473,12791,98287,31895,65787,4463,94536,24951,36332,59901,28803,52130,86403,7668,181822,74831,18977,9850,177206,145485,109798,7292,31421,26280,77211,58511,12507,127004,11113,147,8729,56208,43066,79926,129937,31345,83947,39915,46146,98763,42566,1337,13192,18323,105163,80570,117753,16555,72883,11077,159438,40764,70933,83329,26066,12276,72059,21655,173836,126713,69454,153482,91585,70644,102558,110483,6764,127864,190133,3961,101798,20945,71138,82402,90884,69669,44753,923,16939,59700,164258,25969,27082,31399,43846,6306,246093,51342,6153,151581,202801,182731,56475,162188,89426,141356,14355,121815,27536,28023,65257,77523,106668,127314,24947,12790,38796,169698,23555,10725,44573,183083,42088,62716,43265,105958,32050,44067,50118,1668,3874,6243,318411,16599,1691,94999,52378,28671,216728,123258,2059,34969,69225,5913,136280,171443,141515,91662,22175,135282,80020,92270,1663,4808,4482,3495,34691,5226,109830,108512,17342,107488,11606,123190,100247,29666,146527,113014,15794,30894,13224,39585,243192,22351,9903,7836,47699,11078,25468,122291,48821,26780,122679,75521,81450,630,4895,92900,55074,74293,17441,3563,111657,103102,51613,12318,52370,36191,68245,34269,40445,41354,122901,168604,182500,62012,42557,11259,24428,115113,86345,12362,3909,78430,86852,134602,20459,47853,93879,22577,7659,3688,38555,13349,17381,56715,91639,12493,10895,92438,3142,37057,28928,2004,36427,32268,34222,209974,10432,67436,41989,173518,107930,27079,62729,30908,55558,5828,45031,14902,53546,8204,144263,60255,14520,88212,86582,109589,69356,8064,47449,8505,66558,16886,4844,52817,111260,215129,12941,91118,650,20770,6273,73089,40618,62790,2873,35002,14023,97208,19386,102646,36993,143736,135457,35385,113601,17893,32627,84439,100619,56016,6581,57264,172160,45452,111710,203627,70131,24100,322787,1996,35665,70078,22358,90922,83658,4097,63200,58499,14542,99153,52159,6615,12414,63415,31986,16823,1579,65405,137809,8841,16898,48082,259,33014,42375,12260,179850,73667,91389,98882,29532,17311,326251,41092,5928,20742,44964,48019,43505,9317,49265,6643,192712,48424,163487,19861,20113,70848,31928,105333,23685,78563,14638,54755,7158,24142,44018,20774,125255,20331,24280,10163,1285,2336,39851,4299,117269,46714,63816,87779,159624,11731,9971,990,137317,108831,50994,74554,162680,23640,131597,146962,170620,34829,91205,21184,1913,63616,18427,93136,156592,17519,67565,115882,138220,78622,88535,18115,2711,33554,109492,54298,971,24914,25863,36363,45715,27099,194995,14299,178181,111488,72395,322385,157719,130787,11897,81843,83999,11369,49280,118604,40922,61332,110343,53407,75639,40582,300440,54722,25637,13694,48248,48278,194521,56203,52779,48783,72627,10953,376,16733,280238,26351,230789,15132,25168,137270,3588,63704,73376,94031,74284,19443,159557,9697,39901,13351,119050,15406,146455,3460,29556,75195,37673,102524,92329,47289,98413,15311,100684,56345,7116,95480,11590,7200,167,23610,58426,17730,136656,27944,53151,2701,8824,103124,3017,90744,113588,53216,79736,65940,26931,498,29568,80540,143543,21292,1740,59268,16561,180816,42323,50174,40890,52866,10703,57169,4700,17191,4424,93511,49698,166650,26972,48631,165169,82879,69326,202970,4007,2376,231325,139592,22119,62851,37504,68816,58345,67398,186643,43331,277416,53749,15746,23102,17432,4793,151138,48822,54265,48203,198688,14305,54287,2291,18018,113378,123260,7180,97549,87027,120085,2920,76080,8190,102005,5641,64580,14955,59802,54028,58884,19367,81779,412567,85957,97053,103637,78871,29364,27637,141728,4767,30686,112738,130146,42745,12730,105040,14844,232,210944,36581,152317,135543,29744,3129,55647,58149,46319,27265,17499,28005,59948,7170,34138,5702,293047,110892,408,91760,218674,18469,46095,81403,14389,4610,35672,73060,11006,74848,104820,118143,190357,20043,105358,141735,5115,27093,45924,123073,52599,29433,9616,238350,78610,24851,58858,26769,31969,24613,18294,4982,32735,39639,143563,112073,202205,12567,4873,88601,44897,81503,101648,81362,34662,85277,17574,48173,21435,221188,40215,39576,80786,26544,64668,81841,10731,37733,247986,149188,127703,495,18382,54388,72446,43071,30974,198723,89608,41360,190,33045,8386,31658,19992,237838,119015,137622,50890,100913,6460,116233,267230,26621,104129,65114,14190,41542,14888,85962,23342,23041,26453,43725,71809,45186,4770,46452,53894,56616,221286,18973,9038,109299,55365,19366,26863,18808,60909,69353,41738,83463,12100,68561,72860,3980,13796,49340,12332,31311,27418,4255,53430,18976,45523,510,14224,30477,26581,4530,3651,101663,139840,22709,150861,31996,63923,120623,262522,3076,10528,2929,14672,130238,18087,9816,121894,100308,25085,55111,14565,18952,53293,2042,369988,23674,61789,133529,28783,108293,35477,47119,36448,71049,40015,33055,78598,198442,1833,159937,40654,77444,189245,113153,8621,18599,38553,35223,166072,2375,11659,21786,89523,6032,12116,63046,159398,18454,3678,32521,47626,11411,103527,38896,42946,15696,26370,10185,8413,37080,165583,4331,63555,14907,72220,50056,6623,62236,36565,49783,10049,17503,100581,55951,146244,24724,9626,17969,25524,109300,173965,99994,101056,46459,43647,53737,277968,8347,123521,74858,33829,44762,77574,877,81377,222525,123532,30602,43881,53145,2973,16284,81940,61281,127044,63620,9875,14756,114829,19032,9202,52759,119141,23928,120551,19607,3599,33401,76821,73233,117430,39968,36539,7071,5446,121735,194059,15206,45283,6706,15603,65615,1207,165723,92275,34773,104447,8396,32353,205240,164323,13600,60555,79205,25532,22907,33410,57480,107111,69630,32137,47832,70913,33161,20321,2371,117348,10714,86246,1625,11763,17900,268,78457,99175,97940,101092,86660,32221,14041,128504,125080,53744,124263,31017,13897,403,31859,21964,5633,111630,5547,77329,17961,18241,84995,25984,12983,67491,62168,47262,5241,297,51191,7351,8967,147212,82060,16821,782,11033,82431,62957,5026,43459,77963,203477,53528,6247,191852,87774,74164,215654,13467,1522,219964,28589,244104,16242,117821,67725,72570,156792,17186,15979,26990,44128,193014,35276,57125,16212,166451,68017,6905,77608,16364,53777,75921,76426,37975,26203,269296,64099,84122,12077,38533,830,4407,20139,963,43028,38902,42911,37503,83343,85045,16979,1165,60835,137387,58380,86990,110066,134540,56331,193845,81238,17922,163093,38744,110641,12502,56404,34862,26865,125964,12965,111648,25547,7771,27196,136980,9555,29551,107158,57885,18831,37705,35505,101742,13970,102109,62548,124657,23328,11124,89592,146376,248050,6241,22033,18337,80685,29898,11908,216623,67721,106162,146610,21377,15085,91552,42041,62560,122532,125336,102365,121537,142559,29693,223919,11515,110495,18776,22494,5895,185059,103592,229351,51220,100102,37027,257855,29359,54123,36066,106493,12244,79258,32002,432,56205,94836,90182,6726,14762,29391,48938,26864,38083,60364,3310,60192,14766,205567,57504,110760,22649,24666,46333,21517,3430,13135,28873,27052,158809,11597,20529,6695,23138,22960,37137,45574,6545,305877,43423,26153,24769,59844,14501,10430,134352,56169,13213,103432,49523,35181,13435,12408,129475,64620,230854,77390,51990,15653,83248,33466,44571,117828,51481,2187,10559,68019,18021,54895,48247,18354,33737,4554,108595,37288,39767,116707,9175,3726,108877,21616,83684,49862,1938,8543,276466,20134,108498,48770,102254,31914,131520,185291,100559,51890,209,19526,76471,50544,71814,99351,8172,198526,28816,20419,9109,98389,136777,76479,75596,30635,165417,48216,120220,25955,211071,39314,24308,32164,2559,146280,43403,9233,17947,90585,1786,86920,125662,2457,64741,32152,32918,122882,78538,44001,31723,56426,23375,103172,88177,145697,52506,49319,68016,31664,41488,18486,110400,7030,28241,986,109199,19900,42147,56864,65287,49183,7858,24e3,30453,840,16673,25907,68916,89927,6309,158335,36407,199737,130464,13137,59603,201778,195292,21015,42466,179062,172561,89492,11075,180407,31868,72493,20998,60217,9865,19530,39274,130266,54539,21623,12535,13505,40641,73375,4087,85633,2153,3117,70680,55788,92096,47509,98493,37490,271936,151475,3032,16171,96642,34106,78425,125761,19591,3366,19316,54508,24183,50786,194248,91528,33253,34622,108355,41741,705,3814,3883,108929,13203,67831,10142,59754,68208,29128,84820,56880,38794,24972,48571,40821,40476,18137,164254,24064,236309,79181,11282,395,39169,2013,51587,28551,9645,701,109513,115899,113566,12762,62045,58322,103726,41343,40866,244102,143816,2490,70346,40973,52618,15412,30720,104315,38917,42027,93676,17513,107418,20706,123890,13399,97727,24044,87962,65606,44250,98044,65276,74790,101473,19350,91570,1326,87790,172042,7577,100813,86896,85891,41512,108130,27794,14875,71431,12835,156250,58135,3759,22476,42176,115873,34686,56523,73643,108505,51491,20838,12721,32863,45700,29496,13700,34294,55360,29206,155942,123812,7706,163234,203,132720,49358,144431,8130,175788,35818,3270,76832,25710,54095,97274,28779,94621,74396,19092,128242,58067,20885,14670,93255,15107,63291,23654,126900,129421,59294,262659,9798,3251,67344,28600,44629,50672,29072,26999,31526,23183,49175,165843,175455,17282,175411,32022,45989,30298,90690,78118,83156,23749,35636,31317,7069,80381,94561,133756,14960,97404,6138,41065,78041,32843,16601,34123,9559,146529,123377,96395,54441,42012,84257,123541,10745,22139,106459,11720,150883,172651,154996,110538,4728,53447,25704,2009,71152,119354,21166,66604,1429,216162,8637,122250,63520,27180,29172,36124,276428,107787,77184,4680,14952,104903,24418,14793,51561,52931,8371,26342,48526,7118,92066,67280,40653,8847,34597,105438,14198,50163,61188,146286,50315,41205,170829,161496,585,197359,95056,1687,365794,91349,48507,5804,49263,5146,104902,96365,117343,132222,46084,96919,16875,8073,262381,79982,52663,13928,16056,153908,15145,109256,132308,18763,24904,167644,13618,40750,18686,147124,114709,150038,52849,2938,12568,48617,8778,5459,44202,44591,74914,17183,248689,13878,7822,80060,23116,194037,18487,2067,7798,43077,33678,244028,31320,74273,2794,19466,8218,36280,183997,48124,19416,29656,19280,98734,7715,18311,30701,133602,150307,126956,7378,2933,79903,13178,12593,86571,26604,92446,13574,44205,65699,427599,21118,8245,14407,27877,47936,33542,7916,26460,117762,21596,37818,2249,127359,209394,60044,47677,308089,36791,154971,31417,6998,150042,174360,12255,43009,29335,48739,3912,101398,53340,2580,146939,151295,45360,125275,15273,45383,27456,48761,23314,8750,60801,85823,104759,27894,123685,66968,39480,26917,55290,83305,2696,98390,57569,145853,340733,4919,20024,52268,30884,7413,203685,70989,112855,4129,50536,349518,68205,332641,159581,135361,236026,37563,176404,64899,6578,122033,63871,1850,85234,82089,66124,74145,121098,107351,12687,36881,117334,13136,14698,85933,93866,18047,32620,310,15094,46e3,88451,23632,36645,27940,87618,80520,58892,20976,27702,140090,96075,67841,103292,238964,87778,107338,17019,83427,67522,7302,8261,47570,116787,8730,80484,61772,174422,56005,131193,52875,14588,28471,59817,9586,15720,158155,51307,109734,15196,11025,59331,3884,52626,102602,84797,25158,27314,4437,20488,76214,189248,35023,114952,157376,2827,62439,102878,129749,36405,10329,109339,108633,36662,1254,13267,5470,87105,58004,15397,10434,159667,21864,52022,179464,3013,32147,31496,116832,18494,105502,129227,107267,50033,13481,9954,24267,22141,16257,116154,36185,950,115685,11305,176708,2048,178671,112573,287867,162328,497663,95170,50979,193861,50987,30368,136257,31830,46549,15119,169876,23788,17462,249887,57377,1949,35448,14791,43769,210091,3783,34612,282103,88380,245190,5457,20491,98908,11402,86899,117916,16028,162584,60644,320177,156096,31065,55876,22e3,77655,9992,23397,13757,317623,63978,215255,2443,17648,93231,27388,104529,93807,55505,140477,12046,112040,70887,40152,94365,112353,25063,114679,266061,71248,119555,15589,2244,617,14129,211431,70110,100652,7777,4383,85911,89221,21010,120615,58357,86405,37554,41647,18,15143,69662,60491,14714,186134,148344,42347,5410,168175,44535,42449,343894,129417,99682,20659,27272,140483,63455,222159,17536,13722,42637,62324,11976,114691,148109,2283,32057,182393,4295,147364,33705,2075,44303,30274,28331,63740,69740,29148,10346,44862,33716,73937,153333,12930,38784,247159,2515,41053,20256,83368,256189,54639,115240,5096,24661,175419,153552,26516,141,138176,63885,34115,47222,55709,2765,28479,38875,236608,12229,22921,77291,54426,45388,2860,57787,114579,295139,105782,17826,71066,19119,54364,69385,16568,12323,28057,33346,34919,124763,155533,101386,31644,8627,49001,303600,29868,63213,9103,77280,71333,9696,138789,37059,24823,5057,21352,32368,114208,56803,19424,10445,58514,8661,209508,26187,171838,10460,63454,14016,122504,41328,21329,46618,32493,38225,7855,31763,7945,29876,8734,6438,24205,97490,139977,130740,47323,33195,85390,57194,13813,60600,21313,96251,7699,27584,170521,139271,1363,4402,336738,129223,84983,69150,13147,3590,163929,207225,155260,55916,20288,4503,8398,98490,11773,27512,37113,84976,86558,28365,11756,116005,182148,13733,115313,47644,67208,85069,9347,14995,226141,14704,101835,41159,35314,13113,63526,214039,29978,50446,83339,17440,129441,72522,118641,97816,24907,73844,15717,118884,167255,96509,162793,30847,36849,51297,78974,77793,10427,1873,2972,9999,35074,28190,64297,146836,46298,60038,163007,108919,61219,2403,75022,127339,4233,110389,69022,9833,128097,88016,79390,222936,22570,94657,28462,56956,38803,81536,30474,152794,19566,16481,147408,74574,81895,20731,1918,1366,76367,187321,54494,24366,21690,61696,33283,107477,77499,31112,414383,74362,18463,218441,120929,59848,258629,201924,69269,454,19989,13054,59894,3623,58908,20681,35723,78523,102680,38988,184112,108087,50944,132704,52966,21699,18860,96349,201411,82697,85395,95658,5093,6427,177894,44191,32755,26961,155739,6249,31310,81030,26574,84311,120155,86730,113535,7424,48888,13516,45747,98098,20077,183995,81945,43210,26704,40420,75831,45648,11180,6855,57927,65528,124096,34851,2598,156633,107572,127352,38169,123845,60142,62722,105584,232364,23211,68120,1601,22169,89299,747,258039,80572,7258,152249,11862,101204,8834,121434,33761,19175,133142,46343,40178,48723,3589,41977,30210,38868,62257,10087,82658,87827,90646,16415,47552,351723,28298,72225,91146,272760,1701,11295,1652,109651,300747,51863,198800,29446,11794,32345,37538,22356,33102,37590,113544,37970,11478,179743,25454,103417,59905,221970,105196,145604,7817,164809,102360,16974,75840,255333,56902,6659,1954,645,59400,67769,7689,18675,5215,13793,20536,27852,3387,29523,259718,16860,94625,43143,29245,15848,233581,22685,63631,78557,22836,133302,84513,1348,51826,47129,98836,58284,1830,1749,94642,10933,6145,12506,10975,13879,103781,144434,10268,28409,32346,52968,121567,107374,77268,23686,35097,10501,155275,15303,47136,21102,168741,55332,90385,15996,84817,681,137803,25054,142275,6163,38175,8056,124296,240642,65621,4934,178205,16101,62803,60964,18230,100622,76465,44689,14545,9543,47514,16852,93380,28048,12047,107106,37575,101485,77047,57326,34819,96137,76916,6469,46264,115983,75768,87668,69942,13027,165,8373,114231,26434,52844,42799,182044,23580,146254,38081,43236,33883,146220,382894,14606,46035,36481,166621,35417,95382,2957,59384,60428,36358,66343,75378,22267,22950,83528,17577,56474,25285,4619,179691,75355,95836,53295,34588,171410,4487,14679,84208,44015,18562,109133,54101,11531,86052,174479,303157,28095,9953,35642,14564,39802,16145,77606,117406,53038,121117,53624,22062,1212,7632,127157,237292,189087,10478,127345,102515,181997,86752,87623,10966,121602,68783,68681,83042,114380,138349,191305,67176,50085,39016,1427,42384,1412,67118,122616,72389,25260,2237,13576,137346,19938,20304,2191,68759,5373,61364,238507,75814,23931,69565,38993,131741,38364,12528,87762,5679,129853,5310,186831,32653,90338,260176,389531,108118,26843,43985,50175,30563,25106,56965,18130,140428,4542,165503,117991,24219,229605,1819,129663,1240,3797,76093,18398,71339,51919,93043,27175,47060,216257,6483,35051,1217,16512,80798,129064,13225,69339,8548,237079,72298,2575,34280,51379,117910,55671,53345,247552,29486,39328,140821,34681,57045,60177,5004,90269,78522,2479,322607,48474,61296,13057,31558,4678,59271,6699,27044,31988,35944,12503,83480,4389,136508,3781,114121,70279,4488,155829,42214,2898,68191,75695,305850,45041,74344,106509,30087,17429,93292,12477,290,23080,114802,35714,18751,26554,105424,17775,2144,2412,100610,65192,113975,52975,180272,135050,129815,76238,106483,21440,63186,4260,46189,9711,28249,4169,23429,23390,8324,141585,63809,67668,38457,38063,39226,59972,1189,203916,62368,14403,16949,61767,85801,1739,40147,35049,76757,33124,62102,15780,103593,103009,53484,22952,67973,114645,6566,5245,50462,7601,8288,3513,194571,80276,1908,54592,5124,58571,2513,6800,273997,193904,1119,17991,117245,2508,129156,82366,26278,71465,63341,56943,39662,106116,94966,156875,9736,2204,122308,94418,27134,1280,24539,49022,45314,3764,50904,46424,30699,28087,293839,9400,33646,40165,822,147499,50263,116179,29085,11863,31314,5578,17797,5104,12454,1604,15342,219206,10232,67800,94261,25872,13565,90339,78971,75377,26649,41184,47695,11514,35369,20767,14227,41953,309396,148270,147938,33074,14453,27499,109019,39018,25738,240196,158931,52820,8612,95853,21524,137010,84901,70869,70021,116794,48404,38771,6732,1070,70990,187297,49140,5238,576,3564,253975,16027,16483,2811,37775,19034,25259,4053,2e3,70083,95774,19713,33431,92703,91314,42381,288770,48194,95985,3991,77418,13406,241328,245086,56533,35275,62725,9246,51924,70181,95331,16163,31410,79016,39312,120878,119371,275987,80124,27712,9186,220,23598,146167,85209,68238,282190,57048,31273,30555,80913,17594,75779,59160,135002,101219,189377,29225,96735,60126,62522,104e3,27620,86814,17240,147533,11001,5425,43682,410,49460,87270,69480,46315,59448,1816,76201,9431,11788,87960,29063,65539,47347,11678,33846,7008,196704,9895,6753,8633,120892,59970,572824,115934,6646,202559,892,48351,37611,251282,57823,67263,57750,26527,34485,90747,7685,88370,6144,64182,1709,41969,21458,62327,181657,49247,225330,122600,114574,107124,85361,111833,63243,71420,15655,191178,72430,18063,51425,54002,12364,53225,86557,18193,97580,41232,138398,67821,128724,8944,233212,101353,52099,42127,14006,120107,32789,32132,3498,18123,33758,56058,5779,128760,59888,98869,18445,84702,51911,13234,218379,20093,39031,8074,70195,20708,23462,24355,131384,60189,26390,10403,41060,7140,10781,49410,42261,87202,82566,41663,43105,60276,2768,5733,74176,28329,2297,145430,131632,83615,122915,105441,655,224102,5284,136426,67763,16294,188511,32538,61049,27893,3394,13951,159099,28542,17930,145360,9492,190122,32285,78855,26440,13570,58648,73908,4239,124561,2444,74172,53131,11468,10794,73566,11623,35343,64710,30481,4163,10328,38309,29901,10538,154377,76132,92405,24839,11679,3465,13449,11637,7824,2337,57754,1260,14458,41118,19878,38661,13416,159180,37074,163164,54137,28627,52134,184900,8520,40385,29546,30502,22386,66527,107458,6850,24022,47983,30603,35083,8934,304066,39500,9,28261,33026,77251,9374,44833,116312,34990,29236,63563,125639,135405,165398,159055,55690,88141,69643,236964,31983,25572,20436,36746,60896,31850,16179,11828,5888,3043,66368,9750,31167,7915,53111,36430,1333,64344,93659,20061,60596,180191,51630,6792,30244,43509,101058,22409,420,44210,109783,43223,27030,72477,72831,32679,29235,7675,47556,12258,39907,149412,84926,118247,24692,71717,105038,86009,45941,41189,89453,29856,52543,30627,226798,67303,59230,67415,34408,1367,99685,16867,128419,52147,4111,125381,117881,16173,44093,102224,31575,23234,24870,83790,127407,239098,3200,994,1255,100903,242275,117266,55116,38205,16140,29662,11307,40414,208793,123355,56470,4862,75600,30119,58218,70828,24075,26974,7802,192353,4851,5475,78720,66596,3409,28573,64396,30381,30690,59859,88256,5406,99945,103064,34463,37727,24238,86643,60088,4057,23741,5967,162904,38240,28356,93858,25510,122879,6897,3278,7057,11971,4400,35461,211413,21395,59615,39471,87233,55795,128426,3051,22470,41950,14705,3974,180108,80476,78442,204996,91987,15634,67610,139015,142373,35611,51134,10387,4353,153456,57749,181039,14183,68447,151532,21107,36452,20551,3186,46247,46383,129666,88736,140662,146243,2066,8360,7978,64818,106963,17896,47801,10723,114821,223295,74192,3293,3393,16987,74064,11277,91622,4270,29828,27951,387869,103235,1374,61988,120083,477,145892,128378,11779,211263,61354,18221,17869,46530,83061,108538,157981,90608,67199,95080,49064,195814,12302,66307,10348,231346,160732,112859,63633,146558,21271,31037,198802,47622,12862,95710,3910,77850,73961,85585,34752,61e3,4082,24595,103679,71107,8208,79568,150019,16615,24961,139857,32664,197366,4559,54735,32696,4126,162019,75698,13916,70108,159638,19834,9349,24675,175560,49643,18206,52459,27992,10809,88865,401975,133172,29e3,34558,30915,3658,25834,42430,36562,125265,18182,10155,40149,97082,208980,19575,60853,90529,66545,9600,789,46420,2317,88593,55595,98980,115302,5742,169155,1073,177901,3472,11189,63711,78643,65472,50459,127979,93,42202,67053,21720,157650,11145,141378,42033,22824,85705,79114,35584,15974,1510,54172,28562,12451,104226,19190,97151,73024,20948,5151,81741,21499,29006,84183,198074,54003,45120,170125,26240,35177,28389,64863,79974,60778,176915,232183,45342,2038,80253,41564,40703,32689,5430,100689,5366,23007,134279,14266,26712,73993,24934,64242,52113,102887,61801,46415,201049,54251,62133,122757,164883,30815,139966,2319,30842,766,13362,10287,134518,86111,81665,82440,28333,43019,18963,8804,161944,23439,102144,101145,80029,39052,248708,30350,117340,11878,128467,974,138625,63961,5237,74778,61834,67040,43814,13690,65947,33809,232476,115258,181745,28824,94013,9510,10246,93722,81976,7217,114383,3493,16014,69045,72692,12145,80981,9507,6692,1620,60820,330444,35474,33962,4797,7053,295463,46445,27026,12491,77988,49524,35675,90947,29114,166705,101385,133782,32704,6186,84595,176031,185623,45966,151302,63069,1699,107491,947,15458,74452,196212,6046,10498,12163,10239,35191,243951,9277,9090,29539,54460,22820,26514,112549,60372,51753,48756,21812,70861,260326,41,44222,10441,16961,48148,138771,216194,5914,52153,53400,212036,56519,26245,10117,45888,15294,138019,90913,26368,43842,42111,23348,6082,194845,161089,156206,51546,11647,30759,302912,262094,8635,78876,26535,35283,54183,31183,85484,147873,12989,5197,6356,72894,65347,20150,27370,73787,1493,45918,12366,190217,20724,13858,10981,67449,81213,7553,14115,72242,271517,11842,48310,88743,143726,22177,3290,243231,58452,62937,12592,1654,40066,33477,13751,9921,128442,15868,7106,75236,83773,10775,36938,10482,170465,17368,17469,161508,32752,98340,800,19824,264456,3901,87319,2867,26782,9630,113102,185815,24197,44584,86366,40224,3636,140916,31731,267731,9567,53678,72984,29389,27963,17106,50282,284911,60170,8322,12608,23374,89652,5268,39044,229766,8869,151350,31436,177342,12269,183212,120418,116270,2843,78888,69192,7865,184099,1086,129897,18383,70508,20242,18508,229924,124569,35749,50589,55626,9884,83115,40971,30671,18135,14452,38861,17844,201826,5549,26413,17189,13561,38539,10679,143331,3314,36785,171194,49685,187713,67506,4618,104039,17060,195080,50648,33159,19238,67559,134840,28599,157523,17130,38064,117398,94355,31918,13575,34538,40326,13997,3494,348283,62481,26862,3603,104426,244363,153709,112487,304612,199674,41239,35545,54869,293005,28223,26277,26899,4533,18518,15492,38587,80488,70485,160395,263,60162,11382,222152,4696,250751,51921,182609,10707,48463,46243,1227,49111,111564,46502,33342,56846,68541,63559,858,139927,16654,229375,76759,26478,33205,95828,23399,92945,2637,35630,28470,143992,50214,14174,21456,166191,65665,1711,21594,78019,97599,111701,36,147151,110246,189022,43021,30397,40757,131935,42065,73335,48039,26596,28984,15102,2361,7421,202167,69744,43766,52826,3642,83304,33873,75140,63169,192389,36551,92748,13039,123959,233220,21738,84447,77230,20228,187852,19095,25799,92136,108774,29237,53947,2299,118106,2687,8830,42331,202924,33667,2023,73763,30704,19363,19779,16737,35629,48081,24068,101013,162338,291912,13749,24745,328289,167679,70086,48299,23306,16732,17801,43322,54589,3586,63653,43624,53474,925,109177,251316,43805,13082,19511,86565,142182,92461,17117,101033,103319,64589,4022,4351,235897,5352,82705,107142,46391,156084,5860,61365,10558,13045,7717,18357,33922,12590,33065,6928,46993,783,46937,67846,8952,26295,6107,119656,18799,17458,50747,4229,179559,112727,118080,20683,41464,125468,51560,49749,44231,7359,35339,62988,136487,67015,5208,29150,24956,105186,48858,6143,18097,6972,16404,73489,58742,97196,36357,164616,5834,32267,13746,147733,15113,132091,34127,106298,39729,106426,22294,9780,15602,36213,71502,42808,66802,599,60755,5851,39120,67363,108623,126368,72770,91263,32486,30596,151717,7951,52002,43103,11768,68942,40901,39344,24037,127500,116890,48403,16926,86750,17745,48648,159545,34460,58419,5634,114317,67865,31462,23352,24010,98185,125708,69686,68337,13610,26271,70691,2980,4768,27225,102402,75453,28106,8104,6931,1176,6274,6475,112635,22498,6176,238686,26832,28893,90319,14441,15682,15087,39517,45270,109134,104440,45965,47645,81772,7876,52683,87720,12898,4505,185665,2769,113401,15664,57592,105229,137381,97059,119268,6876,43309,33886,128363,35476,144249,67013,143587,83367,25703,91436,59347,53236,2289,16519,19844,46309,58558,99834,23313,218816,231303,36388,51333,183535,109792,139277,54306,90139,18235,8275,32710,37677,82464,86025,92204,88842,117723,37570,128723,234242,76350,73795,34896,148247,58424,11105,11744,45746,63372,17118,49772,199520,81902,38004,22911,33752,3125,1995,53792,4689,26909,108150,146062,69674,41811,161444,84855,8999,28561,16731,93937,3189,21967,24890,22943,1356,145300,51569,28802,517,118679,31703,40607,48098,108854,25003,10233,73969,177495,5248,24516,215347,146192,48712,60626,69188,40735,5866,586,101541,6509,47590,52129,5969,222045,110933,25733,24223,65339,62812,2414,155418,35819,16022,78423,43138,20995,128255,240673,46745,236093,72176,57085,97841,61248,107,36068,193177,105427,55726,215229,20446,47228,100420,87091,14429,121708,23605,21157,187721,21880,2997,203976,99166,95068,25877,7724,98925,83401,4829,13182,18229,13718,239662,38653,116505,153497,30589,89029,38962,181302,43853,78872,180301,4786,248240,7401,106136,112590,77745,19731,60880,77789,125748,135487,5975,48627,34084,12419,215770,47557,254582,10364,106495,21856,67539,88981,38805,21428,48732,42316,12149,16078,52808,25327,51322,33850,51147,12253,122354,46077,56483,254553,115417,81834,150991,94662,86668,7381,12841,100650,18218,15741,22372,68294,50705,15535,84660,61887,22553,72299,31361,24824,17743,46820,64288,31582,77006,111674,116384,30760,80920,86149,77192,51979,79691,60342,122805,103800,240873,160744,233114,78962,54920,8608,3484,316104,72548,24337,5088,230040,21926,10172,36838,26,86221,83458,102176,12062,17571,41929,41170,28428,68239,41750,103930,2634,18313,53019,34825,97837,63115,24606,73157,152474,14715,91439,37033,109806,140259,30668,174760,380,135597,95673,136073,65073,134249,13829,17279,122305,4420,46444,10237,64848,203623,70728,10349,182885,65075,24519,25783,40318,34139,22222,63394,55266,102764,41422,20126,65100,90408,53640,35128,48932,11192,38935,96839,34782,39492,19396,41332,6250,5511,19492,51304,25936,104466,54099,73771,86115,5080,7669,30891,111700,13931,25276,72289,135447,14820,258641,25265,31005,281179,75286,393,95359,14623,13584,6680,101227,80173,44933,76666,54542,13244,39348,458,25379,109451,134348,81143,6959,65554,12027,51311,8716,57589,140731,28467,23316,17272,30458,25980,55229,77197,83798,28302,114784,7428,34548,26241,14712,39336,103304,18928,54080,12870,334,87722,15208,16895,142098,114262,39820,83913,57817,28682,7721,14900,108672,11250,62246,42849,415188,1724,26555,24549,25505,26443,107450,145899,61035,43528,6901,60726,65906,267741,21338,147590,42079,18924,73017,135236,15393,5206,4026,84185,1531,5988,113890,82647,303391,7386,69844,71611,189865,76523,31877,13315,19314,198575,32821,1928,67641,25913,104475,103489,3297,70391,18406,15446,113347,19295,93790,27856,1792,167471,116449,8541,4408,41757,63233,25765,86680,64501,27034,24816,34975,6079,4486,49693,36229,16917,21581,62426,27862,11612,54284,35702,194034,355,24277,48262,87411,70504,310164,118018,12516,47559,43502,57433,107139,9290,66533,80863,14634,34312,91725,28606,21342,67241,72355,43244,375789,37402,174015,105070,8342,44167,67494,1890,16365,11723,271002,1865,47918,8350,45564,27742,25110,125803,8553,49504,81925,62211,4534,15491,19011,80373,206920,667,102405,128623,245524,5553,113309,192739,65766,19567,22832,261958,29679,21293,71134,20962,105123,24721,860,21752,33448,18372,157167,94822,35770,173224,232737,75729,28937,46828,28062,25453,5207,140366,36665,30652,6169,67920,150458,92040,23186,184604,92330,20891,176492,49427,27828,38305,42495,143982,49560,25503,90043,29747,65328,47830,12932,11068,77721,9003,25213,94205,140426,46090,89945,138173,192691,33329,112232,129905,35709,27514,1841,19957,31411,127476,53572,17497,173549,55063,175135,19841,69314,5192,237921,117660,150697,4060,273045,50414,98940,65348,153665,164423,58804,156695,48994,213928,86036,28608,8355,39574,34540,16927,135680,18374,151587,10830,53805,16878,16623,4282,48030,8537,14986,46102,13062,72897,72,33050,108227,39451,45935,651,113320,40535,95176,57450,48843,5003,19019,10407,211163,3848,1068,4988,32091,30095,41692,15099,43602,107434,50744,7627,171349,16313,150832,352665,207750,33937,38256,51091,156e3,87889,90663,84175,24908,114900,50365,31494,83829,5398,169342,47521,54818,18935,8356,43094,41212,174536,10082,92550,6678,60614,23355,69721,14796,34149,128830,58187,3179,208,40325,28399,225029,401412,51150,31580,207268,6657,10993,69818,64282,289845,23308,12961,38447,6681,52944,31855,2572,47646,120728,179148,37240,45196,218274,4816,3695,21961,50084,35209,18073,51452,27004,6100,33941,1377,84831,171214,85,141510,9078,99227,32610,6417,11718,49868,65579,87902,73018,49062,46280,61742,21512,40862,107733,15941,29168,157765,144919,14487,5767,158014,140070,7241,573,71584,16921,223566,40331,179473,35081,47926,140885,41508,52104,59180,42310,32811,29048,123517,102413,80208,10104,14746,12649,153641,126022,37965,113017,4171,83,142592,2809,6362,50416,71323,116894,260776,16204,1524,5760,30351,12658,20703,54403,36083,45408,74772,4946,14485,50759,111222,10890,2195,167147,92962,130534,16283,177256,35016,15472,210156,151187,73922,117691,43250,52051,37392,24811,24358,30830,5775,818,21969,1476,127322,151783,58392,31021,106913,65215,89407,90802,28531,11690,20234,95249,44602,37256,18707,11928,5161,4410,26571,51903,49768,22008,25252,65780,209499,68769,203726,13249,137363,48845,86823,6658,5674,31881,1083,1823,108676,34518,166752,13791,14287,91576,91429,8665,11529,26401,16191,91972,30964,5254,28486,54697,79613,66520,18447,22870,45203,194466,22822,51703,12278,76716,44595,73455,33546,12235,144843,36154,51247,11116,33040,3180,225753,60864,1972,28469,12891,28879,10338,144157,56294,353058,38302,41447,87532,110616,27065,168438,6557,1213,50804,144643,24817,2390,136531,38174,247513,16190,4059,122791,131994,137430,39506,57650,16305,5188,54309,106128,20628,88071,67394,395446,250285,66176,91254,1399,114196,43915,60230,44853,27206,106353,43013,18733,345105,226453,51202,16607,57106,117175,35492,10476,89598,127439,15187,39624,13688,61570,10615,31111,59370,6238,175252,32143,224492,41388,95408,34384,148238,78307,38959,9340,160091,61443,15737,11216,41244,170,38299,102443,113097,26382,14027,33707,3957,76300,66160,19431,18900,6952,1717,108656,82206,188021,257335,27295,43999,41210,31777,46956,57457,12657,11489,15697,48060,204748,53583,82422,284790,30503,137341,8120,19615,220311,15991,10217,63424,9808,67431,70976,98221,4491,15177,28535,144789,751,13230,2394,1504,33977,132104,30316,22230,931,97193,185240,24826,22687,174322,15307,22988,1390,188745,180325,29580,59068,74903,18994,29195,79,15436,7622,38462,11566,138710,44828,45774,37768,99236,68137,84083,19282,22698,17134,74807,126662,173497,46248,16938,119735,3212,28292,213652,49013,9975,32180,45660,86250,4801,68788,95490,77482,113751,11994,44624,94452,46839,128497,100316,5798,58588,73184,202987,65417,37790,88524,1606,43156,97964,105717,34947,11203,100060,37742,130074,93653,107799,94311,196106,41347,8035,10780,16390,27883,118236,167395,1979,25006,19375,31628,18916,144723,78502,114047,103107,86492,107686,5844,20934,206963,23556,22591,16562,146333,20167,10471,117434,33085,2863,9740,36669,41849,37271,22790,18209,28979,8231,12952,54408,21731,25130,45208,55748,138120,75826,414,29593,9925,292865,25999,683,123149,7036,92159,86055,61827,103680,23176,54918,58466,57578,13305,5709,86479,16697,31064,17660,200919,10770,49793,33423,32370,52047,16488,62555,6459,8426,83493,7763,59725,82812,18628,67760,79405,68557,9612,7673,28102,56517,69620,171797,32458,29541,15870,81109,32080,207644,71495,21202,11039,91036,61230,2810,130800,32260,4613,60590,37112,75214,33979,126402,155062,30642,63875,12810,194463,82799,47664,16725,36685,43367,61099,449,172150,102867,21691,301838,36745,7130,18671,57316,34852,38034,54182,35578,65900,99486,19771,3456,2658,16914,99866,28390,28109,8262,21147,34353,20006,4228,137085,1675,203023,283196,198286,214375,163329,290603,152574,40471,83506,30068,14730,23177,131539,34759,27668,32178,71896,104799,116305,85430,119262,42860,25160,8911,23428,49437,105322,6519,16203,6349,74711,1230,38045,8540,75165,44736,25909,51026,317034,4984,32281,91312,27060,44431,17817,45363,155937,239085,35697,59784,91993,29531,126740,213757,76560,167776,285273,24262,8237,65030,41160,74437,48804,118916,13159,37842,1031,75349,1478,11655,108777,23435,277425,101734,67469,70231,124711,43532,28514,65526,54956,1e3,21882,17728,25302,40952,52214,149632,1999,2111,3259,63362,89961,220561,39777,26335,9063,10572,12416,34551,34623,38604,24723,5947,15588,69927,66252,119177,69173,46629,28714,70715,212408,20521,406913,74380,11716,50659,50862,37009,88460,130101,7210,53853,538,65120,151950,55806,163748,52837,13153,21100,16674,64536,6091,138201,44837,58547,3723,163,2177,32288,85454,34033,8497,14282,25742,10535,10741,79559,117493,243787,49337,100718,79495,40139,42956,7551,55433,15421,31509,23034,45081,547,61176,53434,328001,8470,36263,30145,4519,74173,53935,11845,73774,60211,78025,3,4102,73782,109293,315332,48412,26683,13714,6865,20128,18490,104141,325,39470,171970,115860,15707,7268,73301,74336,31370,2368,111827,107757,136231,142844,97138,96638,84053,38691,23801,1588,10573,122098,77039,240,186135,146101,11996,18143,112963,46171,155836,348769,47795,121213,116266,132515,3344,144804,31286,99187,255838,129694,35894,48779,55235,148582,71967,65282,15174,13920,47080,6147,108242,157593,125025,7136,1286,28957,127956,28402,98813,20805,7532,109417,40610,5041,32958,15142,18408,108596,33543,50517,27748,80114,233434,91447,487,37094,100048,30541,43477,10639,89862,155868,37667,8726,60684,237903,73408,99589,12190,38739,97348,3914,13594,2680,149016,13907,30171,28343,23530,115225,61104,35821,147679,14337,4297,244282,24085,326976,56428,7851,21303,131620,71446,83253,68692,111870,5224,15813,38197,49026,45057,13660,3306,76345,40671,27905,91072,996,68527,62085,91351,122634,55109,168209,2024,27560,112707,17352,8306,167115,169921,166958,5031,46020,11844,67284,19130,76185,6920,32849,5450,14610,22451,21002,17392,31872,66682,84796,13709,40210,59898,12029,8719,53564,21462,91884,21647,88379,194428,12754,37797,132826,160016,22567,54383,53186,77611,31107,8339,4694,19185,90355,23597,17222,140675,28442,23668,55977,9128,61555,28774,155229,17658,9390,24379,69357,15752,127381,239631,62460,93181,55913,45133,140155,18676,25249,33164,29581,82837,67223,22362,29975,7317,52813,1943,29613,20012,207130,49617,49651,5636,15334,36313,29226,28084,95247,72072,19e3,224932,15811,114,32127,38097,37508,88507,37225,27359,91626,12193,69279,20608,11055,88156,92808,2152,57259,55275,72789,24475,104414,1708,9882,3818,48661,66897,1631,34806,227930,85815,87753,18321,250664,72733,25107,206797,50891,8082,196411,92596,96764,152823,65514,22819,387277,62176,51225,40329,15563,189,3659,73670,64357,51793,275136,33482,86653,74615,67058,11318,125720,15388,22388,8267,1730,102663,170910,40784,7144,85373,13040,7088,94309,583,44224,140424,77439,18496,164026,36578,4722,9151,5824,63365,26510,35199,40500,79277,32495,44614,35233,9566,203293,152144,7097,2330,183480,98629,13423,330887,44130,68600,30939,97829,31012,345465,56747,94879,4939,160027,149761,99423,46099,32251,15332,8761,96094,128555,5763,235318,222223,55729,30241,55420,201746,3987,81382,8259,49325,23287,7719,24633,251100,92311,18591,110533,64759,170260,393860,7175,21144,132887,3593,75346,101277,91109,16387,259187,11627,57459,173829,44694,55780,49797,89192,120443,62622,3904,14814,23887,1027,112258,64955,99800,11132,66353,36202,48624,18158,88481,96882,43059,11040,2455,7077,21651,181159,99126,100434,61388,68186,19161,110468,120052,8819,55324,41494,7014,37689,3618,87729,92615,207943,9823,128657,12587,15857,6379,67628,51216,71775,157617,63244,1503,3864,218754,110864,5769,21492,7243,1192,87921,85529,31512,18537,42698,35350,73510,84474,34301,8991,21013,35034,566,38832,19838,35586,37216,39413,55006,12178,59742,856,84563,6900,25632,17437,49786,30723,13847,70845,4044,7843,23944,235976,55530,48942,6518,20939,73769,192653,52936,95207,23895,132542,142982,22632,87452,48042,54018,178468,10728,26230,23559,363,81269,142012,5718,346258,31456,84333,246476,51018,66692,101804,120570,39962,30373,70593,2864,60541,19425,54209,104092,7201,31545,48018,25865,15442,46257,40443,8328,6451,111782,47527,97754,33046,470,245116,31095,39,91934,87208,73470,36708,36521,12801,70624,36272,8892,79768,12427,55454,103756,5908,52390,62962,22720,141138,94634,41689,128402,126390,6628,106394,35527,134394,82727,254651,194502,148064,89549,3202,28359,957,21954,27906,49840,142747,8307,24206,48978,1186,71728,133038,71474,91306,6333,110959,74600,70387,18983,62609,56057,22970,1147,135850,1321,28834,3578,59715,102227,32827,81415,99952,55636,257598,390,22702,35701,85872,402916,39216,189795,14929,19467,10112,144422,61514,5279,63421,134686,41436,8424,51925,10598,132295,124416,4604,194739,210929,57866,31829,51626,50007,9976,91878,61906,56168,81906,60918,61859,40017,23059,16887,40927,62064,12785,32893,32913,21782,93965,20169,44387,79084,38463,11457,93950,27127,157050,2697,337088,5116,54128,48255,33279,8821,27352,25515,124022,65710,28906,38557,33390,1722,104435,72215,38551,12094,30978,25113,6671,37355,175109,42862,98024,65406,221276,59624,118012,64637,78760,86697,21426,1639,40350,12584,67193,84144,31396,7863,143011,69629,63112,9454,28666,65798,46372,134721,6314,51402,30837,151922,2847,38676,38008,92823,136245,17540,5504,109295,205242,37606,5211,214892,1586,20670,208711,137743,19328,40652,16995,20023,14657,154919,34422,12996,13918,38221,47690,16398,2959,37680,89122,6721,198469,91876,172043,83898,101992,26084,94570,3635,76958,22853,76497,38266,176590,168403,44464,142840,79180,184594,1984,41806,83147,11985,6546,366068,59732,24533,271505,8736,39084,222992,93429,28962,58985,86665,8432,30028,14548,32439,54424,165029,55175,27458,69046,121277,46168,33732,20661,24581,135574,123110,37556,79260,72611,16957,12939,46162,58238,44907,72936,253758,41324,32518,96480,11949,124438,65280,43256,34107,53533,43531,37037,28366,45970,32741,173438,6121,194202,62969,26355,30314,58370,28455,1848,50519,82830,90393,21761,295490,10936,256940,133568,44050,20269,4089,27457,21610,219460,36743,14821,101388,52005,13124,30979,140816,167362,26054,18458,60789,34917,40447,26606,33422,9066,3452,83614,5761,20263,137238,25038,91310,101,52322,74548,42572,38084,214054,186568,31802,17665,30620,141936,37730,14420,4265,187218,49640,188208,51441,55388,96452,66659,40869,42039,60967,221027,19234,178581,29105,96050,9165,196118,157335,3738,40354,117436,2965,34136,59659,15570,50843,230035,31444,71260,43886,18316,5387,38500,168508,17406,32174,8828,103373,143806,90367,3560,18719,122310,16508,26719,2541,105429,6645,37998,73190,10591,235916,49737,87112,233941,53188,32193,79154,4544,52905,126477,7580,63501,57314,3216,31337,6541,103083,60846,49,9756,15481,1355,43840,14319,13743,27486,10222,73114,230718,418644,16706,6674,279748,23058,45273,295831,86306,2743,5535,88773,21829,35253,120938,31153,3169,16839,42847,8751,80974,33942,36867,35514,16485,26474,77775,56877,5391,48346,3882,108713,31403,27804,55248,26235,43821,136104,40118,175507,28034,203908,18732,1788,34030,106427,36958,54359,7251,44936,15356,69139,455,157915,22173,140291,50348,43275,82066,49621,54952,15216,36226,96695,66855,6936,1987,8227,196087,4631,68827,99004,47541,110265,17953,147605,110242,58520,31312,38724,329975,642,3155,34497,75937,6207,73843,6120,17249,51429,117746,3218,910,68961,319671,14938,29555,34700,1649,66673,72268,9655,76800,153087,6941,210168,27130,35398,1780,73242,3135,56689,19556,165307,8765,35967,121458,13333,70453,17350,117253,22265,13340,44265,39869,441,3742,135025,23581,33309,16543,17731,13291,157637,283005,21408,101360,63887,52312,83873,5338,233779,23759,186949,34531,177320,38069,156465,91004,19353,59852,68160,14891,1338,1072,29823,1950,28901,81407,313445,73038,84807,162348,240257,37162,138934,16111,58013,41253,102951,16457,96056,19541,56402,67217,41638,94381,89674,29481,37456,80815,151579,13937,13683,132537,19699,134545,67020,29816,222341,141235,427578,48868,129557,233342,23077,87871,16213,18728,16184,9469,37913,19680,2798,171356,178328,13216,50049,72690,71904,124644,55455,7504,29052,41036,266546,19899,30391,188755,8659,59469,16,104298,112943,53865,76203,138226,68857,139953,14125,107625,119795,173133,4398,50273,48808,54390,16466,122086,31835,67035,50971,48859,7508,46427,66477,73021,84615,39985,83076,46779,201569,53336,36443,60865,168164,143810,51393,25548,169307,32896,24485,38424,21837,29087,275813,51674,6714,64883,46169,187369,55186,76192,12852,12018,62134,31067,118303,16542,12125,10579,4928,26291,43854,7091,10946,253716,109062,39283,17261,113012,258512,47764,125126,32646,55892,80279,201623,149872,3192,385,1208,48750,5376,58738,22335,5427,82416,47811,32435,143086,38930,94128,59975,156037,37977,38224,62485,7698,50405,71027,16462,21559,136153,34131,107506,162069,63703,3101,215029,40407,4178,3774,9187,80019,17880,97926,67579,2600,18405,8351,47924,86638,70820,92206,86453,29610,42241,119200,3198,15466,67813,57863,35454,4779,99518,4649,104641,144269,33730,38073,65864,6838,109456,193298,154007,5623,45741,30846,182578,25573,157224,1543,58575,138703,146140,44971,49356,18275,59064,20300,13122,11848,24453,11973,9797,86843,2919,25530,49210,1130,161220,76788,75373,85604,34926,36014,17777,17255,51533,11676,92226,51845,119859,21525,5936,18507,28050,1140,31418,14857,34207,47859,10750,36382,32079,106909,59426,87757,38393,110042,15965,97104,33757,35344,97993,53979,33651,45407,41884,82515,173089,7177,58371,35365,47543,51927,35587,10670,23544,29306,84233,39976,76076,62097,9007,8668,28119,78281,120790,19835,143020,54968,18670,64959,20649,34469,42570,33001,136570,87796,120044,1106,58700,63951,127623,12805,83057,40212,31773,49850,7361,54336,347524,101314,23751,19569,48791,29174,49369,20467,7465,75842,38281,623,112457,60210,28849,51003,94720,6426,90047,85560,43761,3579,85105,34607,90410,118528,7224,42907,111163,18168,6960,161135,191298,5247,100584,127552,171568,20121,91173,12636,54615,20199,63730,98105,2396,40387,14438,125012,4765,33235,12865,45299,37728,82098,77872,114037,59253,19675,24838,398016,102561,11446,17069,57508,178277,65836,99941,26114,2585,271882,136866,50126,11027,155648,118367,14585,8910,123015,335383,40434,41016,53021,14439,87098,176860,201543,121888,2358,9286,5739,22666,54270,37884,169381,33984,93859,16124,89364,72207,51639,76366,99029,65812,2198,12147,174891,194289,6986,30252,88822,21284,11445,288337,160821,33034,100869,43852,25761,52882,1144,103809,1924,84458,86079,43411,13542,139276,18141,34978,41298,7276,26481,173800,33210,17951,142652,33616,33677,2210,19941,98568,2486,192414,80136,12058,235883,50963,249638,29572,27221,47034,6124,72107,63346,97620,158513,299699,40388,23235,37176,224244,198386,121323,67992,23827,63170,17838,106622,158590,26807,5345,23489,91891,55474,74834,37981,13058,5977,72552,34706,26828,145172,19904,21367,34043,960,77092,91381,4733,47446,7680,41697,5170,16960,14741,46101,13656,473,51842,37433,11103,11551,121951,13191,97536,165932,50397,51628,129028,9069,44885,6590,59195,47045,32940,225472,90345,21833,13303,29407,96615,141951,5198,6028,18395,7181,3861,14966,156358,167182,36529,55253,25942,173153,30959,27261,50691,150176,162201,38467,48462,80602,42163,118482,168,108756,26011,17166,54149,456538,22512,91374,13816,90358,131615,18132,226707,1824,28139,26860,42253,93877,77351,65575,8980,80574,22020,27948,40422,91324,76376,13528,39281,91685,82215,122541,144066,1983,193851,17283,26320,2739,194978,4790,26845,42627,61300,65815,174612,55133,4200,191130,79771,158321,52280,166796,221620,62461,11278,4067,88152,83409,31717,121367,13522,47325,37945,10406,174348,249321,154101,64912,29938,51775,17220,15776,166138,78890,84425,54121,42861,16368,24572,291647,10197,32073,22651,11677,97509,26952,35787,18424,41910,71614,94977,72318,41594,70024,275419,37702,60199,7335,39107,61315,18271,18394,33768,87884,104277,123724,7277,56288,71981,189803,49320,3352,6798,14240,8954,69220,94433,57372,28620,68863,193727,85575,42309,41667,67689,42081,22543,44824,12719,28540,114236,101553,27638,27296,4300,5353,4663,19379,94098,3758,95888,95144,80344,87320,28447,259518,12718,71391,152731,37063,24132,31911,104896,15672,103782,1521,4945,72541,23717,122632,15619,87175,206120,29428,189780,61416,28350,44457,972,1175,47233,198738,95789,41907,21953,97034,59341,22864,53713,16873,32971,20693,20954,31336,21477,16169,38370,16412,9019,3841,24599,21938,17085,6484,81198,76413,5849,72514,12320,65247,276175,37234,59796,52642,16312,57349,198507,94148,46134,18958,125552,1747,18725,151873,14901,5490,68287,29470,3689,64794,40814,26018,25692,54450,2703,88278,124886,173087,174e3,24159,179477,24276,46004,201876,209202,445,52876,31948,30206,157610,39180,18439,44124,50469,5774,96278,222758,200216,50290,45486,20435,46986,46276,140133,142326,15569,13363,47522,92583,2182,7135,16853,22998,30272,4952,63263,35623,39096,53789,44864,20053,110392,124213,4630,16087,28221,127787,25839,77481,44693,13464,113146,6983,27069,55717,50102,4760,7107,26186,66507,59145,36032,104182,71328,29425,64317,50781,47465,94298,69706,74899,22754,120756,25108,93077,56834,73286,39928,16218,41699,176763,7555,70819,50083,26895,23315,26014,16773,123079,41712,5719,31516,90427,158540,85051,183128,40864,27505,55392,9058,45224,96857,30901,136622,96557,56304,120061,11501,151448,5773,89743,7769,86069,2935,18471,41628,10114,33660,110170,49479,26745,92846,33221,26731,18795,87076,8550,2100,29972,120289,3077,72490,33784,2630,208722,50861,63483,79029,6419,39467,14302,45286,64207,9686,67513,44170,1050,77246,59266,17055,53801,7150,11111,42432,4278,94579,362117,36175,42902,41933,39002,98489,22913,74161,84773,57036,17556,162288,74485,178760,93867,73635,128860,50362,261,67455,80001,46080,35662,4368,25247,19230,74393,22588,1822,27682,235324,13798,85998,13194,235067,23514,71669,147632,23191,134748,214683,105101,1518,25489,247114,7380,54842,26922,3971,26361,20844,68642,170517,77339,123255,8963,77818,150998,48466,36806,2732,23261,11741,236162,18243,126216,28690,50546,16385,92760,197383,246558,201295,88255,67588,71687,176076,172653,169058,33906,63747,24835,157621,43338,30050,46152,132741,2770,51371,94835,6614,15112,11749,56936,1250,19027,399017,58036,100215,23388,55815,308768,124152,94803,9521,64186,8971,28,30427,62163,7616,103838,35079,29203,131235,7743,17389,10882,37420,61460,228512,85363,41581,131077,62822,119647,10130,54445,26925,19968,29016,24446,74028,24176,61448,67185,9254,8563,119129,9771,99184,37716,39514,10532,221512,258753,218630,55980,23394,32141,61924,66749,32411,3741,36475,26678,77010,44946,91203,128749,116953,20476,49625,53116,13735,102335,29376,51946,83407,67892,59212,34685,21083,1546,112982,32972,74397,1078,190545,16082,86140,58591,89611,101531,10061,105104,76319,20035,17551,52611,169061,190842,100780,23907,90413,115619,9675,34710,193435,49443,129734,11183,258877,16318,136182,126808,44635,27304,192375,2599,125648,47051,12091,23814,721,58800,40137,66726,97930,60877,74487,7942,54326,9841,41428,13762,8211,85383,6950,99177,79806,201786,296464,124087,13144,29741,41721,47634,55088,254286,106408,17041,99064,12942,64086,45233,14005,2612,55827,255,7984,13980,38574,12776,46654,73499,249951,2101,26676,25996,132326,116415,119062,50449,31033,23038,11589,179252,20007,14860,129270,21143,17796,144715,60106,70758,69842,34674,282133,44014,16774,57268,38528,24053,46373,201667,28327,471023,51889,102667,21193,114909,84132,69317,96723,67969,16134,68145,15058,28765,32035,2524,101089,98664,25045,76571,14957,86040,118506,262428,154764,81573,39681,283900,73287,127825,544,80448,52347,38512,175971,15180,45467,33086,46552,48894,81107,43213,36672,54025,76703,8053,7608,13299,56619,20752,238099,54164,105133,1444,32942,953,37564,8e3,66316,119463,106817,404,13667,149108,128597,31267,10269,49836,106150,1484,52330,76965,160486,171648,38456,31263,22424,37738,66245,67467,143369,60471,75610,20895,115528,86070,60854,40796,49347,18989,15030,11371,37578,15779,79867,10187,86462,46402,155626,93200,40229,7090,57547,108053,99598,11088,47505,41218,206017,2173,20988,30219,22919,80563,57566,42369,93141,41675,2407,182519,120495,27154,16702,29456,14349,7958,16688,117177,140375,42467,261919,74916,153569,10836,34742,49526,7621,105997,12212,2270,392377,7755,17959,25086,232152,138791,33847,13860,35316,5811,1344,71259,50452,207539,92635,50359,5821,33674,30255,2086,2587,96264,17543,42,6029,9580,43007,139248,82831,12917,29607,25786,51467,42137,85161,100698,31561,88989,121990,278500,3602,109344,37982,15279,116442,28936,30880,87894,58079,128661,126731,67392,28051,146885,4861,16216,97344,42827,147561,153948,22684,21335,47685,1853,43349,15185,59642,10229,25520,187921,108972,5579,98037,24945,6697,19193,63734,137934,75056,89740,19767,224268,56138,63643,151661,39313,70618,84031,89723,84074,13703,85626,35460,8867,64845,3439,57906,99776,63968,49270,81130,34356,16210,23547,36446,34090,140028,72439,2221,22163,57058,363492,113754,18913,95451,48663,54464,54037,176097,68425,3023,34906,29482,117389,341780,80431,58330,16753,92616,60907,94846,147486,4498,48646,7773,46801,7778,18946,464978,47558,33223,177444,7328,15626,63337,94700,11743,9351,255024,39098,16447,42647,96230,39769,58840,10068,63439,35800,65843,58823,413844,9156,51258,7434,61791,85018,6872,3692,28096,7121,33024,6009,75532,31997,192535,9661,3304,9547,14753,31987,25314,55689,15896,20430,39472,31340,99744,25398,115569,54883,28719,205423,23071,57855,64638,149867,25671,82403,37616,20668,39989,77996,74948,140555,175248,64810,36515,46595,4958,248773,24045,28728,136673,168704,20804,114833,100325,27135,21205,96151,153134,45992,7093,13992,76047,1980,19432,145001,75159,87462,17710,1013,45556,34297,144882,20648,26061,11319,129567,108555,18872,464580,33386,22717,65948,167189,5603,135042,79542,8801,202632,18114,91882,5973,5239,67315,4431,60916,47819,71693,32597,32606,18183,45072,80329,76385,24749,51305,40314,156514,14693,130345,13168,66214,18029,12858,34801,27628,14544,10823,40522,40185,33739,148694,23548,9923,61012,28859,17933,19442,34364,99849,164107,141167,30629,21054,6744,36491,8096,42474,41706,155060,30650,10600,163442,1143,96655,61390,52359,7559,51568,64256,203854,4467,22453,14504,436398,7878,6980,8293,63610,293747,16167,35763,19627,147603,15419,18032,110744,51346,33681,54571,40472,48615,39073,21604,13754,173027,92560,11083,47299,63062,11813,52007,29883,9734,139722,15953,1550,20651,13616,49306,16113,90089,92326,7584,30712,72424,164858,6831,152871,55746,197721,34167,196442,6022,112107,55215,7538,123381,4920,43539,77165,8939,50392,34192,20225,79762,22505,58667,40770,29788,97180,82835,4568,8579,13273,363569,35898,49983,436,36598,3237,131691,62418,35591,8101,4073,379438,65218,76072,33887,2968,27573,212619,288680,68278,72851,150504,217896,6913,121339,22017,35340,51072,43616,75043,31437,10833,81487,4364,22968,41454,106687,85446,19863,109625,149241,524,141850,214404,54376,657,237023,9401,108137,53800,32474,49712,53334,126876,27337,45552,177696,8269,15036,12097,42240,2328,125374,119295,99715,2500,19624,39441,27220,102691,60957,94543,39101,18566,67362,13975,78230,25017,34017,239007,90027,39351,41681,35354,43822,1043,916,58587,141983,94818,38799,75459,41114,67432,16195,36606,59568,22272,126769,31424,68659,12287,134302,257977,5756,207285,95637,47248,117689,19583,77451,22373,12200,54993,117118,34244,29386,34562,53819,71267,64172,77665,49368,7716,59301,25749,45426,194789,17297,2650,1766,32501,45198,20403,20984,6600,14171,94604,19037,5402,29896,9938,59935,109708,88081,145182,44844,39167,352626,164173,35374,45982,6122,154,73419,220487,53834,53601,17992,8609,229321,5610,68098,66815,71012,95069,140968,27396,8957,134489,24656,86659,56598,134852,17316,123838,255436,6613,41610,138033,81452,32023,32396,123687,63398,8693,29712,30407,19296,121188,3551,36099,20032,111948,56624,16547,27453,35916,15378,52039,56849,13489,22214,73177,53097,277349,2157,14029,187886,10260,141743,246460,91880,50869,3788,49486,133566,54950,33120,129337,53768,18333,9525,26902,312251,10297,9020,70759,16647,112432,59260,84609,9818,82766,73569,468,46001,75780,55028,52106,11498,43645,108069,17150,17753,29417,16705,31799,9606,289,122254,115975,8620,6133,255357,56908,14456,133464,43554,79224,11247,29630,160,12756,25464,65960,350428,62521,321796,100359,67358,35169,46172,113128,48988,88868,31094,33266,6847,60887,98188,49659,69117,92977,220228,13947,80181,35103,62170,97351,13475,2440,199768,19498,36597,46971,25234,67806,62881,84717,73648,181966,10488,94149,21550,26655,63436,48375,14405,165650,9621,24439,28043,42735,4490,29963,56674,45373,1934,262446,50855,67098,26898,5261,52696,40644,33900,9440,180286,87162,22940,19704,26936,69769,10254,101759,27406,12243,48e3,73926,113215,54935,5726,192787,4312,106216,9366,11550,52949,23457,212271,277152,133895,108374,6191,96477,29980,218916,58024,54696,40853,91124,65894,91170,65908,252552,6793,29212,15389,44516,122515,52617,35058,9017,103536,39510,49136,19242,130652,662077,74699,47024,31422,8517,73351,24399,13867,128360,4810,4434,61779,111983,61036,17798,110240,59722,102960,39688,10001,23803,23039,176498,56659,44814,134295,17188,77577,74466,226175,102472,154333,63900,111747,18062,41171,79669,32773,408933,42562,28931,30907,107388,43487,2946,240310,23938,24354,319,184983,7927,6488,1422,10790,68809,68209,64775,4361,202,17123,59634,51200,44391,18188,17843,2619,74278,3230,9540,47187,21702,36274,56894,43907,16310,34790,16866,6150,5561,13587,107545,108873,126867,86986,28640,33427,19017,5762,80637,17430,46903,2047,131055,25958,13558,5444,47152,13900,44563,122857,45348,70863,39593,54332,38068,33637,318,40310,143467,18502,24520,11377,62013,28942,27246,28269,83545,17999,59015,90707,30065,15161,34720,1263,37008,2012,6060,98575,92933,5721,299,199555,24578,29223,2985,743,115825,109523,136657,47454,26378,53586,3733,174945,93340,244456,5693,37386,28782,89767,27545,23573,18798,136425,34320,84778,20041,48453,38215,7477,71958,40621,8773,5874,187927,105965,51100,43533,18083,8443,10180,43597,2003,183999,69689,12216,129696,146188,62389,34044,68410,12765,43273,26949,266807,3345,34477,79197,5688,47539,213110,21634,22257,50092,32222,42346,39530,63668,98,134978,74022,5152,59088,174145,37220,9934,9545,118937,5724,87240,19875,15784,40143,23263,87513,181654,285152,37881,263241,4966,43934,10433,186657,6470,74416,225854,25908,142677,246262,32280,6192,75890,45546,143264,135305,29742,47013,77787,11732,126658,8763,37950,21806,57557,113464,89465,108995,164574,23894,22996,23169,15369,23117,17642,130607,40503,36239,280990,44666,9981,40427,147487,26869,168452,32886,32991,46798,240839,15111,70502,65697,88548,44145,28701,48767,31139,206777,35659,181164,166262,14554,171445,31786,66523,76607,17956,6507,31279,90476,116611,167918,6560,1243,115324,80128,41867,55897,187323,37069,32596,189444,145931,13390,105530,65709,26805,6999,55714,41300,22915,68951,22138,21120,22264,10058,19945,33635,56123,99085,10032,5818,6016,46649,57476,35264,94413,112522,262288,93686,83038,14341,23204,28807,66084,77987,6101,126673,7133,38126,5923,122091,170240,97772,46874,215746,43948,41622,3272,55596,8332,146411,251315,13533,8561,81521,115449,48616,175175,2063,186556,3036,134537,75772,29728,82360,22973,186559,86348,89100,38388,82297,45610,2613,87082,9986,177812,57884,23591,47485,42543,33582,44713,74439,257444,252451,31825,35631,38540,33066,5147,13973,4343,51830,70378,22827,26448,95560,36896,241741,48067,203953,298860,61620,20450,3220,67272,6586,107662,100160,108684,6929,57226,4762,7457,1320,40404,77204,99309,62750,208653,59977,44e3,74315,34332,5819,172217,64904,114077,18147,84012,1791,98456,90930,21446,116669,103938,7422,85140,59713,5768,326211,16239,75411,13229,29398,10758,236107,1539,112472,95979,152154,151294,306,21196,38146,10700,6891,84282,109646,56492,40539,6589,119491,51354,30685,140209,136906,29622,73617,49553,70525,51671,166869,139616,74395,37439,49595,45678,11959,33211,86560,52434,9282,62690,112155,130810,5243,108261,99970,265613,72551,80049,6391,33365,90721,66737,69872,87011,1860,9032,112544,60905,37371,89015,140351,19076,850,373531,2802,36725,218795,72062,28990,16550,24614,7815,6187,26336,33373,32162,42791,73555,32062,23386,10244,56392,49442,27076,136262,12412,14883,1134,33675,97153,199281,15608,100152,74072,47942,254301,36451,16026,10687,65067,56708,254030,30290,50490,13864,57941,259331,35588,23485,43486,24869,21620,92971,22072,88645,1048,182050,13343,32452,14825,19509,3325,216938,45740,99716,189082,53740,78245,25609,24311,176777,47340,308354,40669,66085,14102,125339,9225,128709,97207,1271,200933,78439,113451,88975,18324,46521,11819,18570,141756,72512,170020,52754,63550,118515,103073,93330,32736,50499,14722,31600,68452,398867,29316,172786,18417,104924,2606,5670,84818,16288,67106,59580,82929,607401,291,85829,359,15897,35830,50696,65630,52672,22115,356968,29895,40837,231192,34024,38957,26722,406,23335,124952,72068,68804,13268,147101,164740,276569,162596,66943,11569,26654,66358,4777,23229,102127,5848,978,2921,59666,5371,28212,90108,42938,39320,2499,4271,108792,33510,125072,71653,65239,38250,66357,38577,13964,86251,35708,50755,36010,29448,12209,3844,38222,206337,100876,67827,137088,14167,252225,84163,195270,1306,5703,54198,779,46802,22028,51124,86759,70560,113164,35685,162145,45471,34561,422,2611,6464,47486,19223,38246,9191,18331,89942,243642,212364,15893,17518,22617,6409,30046,126182,59716,36560,104428,18846,26592,19458,50793,147333,30826,1388,27647,10922,14495,33545,19269,135828,39727,41601,46931,233379,49169,131130,182112,16276,82381,118209,142445,128310,19672,28740,82907,33436,3118,102206,28723,24819,41937,38854,5157,3881,111491,1142,9776,421673,152241,29309,14961,87854,6054,15424,3796,82656,54996,2108,55367,239450,154525,9643,118103,106041,64601,68549,48707,30266,25772,18740,9462,229669,91798,112152,191327,14493,72828,8175,66636,236474,25817,87351,129027,76653,20422,22983,71240,27846,44661,12399,46158,77704,53101,35032,11072,17300,109294,33638,24408,1895,11241,760,17584,82479,125877,63150,141075,34259,23274,81698,15732,43577,48340,91584,14688,16379,24481,150280,96420,262050,48635,43727,61819,56268,72003,88178,17281,79912,13218,122519,125295,166396,11811,2171,118930,67746,17636,178278,174656,95661,173039,83845,79689,17473,98555,127696,203415,54730,22925,232239,9309,12136,175026,20740,180188,10747,39816,314017,266131,10040,175732,112550,220651,31974,37393,888,23008,86799,4303,64905,148467,75337,251,3284,370102,50264,9835,5438,23655,4481,29851,329,12855,7162,64931,78141,12804,42372,296771,83547,18624,34874,86271,3360,48665,77735,88767,11463,63527,28889,22258,29140,194315,113924,25499,6406,31334,1845,4802,49184,43455,35469,127594,92970,61038,115005,38840,87761,106838,8811,20572,55637,11162,96721,132425,108925,2948,125457,36356,3502,75270,27622,127192,2561,123095,49394,61155,16897,110064,9699,89448,53356,19628,220310,21622,83036,9885,112214,6087,26713,17901,161912,91492,3440,68594,9266,92238,8087,6866,150194,72175,80701,13459,31836,43243,239700,95846,44749,50647,21945,230538,120612,132371,244604,5193,105637,34661,41341,68775,85393,1874,8771,33718,49672,77403,595452,99507,6490,58895,128742,7704,39239,73217,43816,62824,37804,199976,22361,80005,87514,94832,14089,4574,139975,59142,75523,100268,43906,53442,15152,2547,186002,17011,19513,204282,3343,60568,128318,119250,4298,51871,41336,71759,21921,45074,98169,145889,99427,11350,1237,5520,28799,7803,53702,21026,136352,38293,128690,12158,90132,44600,10184,26957,39459,126025,78904,82999,59373,39301,150198,120529,153042,20177,50089,14764,271571,30530,123161,38975,101562,22941,5648,124654,109243,69817,71675,49162,106884,21241,107795,30258,16572,188262,141456,7688,60718,8271,11044,32440,104608,103419,236109,93156,43293,128929,42107,67180,25201,115254,185488,130954,72813,167547,20537,39969,38432,22582,184022,1139,27199,5655,17767,97412,122606,209377,27070,35871,326617,188954,42680,73512,80911,22629,3011,95021,315242,157737,383,41821,41808,19335,27950,15674,25677,110950,35375,76835,59108,57370,35262,16569,160415,37706,78086,32041,49691,137143,9782,172080,50148,77917,6323,10110,69172,17711,21795,59511,76184,135114,31046,132319,59105,157578,20549,80778,57649,158421,65143,4575,72235,21899,10797,92745,34035,106079,80159,4508,78304,25350,75457,46458,32937,25623,47,8531,104751,84953,8138,36508,187199,66310,115274,13253,32461,38536,1916,42007,187160,35055,26325,84394,35963,94216,45590,97782];var W3=15,j3=class{log;peerRouting;routingTable;refreshInterval;refreshQueryTimeout;commonPrefixLengthRefreshedAt;refreshTimeoutId;constructor(e,t){let{peerRouting:n,routingTable:o,refreshInterval:i,refreshQueryTimeout:s,logPrefix:a}=t;this.log=e.logger.forComponent(`${a}:routing-table:refresh`),this.peerRouting=n,this.routingTable=o,this.refreshInterval=i??nP,this.refreshQueryTimeout=s??oP,this.commonPrefixLengthRefreshedAt=[],this.refreshTable=this.refreshTable.bind(this)}async afterStart(){this.log(`refreshing routing table every ${this.refreshInterval}ms`),this.refreshTable(!0)}async stop(){this.refreshTimeoutId!=null&&clearTimeout(this.refreshTimeoutId)}refreshTable(e=!1,t){this.log("refreshing routing table");let n=this._maxCommonPrefix(),o=this._getTrackedCommonPrefixLengthsForRefresh(n);this.log(`max common prefix length ${n}`),this.log(`tracked CPLs [ ${o.map(i=>i.toISOString()).join(", ")} ]`),Promise.all(o.map(async(i,s)=>{try{if(await this._refreshCommonPrefixLength(s,i,e,t),this._numPeersForCpl(n)===0){let a=Math.min(2*(s+1),o.length-1);for(let c=s+1;c<a+1;c++)try{await this._refreshCommonPrefixLength(c,i,e,t)}catch(l){this.log.error("failed to refresh entries with common prefix length %d - %e",c,l)}}}catch(a){this.log.error("failed to refresh entries with common prefix length - %e",a)}})).catch(i=>{this.log.error("failed to refresh table - %e",i)}).then(()=>{this.refreshTimeoutId=setTimeout(this.refreshTable,this.refreshInterval),this.refreshTimeoutId.unref!=null&&this.refreshTimeoutId.unref()}).catch(i=>{this.log.error("failed to set refresh timeout - %e",i)})}async _refreshCommonPrefixLength(e,t,n,o){if(!n&&t.getTime()>Date.now()-this.refreshInterval){this.log("not running refresh for cpl %s as time since last refresh not above interval",e);return}let i=this._generateRandomPeerId(e);this.log("starting refreshing cpl %s with key %p (routing table size was %s)",e,i,this.routingTable.size);let s=ae([o?.signal,AbortSignal.timeout(this.refreshQueryTimeout)]);try{let a=await H3(this.peerRouting.getClosestPeers(i.toMultihash().bytes,{signal:s}));this.log(`found ${a} peers that were close to imaginary peer %p`,i),this.log("finished refreshing cpl %s with key %p (routing table size is now %s)",e,i,this.routingTable.size)}finally{s.clear()}}_getTrackedCommonPrefixLengthsForRefresh(e){e>W3&&(e=W3);let t=[];for(let n=0;n<=e;n++)t[n]=this.commonPrefixLengthRefreshedAt[n]??new Date;return t}_generateRandomPeerId(e){if(this.routingTable.kb==null)throw new Error("Routing table not started");if(this.routingTable.kb.localPeer==null)throw new Error("Local peer not set");let t=kr(2),n=(t[1]<<8)+t[0],o=this._makePeerId(this.routingTable.kb.localPeer.kadId,n,e),i=xe(o);return bt(i)}_makePeerId(e,t,n){if(n>W3)throw new Error(`Cannot generate peer ID for common prefix length greater than ${W3}`);let s=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1)^32768>>n,a=65535<<16-(n+1),c=s&a|t&~a,l=TP[c],u=new ArrayBuffer(34),d=new DataView(u,0,u.byteLength);return d.setUint8(0,ct.code),d.setUint8(1,32),d.setUint32(2,l,!1),new Uint8Array(d.buffer,d.byteOffset,d.byteLength)}_maxCommonPrefix(){let e=0;for(let t of this._prefixLengths())t>e&&(e=t);return e}_numPeersForCpl(e){let t=0;for(let n of this._prefixLengths())n===e&&t++;return t}*_prefixLengths(){if(this.routingTable.kb?.localPeer!=null)for(let{kadId:e}of this.routingTable.kb.toIterable()){let t=To(this.routingTable.kb.localPeer.kadId,e),n=0;for(let o of t)if(o===0)n++;else break;yield n}}};var Y3=class{peerId;providers;peerStore;log;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:add-provider`),this.peerId=e.peerId,this.providers=t.providers,this.peerStore=e.peerStore}async handle(e,t){if(t.key==null||t.key.length===0)throw new he("Missing key");let n;try{n=F.decode(t.key)}catch{throw new he("Invalid CID")}(t.providers==null||t.providers.length===0)&&this.log.error("no providers found in message"),this.log("%p asked us, %p to store provider record for for %c",e,this.peerId,n),await Promise.all(t.providers.map(async o=>{let i=xe(o.id),s=bt(i),a=o.multiaddrs.map(c=>j(c));if(!e.equals(s)){this.log("invalid provider peer %p from %p",o.id,e);return}if(o.multiaddrs.length<1){this.log("no valid addresses for provider %p. Ignore",e);return}this.log.trace("received provider %p for %s (addrs %s)",e,n,a),await this.providers.addProvider(n,s),await this.peerStore.merge(s,{multiaddrs:a})}))}};var X3=class{peerRouting;peerInfoMapper;peerId;addressManager;log;constructor(e,t){let{peerRouting:n,logPrefix:o}=t;this.log=e.logger.forComponent(`${o}:rpc:handlers:find-node`),this.peerId=e.peerId,this.addressManager=e.addressManager,this.peerRouting=n,this.peerInfoMapper=t.peerInfoMapper}async handle(e,t){this.log("incoming request from %p for peers close to %b",e,t.key);try{if(t.key==null)throw new he("Invalid FIND_NODE message received - key was missing");let n=await this.peerRouting.getClosestPeersOffline(t.key,{exclude:[e,this.peerId]});So(this.peerId.toMultihash().bytes,t.key)&&n.push({id:this.peerId,multiaddrs:this.addressManager.getAddresses().map(i=>i.decapsulateCode(421))});let o={type:De.FIND_NODE,clusterLevel:t.clusterLevel,closer:n.map(this.peerInfoMapper).filter(({multiaddrs:i})=>i.length).map(i=>({id:i.id.toMultihash().bytes,multiaddrs:i.multiaddrs.map(s=>s.bytes)})),providers:[]};return o.closer.length===0?this.log("could not find any peers closer to %b for %p",t.key,e):this.log("found %d peers close to %b for %p",o.closer.length,t.key,e),o}catch(n){throw this.log("error during finding peers closer to %b for %p - %e",t.key,e,n),n}}};var Q3=class{peerId;peerRouting;providers;peerStore;peerInfoMapper;log;constructor(e,t){let{peerRouting:n,providers:o,logPrefix:i}=t;this.log=e.logger.forComponent(`${i}:rpc:handlers:get-providers`),this.peerId=e.peerId,this.peerStore=e.peerStore,this.peerRouting=n,this.providers=o,this.peerInfoMapper=t.peerInfoMapper}async handle(e,t){if(t.key==null)throw new he("Invalid GET_PROVIDERS message received - key was missing");let n;try{n=F.decode(t.key)}catch{throw new he("Invalid CID")}this.log("%p asking for providers for %s",e,n);let[o,i]=await Promise.all([Pi(Ct(await this.providers.getProviders(n),async a=>{let c=await this.peerStore.get(a);return{id:c.id,multiaddrs:c.addresses.map(({multiaddr:u})=>u)}})),this.peerRouting.getClosestPeersOffline(t.key)]),s={type:De.GET_PROVIDERS,key:t.key,clusterLevel:t.clusterLevel,closer:i.map(this.peerInfoMapper).filter(({id:a,multiaddrs:c})=>c.length>0).map(a=>({id:a.id.toMultihash().bytes,multiaddrs:a.multiaddrs.map(c=>c.bytes)})),providers:o.map(this.peerInfoMapper).filter(({id:a,multiaddrs:c})=>c.length>0).map(a=>({id:a.id.toMultihash().bytes,multiaddrs:a.multiaddrs.map(c=>c.bytes)}))};return this.log("got %s providers %s closerPeers",s.providers.length,s.closer.length),s}async _getAddresses(e){return[]}};var Z3=class{peerStore;datastore;peerRouting;log;datastorePrefix;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:get-value`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.peerStore=e.peerStore,this.datastore=e.datastore,this.peerRouting=t.peerRouting}async handle(e,t){let n=t.key;if(this.log("%p asked for key %b",e,n),n==null||n.length===0)throw new he("Invalid key");let o={type:De.GET_VALUE,key:n,clusterLevel:t.clusterLevel,closer:[],providers:[]};if(yP(n)){this.log("is public key");let a=wP(n),c;try{let l=await this.peerStore.get(a);if(l.id.publicKey==null)throw new qe("No public key found in key book");c=Ht(l.id.publicKey)}catch(l){if(l.name!=="NotFoundError")throw l}if(c!=null)return this.log("returning found public key"),o.record=new ft(n,c,new Date).serialize(),o}let[i,s]=await Promise.all([this._checkLocalDatastore(n),this.peerRouting.getClosestPeersOffline(n)]);return i!=null&&(this.log("had record for %b in local datastore",n),o.record=i.serialize()),s.length>0&&(this.log("had %s closer peers in routing table",s.length),o.closer=s.map(a=>({id:a.id.toMultihash().bytes,multiaddrs:a.multiaddrs.map(c=>c.bytes)}))),o}async _checkLocalDatastore(e){this.log("checkLocalDatastore looking for %b",e);let t=Ks(this.datastorePrefix,e),n;try{n=await this.datastore.get(t)}catch(i){if(i.name==="NotFoundError")return;throw i}let o=ft.deserialize(n);if(o.timeReceived==null||Date.now()-o.timeReceived.getTime()>v3){await this.datastore.delete(t);return}return o}};var J3=class{log;constructor(e,t){this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:ping`)}async handle(e,t){return this.log("ping from %p",e),t}};var ey=class{components;validators;log;datastorePrefix;constructor(e,t){let{validators:n}=t;this.components=e,this.log=e.logger.forComponent(`${t.logPrefix}:rpc:handlers:put-value`),this.datastorePrefix=`${t.datastorePrefix}/record`,this.validators=n}async handle(e,t){let n=t.key;if(this.log("%p asked us to store value for key %b",e,n),t.record==null)throw this.log.error("empty record from %p",e),new he(`Empty record from: ${e}`);try{let o=ft.deserialize(t.record);await Su(this.validators,o),o.timeReceived=new Date;let i=Ks(this.datastorePrefix,o.key);return await this.components.datastore.put(i,o.serialize().subarray()),this.log("accepted put for key %b under %k",n,i),t}catch(o){throw this.log("failed to accept put for key %b - %e",n,o),o}}};var ty=class{handlers;log;metrics;incomingMessageTimeout;constructor(e,t){this.metrics={operations:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_inbound_rpc_requests_total`),errors:e.metrics?.registerCounterGroup(`${t.metricsPrefix}_inbound_rpc_errors_total`),rpcTime:e.metrics?.registerMetricGroup(`${t.metricsPrefix}_inbound_rpc_time_seconds`,{label:"operation"})},this.log=e.logger.forComponent(`${t.logPrefix}:rpc`),this.incomingMessageTimeout=t.incomingMessageTimeout??1e4,this.handlers={[De.GET_VALUE.toString()]:new Z3(e,t),[De.PUT_VALUE.toString()]:new ey(e,t),[De.FIND_NODE.toString()]:new X3(e,t),[De.ADD_PROVIDER.toString()]:new Y3(e,t),[De.GET_PROVIDERS.toString()]:new Q3(e,t),[De.PING.toString()]:new J3(e,t)}}async handleMessage(e,t){let n=this.handlers[t.type];if(n==null)throw new he(`No handler found for message type: ${t.type}`);try{return this.metrics.operations?.increment({[t.type]:!0}),await n.handle(e,t)}catch(o){throw this.metrics.errors?.increment({[t.type]:!0}),o}}async onIncomingStream(e,t){let n=()=>{e.abort(new Ro)},o=AbortSignal.timeout(this.incomingMessageTimeout);o.addEventListener("abort",n);let i=Xe(e).pb(qs);for(;;){if(e.readStatus!=="readable"){await e.close({signal:o});break}let s=await i.read({signal:o}),a=this.metrics?.rpcTime?.timer(s.type.toString()),c=this.metrics?.rpcTime?.timer(s.type.toString()),l=!1;try{this.log("incoming %s from %p",s.type,t.remotePeer);let u=await this.handleMessage(t.remotePeer,s);u!=null&&await i.write(u,{signal:o})}catch(u){l=!0,c?.(),this.log.error("error handling incoming message - %e",u),e.abort(u);return}finally{l||a?.()}o.removeEventListener("abort",n),o=AbortSignal.timeout(this.incomingMessageTimeout),o.addEventListener("abort",n)}}};var ry=class extends se{log;components;protocol;running;registrarId;constructor(e,t){super();let{protocol:n,logPrefix:o}=t;this.components=e,this.log=e.logger.forComponent(`${o}:topology-listener`),this.running=!1,this.protocol=n}isStarted(){return this.running}async start(){this.running||(this.running=!0,this.registrarId=await this.components.registrar.register(this.protocol,{onConnect:e=>{this.log("observed peer %p with protocol %s",e,this.protocol),this.dispatchEvent(new CustomEvent("peer",{detail:e}))}}))}async stop(){this.running=!1,this.registrarId!=null&&(this.components.registrar.unregister(this.registrarId),this.registrarId=void 0)}};var Pb=class{dht;constructor(e){this.dht=e}async provide(e,t={}){await pr(this.dht.provide(e,t))}async cancelReprovide(e){await this.dht.cancelReprovide(e)}async*findProviders(e,t={}){for await(let n of this.dht.findProviders(e,t))n.name==="PROVIDER"&&(yield*n.providers.map(o=>({...o,routing:"kad-dht"})))}async put(e,t,n){await pr(this.dht.put(e,t,n))}async get(e,t){for await(let n of this.dht.get(e,t))if(n.name==="VALUE")return n.value;throw new qe("Could not find value for key")}},Db=class{dht;constructor(e){this.dht=e}async findPeer(e,t={}){for await(let n of this.dht.findPeer(e,t))if(n.name==="FINAL_PEER")return n.peer;throw new qe("Peer not found")}async*getClosestPeers(e,t={}){for await(let n of this.dht.getClosestPeers(e,t))n.name==="FINAL_PEER"&&(yield n.peer)}},PY=32,DY=64,ny=class extends se{k;a;d;protocol;routingTable;providers;network;peerRouting;validators;selectors;components;log;running;clientMode;queryManager;contentFetching;contentRouting;routingTableRefresh;rpc;topologyListener;querySelf;maxInboundStreams;maxOutboundStreams;dhtContentRouting;dhtPeerRouting;peerInfoMapper;reprovider;onPeerConnectTimeout;constructor(e,t={}){super();let n=t.logPrefix??"libp2p:kad-dht",o=t.datastorePrefix??"/dht",i=t.metricsPrefix??"libp2p_kad_dht",s={queries:e.metrics?.registerMetricGroup(`${i}_operations_total`,{label:"operation"}),errors:e.metrics?.registerCounterGroup(`${i}_operation_errors_total`,{label:"operation"}),queryTime:e.metrics?.registerMetricGroup(`${i}_operation_time_seconds`,{label:"operation"}),errorTime:e.metrics?.registerMetricGroup(`${i}_operation_error_time_seconds`,{label:"operation"})};this.running=!1,this.components=e,this.log=e.logger.forComponent(n),this.k=t.kBucketSize??Bh,this.a=t.alpha??Us,this.d=t.disjointPaths??this.a,this.protocol=t.protocol??jR,this.clientMode=t.clientMode??!0,this.maxInboundStreams=t.maxInboundStreams??PY,this.maxOutboundStreams=t.maxOutboundStreams??DY,this.peerInfoMapper=t.peerInfoMapper??mP,this.onPeerConnectTimeout=t.onPeerConnectTimeout??JR,this.providers=new U3(e,{...t.providers,logPrefix:n,datastorePrefix:o}),this.validators={...pP,...t.validators},this.selectors={...hP,...t.selectors},this.network=new M3(e,{protocol:this.protocol,logPrefix:n,metricsPrefix:i,timeout:t.networkDialTimeout}),this.routingTable=new G3(e,{kBucketSize:this.k,pingOldContactTimeout:t.pingOldContactTimeout,pingOldContactConcurrency:t.pingOldContactConcurrency,pingOldContactMaxQueueSize:t.pingOldContactMaxQueueSize,pingNewContactTimeout:t.pingNewContactTimeout,pingNewContactConcurrency:t.pingNewContactConcurrency,pingNewContactMaxQueueSize:t.pingNewContactMaxQueueSize,protocol:this.protocol,logPrefix:n,metricsPrefix:i,prefixLength:t.prefixLength,splitThreshold:t.kBucketSplitThreshold,network:this.network,routingTableUpdateQueueConcurrency:t.routingTableUpdateQueueConcurrency??Math.max(1,Math.min(this.a*2,16)),routingTableUpdateMaxQueueSize:t.routingTableUpdateMaxQueueSize});let a=me();t.allowQueryWithZeroPeers===!0&&a.resolve(),this.queryManager=new $3(e,{disjointPaths:this.d,alpha:this.a,logPrefix:n,metricsPrefix:i,initialQuerySelfHasRun:a,routingTable:this.routingTable,allowQueryWithZeroPeers:t.allowQueryWithZeroPeers}),this.peerRouting=new F3(e,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,logPrefix:n}),this.contentFetching=new O3(e,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,logPrefix:n,datastorePrefix:o}),this.contentRouting=new B3(e,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,logPrefix:n}),this.routingTableRefresh=new j3(e,{peerRouting:this.peerRouting,routingTable:this.routingTable,logPrefix:n}),this.rpc=new ty(e,{routingTable:this.routingTable,providers:this.providers,peerRouting:this.peerRouting,validators:this.validators,logPrefix:n,metricsPrefix:i,datastorePrefix:o,peerInfoMapper:this.peerInfoMapper}),this.topologyListener=new ry(e,{protocol:this.protocol,logPrefix:n}),this.querySelf=new q3(e,{peerRouting:this.peerRouting,interval:t.querySelfInterval,initialInterval:t.initialQuerySelfInterval,logPrefix:n,initialQuerySelfHasRun:a,operationMetrics:s}),this.reprovider=new V3(e,{...t.reprovide,logPrefix:n,metricsPrefix:i,datastorePrefix:o,contentRouting:this.contentRouting,operationMetrics:s}),this.network.addEventListener("peer",c=>{let l=c.detail;this.onPeerConnect(l).catch(u=>{this.log.error("could not add %p to routing table - %e",l.id,u)}),this.dispatchEvent(new CustomEvent("peer",{detail:l}))}),this.topologyListener.addEventListener("peer",c=>{let l=c.detail;Promise.resolve().then(async()=>{let u=await this.components.peerStore.get(l),d={id:l,multiaddrs:u.addresses.map(({multiaddr:f})=>f),protocols:u.protocols};await this.onPeerConnect(d)}).catch(u=>{this.log.error("could not add %p to routing table - %e",l,u)})}),this.dhtPeerRouting=new Db(this),this.dhtContentRouting=new Pb(this),t.clientMode==null&&e.events.addEventListener("self:peer:update",c=>{this.log("received update of self-peer info"),Promise.resolve().then(async()=>{let l=c.detail.peer.addresses.some(({multiaddr:d})=>!wt(d)&&!Kt.exactMatch(d)),u=this.getMode();l&&u==="client"?await this.setMode("server"):u==="server"&&!l&&await this.setMode("client")}).catch(l=>{this.log.error("error setting dht server mode - %e",l)})}),this.get=Sc(this.get.bind(this),s,"GET_VALUE"),this.findProviders=Sc(this.findProviders.bind(this),s,"FIND_PROVIDERS"),this.findPeer=Sc(this.findPeer.bind(this),s,"FIND_PEER"),this.getClosestPeers=Sc(this.getClosestPeers.bind(this),s,"GET_CLOSEST_PEERS"),this.provide=Sc(this.provide.bind(this),s,"PROVIDE"),this.put=Sc(this.put.bind(this),s,"PUT_VALUE")}[Symbol.toStringTag]="@libp2p/kad-dht";[be]=["@libp2p/content-routing","@libp2p/peer-routing","@libp2p/peer-discovery","@libp2p/kad-dht"];[Zr]=["@libp2p/identify","@libp2p/ping"];get[si](){return this.dhtContentRouting}get[ci](){return this.dhtPeerRouting}get[aa](){return this}async onPeerConnect(e){if(this.log.trace("peer %p connected",e.id,e.multiaddrs),e=this.peerInfoMapper(e),e.multiaddrs.length===0){this.log.trace("ignoring %p as there were no valid addresses in %s after filtering",e.id,e.multiaddrs.map(t=>t.toString()));return}this.routingTable.queueRoutingTableUpdate(e.id,{activeTimeout:this.onPeerConnectTimeout})}isStarted(){return this.running}getMode(){return this.clientMode?"client":"server"}async setMode(e,t){if(e===this.getMode()&&t?.force!==!0){this.log("already in %s mode",e);return}if(await this.components.registrar.unhandle(this.protocol,t),e===this.getMode()&&t?.force!==!0){this.log("already in %s mode",e);return}e==="client"?(this.log("enabling client mode while in %s mode",this.getMode()),this.clientMode=!0):(this.log("enabling server mode while in %s mode",this.getMode()),this.clientMode=!1,await this.components.registrar.handle(this.protocol,this.rpc.onIncomingStream.bind(this.rpc),{signal:t?.signal,maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}))}async start(){this.running||(this.running=!0,await this.setMode(this.clientMode?"client":"server",{force:!0}),await Rt(this.routingTable,this.queryManager,this.network,this.topologyListener,this.routingTableRefresh,this.reprovider),await Rt(this.querySelf))}async stop(){this.running=!1,await Ut(this.querySelf,this.queryManager,this.network,this.routingTable,this.routingTableRefresh,this.topologyListener,this.reprovider)}async*put(e,t,n={}){yield*this.contentFetching.put(e,t,n)}async*get(e,t={}){yield*this.contentFetching.get(e,t)}async*provide(e,t={}){yield*this.contentRouting.provide(e,this.components.addressManager.getAddresses(),t)}async cancelReprovide(e,t){await this.providers.removeProvider(e,this.components.peerId,t)}async*findProviders(e,t={}){yield*this.contentRouting.findProviders(e,t)}async*findPeer(e,t={}){yield*this.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t={}){yield*this.peerRouting.getClosestPeers(e,t)}async refreshRoutingTable(e){this.routingTableRefresh.refreshTable(!0,e)}};var _P;(function(r){r[r.SEND_QUERY=0]="SEND_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADD_PEER=6]="ADD_PEER",r[r.DIAL_PEER=7]="DIAL_PEER",r[r.PATH_ENDED=8]="PATH_ENDED"})(_P||(_P={}));function CP(r={}){return e=>new ny(e,r)}function Ws(r=0){return new Uint8Array(r)}function kP(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var IP=kP("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Lb=kP("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=Ws(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),NY={utf8:IP,"utf-8":IP,hex:oe.base16,latin1:Lb,ascii:Lb,binary:Lb,...oe},oy=NY;function Nb(r,e="utf8"){let t=oy[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function iy(r,e="utf8"){let t=oy[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Le;(function(r){r[r.NEW_STREAM=0]="NEW_STREAM",r[r.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",r[r.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",r[r.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",r[r.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",r[r.RESET_RECEIVER=5]="RESET_RECEIVER",r[r.RESET_INITIATOR=6]="RESET_INITIATOR"})(Le||(Le={}));var Mh=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),Ob=Object.freeze({NEW_STREAM:Le.NEW_STREAM,MESSAGE:Le.MESSAGE_INITIATOR,CLOSE:Le.CLOSE_INITIATOR,RESET:Le.RESET_INITIATOR}),RP=Object.freeze({MESSAGE:Le.MESSAGE_RECEIVER,CLOSE:Le.CLOSE_RECEIVER,RESET:Le.RESET_RECEIVER});var Fh=1<<20,Bb=4<<20,sy=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Fh,t=Bb){this._buffer=new G,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(e==null||e.length===0)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new he("Unprocessed message queue size too large!");let t=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(l){if(l.name==="InvalidMessageError")throw l;break}let{id:n,type:o,length:i,offset:s}=this._headerInfo;if(this._buffer.length-s<i)break;let c={id:n,type:o};(o===Le.NEW_STREAM||o===Le.MESSAGE_INITIATOR||o===Le.MESSAGE_RECEIVER)&&(c.data=this._buffer.sublist(s,s+i)),t.push(c),this._buffer.consume(s+i),this._headerInfo=null}return t}_decodeHeader(e){let{value:t,offset:n}=DP(e),{value:o,offset:i}=DP(e,n),s=t&7;if(Mh[s]==null)throw new Error(`Invalid type received: ${s}`);if(o>this._maxMessageSize)throw new he("Message size too large");return{id:t>>3,type:s,offset:n+i,length:o}}},OY=128,PP=127;function DP(r,e=0){let t=0,n=0,o=e,i,s=r.length;do{if(o>=s||n>49)throw e=0,new RangeError("Could not decode varint");i=r.get(o++),t+=n<28?(i&PP)<<n:(i&PP)*Math.pow(2,n),n+=7}while(i>=OY);return e=o-e,{value:t,offset:e}}var Mb=10*1024,Fb=class{_pool;_poolOffset;constructor(){this._pool=Ws(Mb),this._poolOffset=0}write(e,t){let n=this._pool,o=this._poolOffset;ur(e.id<<3|e.type,n,o),o+=ye(e.id<<3|e.type),(e.type===Le.NEW_STREAM||e.type===Le.MESSAGE_INITIATOR||e.type===Le.MESSAGE_RECEIVER)&&e.data!=null?(ur(e.data.length,n,o),o+=ye(e.data.length)):(ur(0,n,o),o+=ye(0));let i=n.subarray(this._poolOffset,o);Mb-o<100?(this._pool=Ws(Mb),this._poolOffset=0):this._poolOffset=o,t.append(i),(e.type===Le.NEW_STREAM||e.type===Le.MESSAGE_INITIATOR||e.type===Le.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},BY=new Fb;function Uh(r){let e=new G;return BY.write(r,e),e}var Ub=class extends ys{streamId;types;maxDataSize;muxer;constructor(e){super(e),this.types=e.direction==="outbound"?Ob:RP,this.maxDataSize=e.maxDataSize,this.muxer=e.muxer,this.streamId=parseInt(this.id.substring(1)),e.direction==="outbound"&&queueMicrotask(()=>{this.muxer.send(Uh({id:this.streamId,type:Ob.NEW_STREAM,data:new G(Nb(this.id))}))})}sendData(e){let t=new G,n=e.byteLength;for(;e.byteLength>0;){let o=Math.min(e.byteLength,this.maxDataSize),i=e.sublist(0,o);e=e.sublist(o),t.append(Uh({id:this.streamId,type:this.types.MESSAGE,data:i}))}return{sentBytes:n,canSendMore:this.muxer.send(t)}}sendReset(){return this.muxer.send(Uh({id:this.streamId,type:this.types.RESET}))}async sendCloseWrite(e){this.muxer.send(Uh({id:this.streamId,type:this.types.CLOSE})),e?.signal?.throwIfAborted()}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}};function LP(r){let{id:e,muxer:t,direction:n,maxMsgSize:o=Fh}=r;return new Ub({...r,id:n==="outbound"?`i${e}`:`r${e}`,direction:n,maxDataSize:o,muxer:t,log:r.log.newScope(`${n}:${e}`),protocol:""})}var MY=5;function FY(r){let e={...r,type:`${Mh[r.type]} (${r.type})`};return r.type===Le.NEW_STREAM&&(e.data=iy(r.data.subarray())),(r.type===Le.MESSAGE_INITIATOR||r.type===Le.MESSAGE_RECEIVER)&&(e.data=iy(r.data.subarray(),"base16")),e}var ay=class extends gs{_streamId;rateLimiter;maxMessageSize;maxUnprocessedMessageQueueSize;decoder;constructor(e,t){super(e,{...t,protocol:"/mplex/6.7.0",name:"mplex"}),this._streamId=0,this.maxMessageSize=t.maxMessageSize??Fh,this.maxUnprocessedMessageQueueSize=t.maxUnprocessedMessageQueueSize??Bb,this.decoder=new sy(this.maxMessageSize,this.maxUnprocessedMessageQueueSize),this.rateLimiter=new Bl({points:t.disconnectThreshold??MY,duration:1})}onData(e){for(let t of this.decoder.write(e))this.handleMessage(t)}onCreateStream(e){if(this.status!=="open")throw new Xn("Muxer already closed");let t=this._streamId++;return this._newStream(t,"outbound",e)}_newStream(e,t,n){return this.log("new %s stream %s",t,e),LP({...n,id:e,direction:t,maxMsgSize:this.maxMessageSize,log:this.log,muxer:this})}handleMessage(e){if(this.log.enabled&&this.log.trace("incoming message",FY(e)),e.type===Le.NEW_STREAM){try{this.rateLimiter.consume("new-stream",1)}catch{this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}let o=this._newStream(e.id,"inbound",this.streamOptions);this.onRemoteStream(o);return}let t=`${(e.type&1)===1?"i":"r"}${e.id}`,n=this.streams.find(o=>o.id===t);if(n==null){this.log("missing stream %s for message type %s",t,Mh[e.type]);try{this.rateLimiter.consume("missing-stream",1)}catch{this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(new Error("Too many messages for missing streams"));return}return}try{switch(e.type){case Le.MESSAGE_INITIATOR:case Le.MESSAGE_RECEIVER:n.onData(e.data);break;case Le.CLOSE_INITIATOR:case Le.CLOSE_RECEIVER:n.onRemoteCloseWrite();break;case Le.RESET_INITIATOR:case Le.RESET_RECEIVER:n.onRemoteReset();break;default:this.log("unknown message type")}}catch(o){this.log.error("error while processing message - %e",o),n.abort(o)}}};var $b=class{protocol="/mplex/6.7.0";_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@libp2p/mplex";[be]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new ay(e,{...this._init})}};function NP(r={}){return()=>new $b(r)}function OP(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 BP="1.0.0",MP="ping",FP="ipfs";var cy=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(e,t={}){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??FP}/${MP}/${BP}`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[be]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handlePing,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async handlePing(e,t){let n=e.log.newScope("ping");n.trace("ping from %p",t.remotePeer);let o=AbortSignal.timeout(this.timeout);o.addEventListener("abort",()=>{e.abort(new Ro("Ping timed out"))});let i=Date.now();for await(let s of e){if(e.status!=="open"){n("stream status changed to %s",e.status);break}e.send(s)||(n("waiting for stream to drain"),await ke(e,"drain",{rejectionEvents:["close"],signal:o}),n("stream drained"))}n("ping from %p complete in %dms",t.remotePeer,Date.now()-i),await e.close({signal:o})}async ping(e,t={}){let n=kr(32),o=await this.components.connectionManager.openStream(e,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...t}),i=o.log.newScope("ping");try{let s=Date.now(),a=Promise.withResolvers(),c=new G,l=u=>{if(c.append(u.data),c.byteLength===32){o.removeEventListener("message",l);let d=Date.now()-s;Promise.all([o.closeRead(t)]).then(()=>{if(OP(n,c.subarray()))a.resolve(d);else throw new ia(`Received wrong ping ack after ${d}ms`)}).catch(f=>{o.abort(f),a.reject(f)})}};return o.addEventListener("message",l),o.send(n),await o.close(t),await Me(a.promise,t.signal)}catch(s){throw i.error("error while pinging %o - %e",e,s),o?.abort(s),s}finally{o?.close()}}};function $P(r={}){return e=>new cy(e,r)}var xr;(function(r){let e;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(e=r.Flag||(r.Flag={}));let t;(function(a){a[a.FIN=0]="FIN",a[a.STOP_SENDING=1]="STOP_SENDING",a[a.RESET=2]="RESET",a[a.FIN_ACK=3]="FIN_ACK"})(t||(t={})),(function(a){a.codec=()=>Ye(t)})(e=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=re((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),r.Flag.codec().encode(a.flag,c)),a.message!=null&&(c.uint32(18),c.bytes(a.message)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.flag=r.Flag.codec().decode(a);break}case 2:{u.message=a.bytes();break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.flag`,value:r.Flag.codec().decode(a)};break}case 2:{yield{field:`${l}.message`,value:a.bytes()};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return ee(a,r.codec())}r.encode=o;function i(a,c){return J(a,r.codec(),c)}r.decode=i;function s(a,c){return te(a,r.codec(),c)}r.stream=s})(xr||(xr={}));var HP=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Hb=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),qP="libp2p+webrtc+v1/",VP=2*1024*1024,Au=16*1024;function qY(r=Au){let e=ye(r-ye(r)),t=1+ye(Object.keys(xr.Flag).length-1),n=1,o=r-e-t-n,i=ye(o);return e+t+n+i}var KP=qY();var zP=1e4,qb="/webrtc",$h="/webrtc-signaling/0.0.1";function VY(r){return r.buffer instanceof ArrayBuffer}function GP(r){return VY(r)?r:r.slice()}var Vb=class extends ys{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??Au)-KP}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=Nt(),this.maxBufferedAmount=e.maxBufferedAmount??VP,this.finAckTimeout=e.finAckTimeout??zP,this.channel.onclose=()=>{this.log.trace("received datachannel close event"),this.onRemoteCloseWrite(),this.onTransportClosed()},this.channel.onerror=n=>{let o=n.error;this.log.trace("received datachannel error event - %e",o),this.abort(o)},this.channel.onmessage=async n=>{this.log("incoming message %d bytes",n.data.byteLength);let{data:o}=n;o===null||o.byteLength===0||this.incomingData.push(new Uint8Array(o,0,o.byteLength))},this.channel.bufferedAmountLowThreshold=0,this.channel.onbufferedamountlow=()=>{this.writableNeedsDrain&&this.safeDispatchEvent("drain")},Promise.resolve().then(async()=>{for await(let n of za(this.incomingData))this.processIncomingProtobuf(n)}).catch(n=>{this.log.error("error processing incoming data channel messages - %e",n)});let t=()=>{this.channel.readyState==="open"&&(this.log.trace("stream closed, closing underlying datachannel"),this.channel.close())};this.addEventListener("close",t),this.channel.readyState!=="open"&&(this.log('channel ready state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),ke(this.channel,"open",{rejectionEvents:["close","error"]}).then(()=>{this.log('channel ready state is now "%s", dispatching drain',this.channel.readyState),this.safeDispatchEvent("drain")}).catch(n=>{this.abort(n.error??n)}))}sendNewStream(){}_sendMessage(e){if(this.channel.readyState!=="open")throw new Io(`Invalid datachannel state - ${this.channel.readyState}`);this.log.trace('sending message, channel state "%s"',this.channel.readyState);try{for(let t of e)this.channel.send(GP(t))}catch(t){this.log.error("error sending datachannel message - %e",t),this.abort(t)}}sendData(e){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(Si.single(xr.encode({message:e.subarray()}))),{sentBytes:e.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(e){try{this.log.error("sending reset - %e",e),this._sendFlag(xr.Flag.RESET),this.receivedFinAck?.reject(e)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(e){this._sendFlag(xr.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let t=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[ke(this.channel,"close",{signal:t}),ke(this.channel,"error",{signal:t})];await Promise.any([Me(this.receivedFinAck.promise,t),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(xr.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let t=xr.decode(e);t.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new G(t.message)),t.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',t.flag,this.writeStatus,this.readStatus),t.flag===xr.Flag.FIN&&(this._sendFlag(xr.Flag.FIN_ACK),this.onRemoteCloseWrite()),t.flag===xr.Flag.RESET&&(this.receivedFinAck?.reject(new Hc("The stream was reset")),this.onRemoteReset()),t.flag===xr.Flag.STOP_SENDING&&this.onRemoteCloseRead(),t.flag===xr.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(e){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',e.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",e.toString());let t=xr.encode({flag:e}),n=Si.single(t);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",e.toString(),o)}return!1}sendPause(){}sendResume(){}};function Hh(r){let{channel:e,direction:t,isHandshake:n}=r;return new Vb({...r,id:`${e.id}`,log:r.log.newScope(`${n===!0?"handshake":t}:${e.id}`),protocol:""})}var js=class{protocol;peerConnection;metrics;dataChannelOptions;earlyDataChannels;constructor(e){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??qb,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(e){this.earlyDataChannels.push(e.channel)}createStreamMuxer(e){return this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new Kb(e,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},Kb=class extends gs{peerConnection;dataChannelOptions;constructor(e,t){super(e,{...t,name:"muxer"}),this.peerConnection=t.peerConnection,this.protocol=t.protocol??qb,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){t.earlyDataChannels.forEach(n=>{n.close()});return}t.earlyDataChannels.forEach(n=>{this.onDataChannel(n)})})}onDataChannel(e){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",e.id,e.protocol,e.readyState),e.label==="init"){this.log.trace("closing init channel %d",e.id),e.close();return}let t=Hh({...this.streamOptions,...this.dataChannelOptions,channel:e,direction:"inbound",log:this.log});this.onRemoteStream(t)}async onCreateStream(e){let t=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",t.id,e?.protocol),Hh({...e,...this.dataChannelOptions,channel:t,direction:"outbound",log:this.log})}onData(){}};var zb=class extends ps{peerConnection;constructor(e){super(e),this.peerConnection=e.peerConnection;let t=e.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change %s initial state %s",this.peerConnection.connectionState,t),(this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.onTransportClosed(),this.peerConnection.close())}}sendData(e){return{sentBytes:e.byteLength,canSendMore:!0}}async sendClose(e){this.peerConnection.close(),e?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},qh=r=>new zb(r);async function Gb(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??HP.map(e=>({urls:[e]})),r}var WP=(r=32)=>qP+[...Array(r)].map(()=>Hb.at(Math.floor(Math.random()*Hb.length))).join("");var ly=globalThis.RTCPeerConnection,uy=globalThis.RTCSessionDescription,jP=globalThis.RTCIceCandidate;var Ys=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},zn=class extends Ys{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var dy=class extends Ys{constructor(e,t){super(`Invalid fingerprint "${e}" within ${t}`),this.name="WebRTC/InvalidFingerprintError"}};var fy=class extends Ys{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},hy=class extends Ys{constructor(e){super(`unsupported hash algorithm code: ${e} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Wr;(function(r){let e;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.SDP_OFFER=0]="SDP_OFFER",a[a.SDP_ANSWER=1]="SDP_ANSWER",a[a.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(t||(t={})),(function(a){a.codec=()=>Ye(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=re((a,c,l={})=>{l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.data!=null&&(c.uint32(18),c.string(a.data)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.data=a.string();break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield{field:`${l}.data`,value:a.string()};break}default:{a.skipType(f&7);break}}}})),n);function o(a){return ee(a,r.codec())}r.encode=o;function i(a,c){return J(a,r.codec(),c)}r.decode=i;function s(a,c){return te(a,r.codec(),c)}r.stream=s})(Wr||(Wr={}));var py=async(r,e,t)=>{try{let n=Promise.withResolvers();for(KY(r,n);;){let o=await Promise.race([n.promise,e.read({signal:t.signal})]);if(o==null){t.signal?.throwIfAborted();break}if(o.type!==Wr.Type.ICE_CANDIDATE)throw new he("ICE candidate message expected");let i=JSON.parse(o.data??"null");if(i===""||i===null){t.onProgress?.(new k("webrtc:end-of-ice-candidates")),t.log.trace("end-of-candidates received");continue}let s=new jP(i);t.log.trace("%s received new ICE candidate %o",t.direction,i);try{t.onProgress?.(new k("webrtc:add-ice-candidate",s.candidate)),await r.addIceCandidate(s)}catch(a){t.log.error("%s bad candidate received %o - %e",t.direction,i,a)}}}catch(n){if(t.log.error("%s error parsing ICE candidate - %e",t.direction,n),t.signal?.aborted===!0&&r.connectionState!=="connected")throw n}};function KY(r,e){if(r.connectionState==="connected"){e.resolve();return}r.onconnectionstatechange=t=>{switch(r.connectionState){case"connected":e.resolve();break;case"failed":case"closed":e.reject(new $c(`RTCPeerConnection connection state became "${r.connectionState}"`));break;default:break}}}function my(r){let e;for(let t of r.getComponents())t.name==="p2p"&&(e=Ee(t.value??""));if(e==null)throw new ko("Remote peerId must be present in multiaddr");return e}async function YP({rtcConfiguration:r,dataChannel:e,signal:t,metrics:n,multiaddr:o,connectionManager:i,transportManager:s,log:a,logger:c,onProgress:l}){let{circuitAddress:u,targetPeer:d}=XP(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",u);let f=i.getConnections(d),h;f.length===0?(l?.(new k("webrtc:dial-relay")),h=await s.dial(u,{signal:t,onProgress:l})):(l?.(new k("webrtc:reuse-relay-connection")),h=f[0]),l?.(new k("webrtc:open-signaling-stream"));let p=await h.newStream($h,{signal:t,runOnLimitedConnection:!0}),y=Xe(p).pb(Wr),g=new ly(r);g.addEventListener("connectionstatechange",()=>{g.connectionState==="closed"&&g.close()});let m=new js({peerConnection:g,dataChannelOptions:e});try{let b=g.createDataChannel("init");g.onicecandidate=({candidate:O})=>{if(g.connectionState==="connected"){a.trace("ignore new ice candidate as peer connection is already connected");return}if(O==null||O?.candidate===""){a.trace("initiator detected end of ICE candidates");return}let U=JSON.stringify(O?.toJSON()??null);a.trace("initiator sending ICE candidate %o",O),y.write({type:Wr.Type.ICE_CANDIDATE,data:U},{signal:t}).catch(C=>{a.error("error sending ICE candidate - %e",C)})},g.onicecandidateerror=O=>{a.error("initiator ICE candidate error",O)};let T=await g.createOffer().catch(O=>{throw a.error("could not execute createOffer - %e",O),new zn("Failed to set createOffer")});a.trace("initiator send SDP offer %s",T.sdp),l?.(new k("webrtc:send-sdp-offer")),await y.write({type:Wr.Type.SDP_OFFER,data:T.sdp},{signal:t}),await g.setLocalDescription(T).catch(O=>{throw a.error("could not execute setLocalDescription - %e",O),new zn("Failed to set localDescription")}),l?.(new k("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let R=await y.read({signal:t});if(R.type!==Wr.Type.SDP_ANSWER)throw new zn("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",R.data);let D=new uy({type:"answer",sdp:R.data});return await g.setRemoteDescription(D).catch(O=>{throw a.error("could not execute setRemoteDescription - %e",O),new zn("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new k("webrtc:read-ice-candidates")),await py(g,y,{direction:"initiator",signal:t,log:a,onProgress:l}),a.trace("initiator connected"),b.readyState!=="open"&&(a.trace("wait for init channel to open"),await ke(b,"open",{signal:t})),a.trace("closing init channel"),b.close(),a.trace("waiting for init channel to close"),await ke(b,"close",{signal:t}),l?.(new k("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await p.close({signal:t}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:g,muxerFactory:m}}catch(b){throw a.error("outgoing signaling error - %e",b),g.close(),p.abort(b),b}finally{g.onicecandidate=null,g.onicecandidateerror=null}}var QP=Be(Tl.matchers[0],Oe(290)),gy=class r extends se{transportManager;shutdownController;events;constructor(e,t){super(),this.transportManager=e.transportManager,this.events=e.events,this.shutdownController=t.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(e){e.detail.getAddrs().filter(n=>QP.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(e=>!(e instanceof r)).map(e=>e.getAddrs().filter(t=>QP.exactMatch(t)).map(t=>t.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function ZP(r,e,{peerConnection:t,signal:n,log:o}){o.trace("new inbound signaling stream");let i=Xe(r).pb(Wr);try{t.onicecandidate=({candidate:d})=>{if(t.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(d==null||d?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let f=JSON.stringify(d?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),i.write({type:Wr.Type.ICE_CANDIDATE,data:f},{signal:n}).catch(h=>{o.error("error sending ICE candidate - %e",h)})},o.trace("recipient read SDP offer");let c=await i.read({signal:n});if(c.type!==Wr.Type.SDP_OFFER)throw new zn(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let l=new uy({type:"offer",sdp:c.data});await t.setRemoteDescription(l).catch(d=>{throw o.error("could not execute setRemoteDescription - %e",d),new zn("Failed to set remoteDescription")});let u=await t.createAnswer().catch(d=>{throw o.error("could not execute createAnswer - %e",d),new zn("Failed to create answer")});o.trace("recipient send SDP answer %s",u.sdp),await i.write({type:Wr.Type.SDP_ANSWER,data:u.sdp},{signal:n}),await t.setLocalDescription(u).catch(d=>{throw o.error("could not execute setLocalDescription - %e",d),new zn("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await py(t,i,{direction:"recipient",signal:n,log:o})}catch(c){if(t.connectionState!=="connected")throw o.error("error while handling signaling stream from peer %a - %e",e.remoteAddr,c),t.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",e.remoteAddr,c)}let s=my(e.remoteAddr),a=j(`/webrtc/p2p/${s}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:s}}var yy=class{components;init;log;_started=!1;metrics;shutdownController;constructor(e,t={}){this.components=e,this.init=t,this.log=e.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[Xi]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[be]=["@libp2p/transport"];[Zr]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle($h,(e,t)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(e,t,n).catch(o=>{this.log.error("failed to handle incoming connect from %p - %e",t.remotePeer,o)}).finally(()=>{n.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle($h),this._started=!1}createListener(e){return new gy(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Ua.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,t){this.log.trace("dialing address: %a",e);let{remoteAddress:n,peerConnection:o,muxerFactory:i}=await YP({rtcConfiguration:await Gb(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:t.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:t.onProgress}),s=qh({peerConnection:o,remoteAddr:n,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")}),a=await t.upgrader.upgradeOutbound(s,{skipProtection:!0,skipEncryption:!0,remotePeer:my(e),muxerFactory:i,onProgress:t.onProgress,signal:t.signal});return this._closeOnShutdown(o,s),a}async _onProtocol(e,t,n){let o=new ly(await Gb(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let i=new js({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:s,remotePeer:a}=await ZP(e,t,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=qh({peerConnection:o,remoteAddr:s,metrics:this.metrics?.listenerEvents,direction:"inbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")});await this.components.upgrader.upgradeInbound(c,{skipEncryption:!0,skipProtection:!0,remotePeer:a,muxerFactory:i,signal:n}),this._closeOnShutdown(o,c)}catch(s){throw this.log.error("incoming signaling error - %e",s),o.close(),e.abort(s),s}}_closeOnShutdown(e,t){let n=()=>{t.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function XP(r){let e=r.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new E("Destination peer id was missing");return{circuitAddress:j(r.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:Ee(e)}}function wy(r=0){return new Uint8Array(r)}function zY(r){return r?.buffer instanceof ArrayBuffer}function JP(r){if(zY(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Wb(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=wy(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return JP(t)}function tD(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var eD=tD("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),jb=tD("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=wy(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),GY={utf8:eD,"utf-8":eD,hex:oe.base16,latin1:jb,ascii:jb,binary:jb,...oe},rD=GY;function Yb(r,e="utf8"){let t=rD[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Xb=Object.values(oe).map(r=>r.decoder).reduce((r,e)=>r.or(e)),WY=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function nD(r){return r?.match(WY)?.groups?.fingerprint}function Qb(r){let t=r.getComponents().find(n=>n.code===466)?.value;if(t===void 0||t==="")throw new E(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return t}function jY(r){return Ve.decode(Xb.decode(r))}function YY(r){let e=jY(Qb(r)),t=XY(e.code),n=e.digest.reduce((i,s)=>i+s.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new dy(n,r.toString());return`${t} ${o.join(":").toUpperCase()}`}function oD(r){let e=r.split(":").map(o=>parseInt(o,16)),t=Uint8Array.from(e),n=Cr(ct.code,t);return j(`/certhash/${ud.encode(n.bytes)}`)}function XY(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new hy(r)}}function iD(r,e){let{host:t,port:n,type:o}=ie(r);if(o!=="ip4"&&o!=="ip6")throw new E(`Multiaddr ${r} was not an IPv4 or IPv6 address`);let i=YY(r);return{type:"answer",sdp:`v=0
66
66
  o=- 0 0 IN IP${o==="ip4"?4:6} ${t}
67
67
  s=-
68
68
  t=0 0
@@ -100,17 +100,17 @@ a=end-of-candidates
100
100
  `:`
101
101
  `;try{r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
102
102
  a=ice-ufrag:`+e+t).replace(/\na=ice-pwd:[^\n]*\n/,`
103
- a=ice-pwd:`+e+t)}catch{}return r}var Jb=Yb("libp2p-webrtc-noise:");function cD(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=Yb(n,"hex"),i=Cr(ct.code,o),s=Xb.decode(Qb(e)),a=Jb.byteLength+i.bytes.byteLength+s.byteLength;return t==="server"?Wb([Jb,s,i.bytes],a):Wb([Jb,i.bytes,s],a)}function QY(r,e){return r.role==="server"}async function lD(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let d=await r.createOffer();n.log.trace("client created local offer %s",d.sdp);let f=Zb(d,t);n.log.trace("client setting local offer %s",f.sdp),await r.setLocalDescription(f);let h=iD(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let d=sD(n.remoteAddr,t);n.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),n.log.trace("server creating local answer");let f=await r.createAnswer();n.log.trace("server created local answer");let h=Zb(f,t);n.log.trace("server setting local description %s",f.sdp),await r.setLocalDescription(h)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await ke(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),QY(n,r)){let d=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(oD(d))}let i=nD(r.localDescription?.sdp);if(i==null)throw new Ys("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let s=cD(i,n.remoteAddr,n.role),a=Pg({prologueBytes:s})(n),c=Hh({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=qh({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener("connectionstatechange",()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{n.log.error("error closing connection - %e",d),l.abort(d)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let d=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:d.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(i){throw o.close(),r.close(),i}}async function uD(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,i=new RTCPeerConnection({...o??{},certificates:[n]}),s=new js({peerConnection:i,metrics:t.events,dataChannelOptions:t.dataChannel});return{peerConnection:i,muxerFactory:s}}var by=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Xi]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[be]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=Ee(o));let i=WP(),{peerConnection:s,muxerFactory:a}=await uD("client",i,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await lD(s,a,i,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw s.close(),c}}createListener(e){throw new fy("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(Fa.exactMatch)}};function xy(r){return e=>new by(e,r)}function dD(r){return e=>new yy(e,r)}function fD(){throw new Error("WebSocket Servers can not be created in the browser!")}function hD(r=0){return new Uint8Array(r)}function mD(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var pD=mD("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),e9=mD("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=hD(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ZY={utf8:pD,"utf-8":pD,hex:oe.base16,latin1:e9,ascii:e9,binary:e9,...oe},gD=ZY;function yD(r,e="utf8"){let t=gD[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function JY(r){return r.buffer instanceof ArrayBuffer}function wD(r){return JY(r)?r:r.slice()}var eX=1024*1024*4,tX=10,t9=class extends ps{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??eX,this.checkBufferedAmountTask=Ml(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??tX),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=yD(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(wD(n));let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function bD(r){return new t9(r)}var r9=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Xi]=!0;[Symbol.toStringTag]="@libp2p/websockets";[be]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=bD({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=Ts(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new k("websockets:open-connection")),await ke(o,"open",t)}catch(i){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new $c(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw i}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return fD({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>fo.exactMatch(t)||xi.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function Ey(r={}){return e=>new r9(e,r)}var n9=Yt(v0(),1);function vy(r,e){let t=e.map((n,o)=>({record:mn(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===qr.ValidityType.EOL&&o.record.validityType===qr.ValidityType.EOL){let a=n9.default.fromString(n.record.validity).toDate(),c=n9.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var xD="6.1.4",ED="helia";var vD={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function Vh(r={}){let e=`${ED}/${xD} ${_2()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[jk(),dD(),xy(),Ey()],connectionEncrypters:[Pg()],streamMuxers:[Ck(),NP()],peerDiscovery:[Dk(vD)],services:{autoNAT:Pk(),dcutr:Qk(),delegatedRouting:O0(Lw()),dht:CP({clientMode:!0,validators:{ipns:sc},selectors:{ipns:vy}}),identify:GR(),identifyPush:WR(),keychain:Eg(r.keychain),ping:$P(),http:BR()}}}async function SD(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await b7(r.datastore,r.keychain));let t=Vh(e);return t.datastore=t.datastore??r.datastore,await C2({...t,...e,start:!1})}async function AD(r={}){let e=r.datastore??new cc,t=r.blockstore??new Lf,n;return UC(r.libp2p)?n=r.libp2p:n=await SD({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[If(),Cf()],routers:r.routers??[Df(n),Pf()],metrics:n.metrics}}async function TD(r={}){let e=await AD(r),t=new h0(e);return e.start!==!1&&await t.start(),t}function _D(){let r=Vh();r.start=!1,r.addresses={listen:[]},r.transports=[xy(),Ey()],r.peerDiscovery=[];let e={dcutr:r.services.dcutr,identify:r.services.identify,keychain:r.services.keychain,ping:r.services.ping};return{...r,start:!1,services:e}}var Xs=class extends Map{#e=0;#t=new Map;#r=new Map;#i;#a;#d;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.#i=e.maxSize,this.#a=e.maxAge||Number.POSITIVE_INFINITY,this.#d=e.onEviction}get __oldCache(){return this.#r}#f(e){if(typeof this.#d=="function")for(let[t,n]of e)this.#d(t,n.value)}#c(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.#d=="function"&&this.#d(e,t.value),this.delete(e)):!1}#y(e,t){if(this.#c(e,t)===!1)return t.value}#h(e,t){return t.expiry?this.#y(e,t):t.value}#p(e,t){let n=t.get(e);return this.#h(e,n)}#u(e,t){this.#t.set(e,t),this.#e++,this.#e>=this.#i&&(this.#e=0,this.#f(this.#r),this.#r=this.#t,this.#t=new Map)}#l(e,t){this.#r.delete(e),this.#u(e,t)}*#o(){for(let e of this.#r){let[t,n]=e;this.#t.has(t)||this.#c(t,n)===!1&&(yield e)}for(let e of this.#t){let[t,n]=e;this.#c(t,n)===!1&&(yield e)}}get(e){if(this.#t.has(e)){let t=this.#t.get(e);return this.#h(e,t)}if(this.#r.has(e)){let t=this.#r.get(e);if(this.#c(e,t)===!1)return this.#l(e,t),t.value}}set(e,t,{maxAge:n=this.#a}={}){let o=typeof n=="number"&&n!==Number.POSITIVE_INFINITY?Date.now()+n:void 0;return this.#t.has(e)?this.#t.set(e,{value:t,expiry:o}):this.#u(e,{value:t,expiry:o}),this}has(e){return this.#t.has(e)?!this.#c(e,this.#t.get(e)):this.#r.has(e)?!this.#c(e,this.#r.get(e)):!1}peek(e){if(this.#t.has(e))return this.#p(e,this.#t);if(this.#r.has(e))return this.#p(e,this.#r)}expiresIn(e){let t=this.#t.get(e)??this.#r.get(e);if(t)return t.expiry?t.expiry-Date.now():Number.POSITIVE_INFINITY}delete(e){let t=this.#t.delete(e);return t&&this.#e--,this.#r.delete(e)||t}clear(){this.#t.clear(),this.#r.clear(),this.#e=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this.#o()],n=t.length-e;n<0?(this.#t=new Map(t),this.#r=new Map,this.#e=t.length):(n>0&&this.#f(t.slice(0,n)),this.#r=new Map(t.slice(n)),this.#t=new Map,this.#e=0),this.#i=e}evict(e=1){let t=Number(e);if(!t||t<=0)return;let n=[...this.#o()],o=Math.trunc(Math.min(t,Math.max(n.length-1,0)));o<=0||(this.#f(n.slice(0,o)),this.#r=new Map(n.slice(o)),this.#t=new Map,this.#e=0)}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.#t){let[t,n]=e;this.#c(t,n)===!1&&(yield[t,n.value])}for(let e of this.#r){let[t,n]=e;this.#t.has(t)||this.#c(t,n)===!1&&(yield[t,n.value])}}*entriesDescending(){let e=[...this.#t];for(let t=e.length-1;t>=0;--t){let n=e[t],[o,i]=n;this.#c(o,i)===!1&&(yield[o,i.value])}e=[...this.#r];for(let t=e.length-1;t>=0;--t){let n=e[t],[o,i]=n;this.#t.has(o)||this.#c(o,i)===!1&&(yield[o,i.value])}}*entriesAscending(){for(let[e,t]of this.#o())yield[e,t.value]}get size(){if(!this.#e)return this.#r.size;let e=0;for(let t of this.#r.keys())this.#t.has(t)||e++;return Math.min(this.#e+e,this.#i)}get maxSize(){return this.#i}get maxAge(){return this.#a}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,o]of this.entriesAscending())e.call(t,o,n,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};var Sy=class extends Error{static name="DNSLinkNotFoundError";constructor(e="DNSLink not found"){super(e),this.name="DNSLinkNotFoundError"}},Tu=class extends Error{static name="InvalidNamespaceError";constructor(e="Invalid namespace"){super(e),this.name="InvalidNamespaceError"}};var CD=(r,e)=>{let[,t,n,...o]=r.split("/");if(t!=="ipfs")throw new Tu(`Namespace ${t} was not "ipfs"`);return{namespace:"ipfs",cid:F.parse(n),path:o.length>0?`/${o.join("/")}`:"",answer:e}};var ID=(r,e)=>{let[,t,n,...o]=r.split("/");if(t!=="ipns")throw new Tu(`Namespace ${t} was not "ipns"`);try{return{namespace:"ipns",peerId:Ee(n),path:o.length>0?`/${o.join("/")}`:"",answer:e}}catch{return{namespace:"dnslink",value:n,path:o.length>0?`/${o.join("/")}`:"",answer:e}}};var Ay=class{dns;log;namespaces;cache;cacheMaxAnswers;constructor(e,t={}){this.dns=e.dns,this.log=e.logger.forComponent("helia:dnslink"),this.namespaces={ipfs:CD,ipns:ID,...t.namespaces},this.cache=new Xs({maxSize:t.cacheSize??1e3,maxAge:t.cacheMaxAge??3e4}),this.cacheMaxAnswers=t.cacheMaxAnswers??10}async resolve(e,t={}){if(t.nocache!==!0){let s=this.cache.get(e);if(s!=null){let a=[...s.values()];if(a.length>0)return a}}let n=await this.recursiveResolveDomain(e,t.maxRecursiveDepth??qT,t),o=new Xs({maxSize:this.cacheMaxAnswers});n.forEach((s,a)=>{o.set(a,s,{maxAge:s.answer.TTL*1e3})});let i=n.reduce((s,a)=>{let c=a.answer.TTL*1e3;return c>s?c:s},0);return this.cache.maxAge<i&&(i=this.cache.maxAge),this.cache.set(e,o,{maxAge:i}),n}async recursiveResolveDomain(e,t,n={}){if(t===0)throw new Error("recursion limit exceeded");e.startsWith("_dnslink.")||(e=`_dnslink.${e}`);try{return await this.recursiveResolveDnslink(e,t,n)}catch(o){if(o.code!=="ENOTFOUND"&&o.code!=="ENODATA"&&o.name!=="DNSLinkNotFoundError"&&o.name!=="NotFoundError")throw o;return e.startsWith("_dnslink.")?e=e.replace("_dnslink.",""):e=`_dnslink.${e}`,this.recursiveResolveDnslink(e,t,n)}}async recursiveResolveDnslink(e,t,n={}){if(t===0)throw new Error("recursion limit exceeded");this.log("query %s for TXT and CNAME records",e);let i=((await this.dns.query(e,{...n,types:[yr.TXT]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));this.log("found %d TXT records for %s",i.length,e);let s=[];for(let l of i)try{let u=l.data;if(u.startsWith('"')&&u.endsWith('"')&&(u=u.substring(1,u.length-1)),!u.startsWith("dnslink="))continue;this.log("%s TXT %s",l.name,u),u=u.replace("dnslink=","");let[,d,f]=u.split("/");if(d==="dnslink"){s.push(...await this.recursiveResolveDomain(f,t-1,n));continue}let h=this.namespaces[d];if(h==null){this.log('unknown protocol "%s" in DNSLink record for domain: %s',d,e);continue}let p=h(u,l);if(p.namespace==="dnslink"){s.push(...await this.recursiveResolveDomain(p.value,t-1,n));continue}s.push(h(u,l))}catch(u){this.log.error("could not parse DNS link record for domain %s, %s - %e",e,l.data,u)}if(s.length>0)return s;this.log("no DNSLink records found for %s, falling back to CNAME",e);let c=((await this.dns.query(e,{...n,types:[yr.CNAME]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));this.log("found %d CNAME records for %s",c.length,e);for(let l of c)try{return await this.recursiveResolveDomain(l.data,t-1,n)}catch(u){this.log.error("domain %s cname %s had no DNSLink records - %e",e,l.data,u)}throw new Sy(`No DNSLink records found for domain: ${e}`)}};function kD(r,e={}){return new Ay(r,e)}var RD=BigInt(6e4)*5000000n;var Ty=class extends Error{static name="RecordsFailedValidationError";constructor(e="Records failed validation"){super(e),this.name="RecordsFailedValidationError"}},_y=class extends Error{static name="UnsupportedMultibasePrefixError";constructor(e="Unsupported multibase prefix"){super(e),this.name="UnsupportedMultibasePrefixError"}},Cy=class extends Error{static name="UnsupportedMultihashCodecError";constructor(e="Unsupported multihash codec"){super(e),this.name="UnsupportedMultihashCodecError"}},Iy=class extends Error{static name="InvalidValueError";constructor(e="Invalid value"){super(e),this.name="InvalidValueError"}};var Kh=class extends Error{static name="RecordNotFoundError";name="RecordNotFoundError"};var rX=114,o9=0,i9=18;function s9(r,e){return r.code===e}var ky="/dht/record/",nX="/ipns/metadata/";function zh(r){return new He(ky+de(r,"base32"),!1)}function Ry(r){return new He(nX+de(r,"base32"),!1)}function oX(r){return r?.asCID===r}function PD(r){if(!oX(r))return!1;if(r.code!==rX)throw new E(`CID codec ${r.code} was not libp2p-key`);if(r.multihash.code!==o9&&r.multihash.code!==i9)throw new E(`Multihash algorithm codec ${r.multihash.code} was not Identity or SHA256 hash`);return!0}var DD={[_r.prefix]:_r,[Ce.prefix]:Ce},Py=class{routers;localStore;log;constructor(e,t){this.log=e.logger.forComponent("helia:ipns"),this.localStore=t.localStore,this.routers=t.routers}async resolve(e,t={}){let n=Pp(e)||pt(e)?e.toMultihash():PD(e)?e.multihash:e,o=ic(n),i=await this.#t(o,t);return{...await this.#e(i.value,t),record:i}}async#e(e,t={}){let n=e.split("/");try{let o=n[1];if(o==="ipns"){let i=n[2],s=i.substring(0,1),a;if(s==="1"||s==="Q")a=Ce.decode(`z${i}`);else if(DD[s]!=null)a=DD[s].decode(i);else throw new _y(`Unsupported multibase prefix "${s}"`);let c;try{c=xe(a)}catch{c=F.decode(a).multihash}if(!s9(c,o9)&&!s9(c,i9))throw new Cy(`Unsupported multihash codec "${c.code}"`);let{cid:l}=await this.resolve(c,t),u=n.slice(3).join("/");return{cid:l,path:u===""?void 0:u}}else if(o==="ipfs"){let i=F.parse(n[2]),s=n.slice(3).join("/");return{cid:i,path:s===""?void 0:s}}}catch(o){this.log.error("error parsing ipfs path - %e",o)}throw this.log.error("invalid ipfs path %s",e),new Iy("Invalid value")}async#t(e,t={}){let n=[];if(await this.localStore.has(e,t))if(this.log("record is present in the cache"),t.nocache!==!0)try{let{record:c,created:l}=await this.localStore.get(e,t);this.log("record retrieved from cache"),await sc(e,c),this.log("record was valid");let u=mn(c),d=Number((u.ttl??RD)/1000000n);if(l.getTime()+d>Date.now())return this.log("record TTL was valid"),u;if(t.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),u;this.log("record TTL has been reached, searching routing for updates"),n.push(c)}catch(c){this.log("cached record was invalid - %e",c),await this.localStore.delete(e,t)}else this.log("ignoring local cache due to nocache=true option");if(t.offline===!0)throw new Kh("Record was not present in the cache or has expired");this.log("did not have record locally");let i=0,s=[];if(await Promise.all(this.routers.map(async c=>{let l;try{l=await c.get(e,{...t,validate:!1})}catch(u){this.log.error("error finding IPNS record using router %s - %e",c.toString(),u),s.push(u);return}try{await sc(e,l),n.push(l)}catch(u){i++,this.log.error("error validating IPNS record from router %s - %e",c.toString(),u)}})),n.length===0)throw i>0?new Ty(`${i>1?`${i} records`:"Record"} found for routing key ${i>1?"were":"was"} invalid`):new Kh("Could not find record for routing key");let a=n[vy(e,n)];return await this.localStore.put(e,a,t),mn(a)}};var Gh;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.keyName!=null&&i.keyName!==""&&(s.uint32(10),s.string(i.keyName)),i.lifetime!=null&&i.lifetime!==0&&(s.uint32(16),s.uint32(i.lifetime)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={keyName:"",lifetime:0},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.keyName=i.string();break}case 2:{c.lifetime=i.uint32();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.keyName`,value:i.string()};break}case 2:{yield{field:`${a}.lifetime`,value:i.uint32()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Gh||(Gh={}));function LD(r,e){return{async put(t,n,o={}){try{let i=zh(t);try{let c=await r.get(i),l=ft.deserialize(c);if(gt(l.value,n))return}catch(c){if(c.name!=="NotFoundError")throw c}let s=new ft(t,n,new Date);o.onProgress?.(new k("ipns:routing:datastore:put"));let a=r.batch();a.put(i,s.serialize()),o.metadata!=null&&a.put(Ry(t),Gh.encode(o.metadata)),await a.commit(o)}catch(i){throw o.onProgress?.(new k("ipns:routing:datastore:error",i)),i}},async get(t,n={}){try{let o=zh(t);n.onProgress?.(new k("ipns:routing:datastore:get"));let i=await r.get(o,n),s=ft.deserialize(i);return{record:s.value,created:s.timeReceived}}catch(o){throw n.onProgress?.(new k("ipns:routing:datastore:error",o)),o}},async has(t,n={}){let o=zh(t);return r.has(o,n)},async delete(t,n){let o=zh(t),i=r.batch();i.delete(o),i.delete(Ry(t)),await i.commit(n)},async*list(t={}){try{t.onProgress?.(new k("ipns:routing:datastore:list"));for await(let{key:n,value:o}of r.query({prefix:ky},t))try{let i=ft.deserialize(o),a=n.toString().substring(ky.length),c=K(a,"base32"),l=Ry(c),u;try{let d=await r.get(l,t);u=Gh.decode(d)}catch(d){e.error("Error deserializing metadata for %s - %e",a,d)}yield{routingKey:c,metadata:u,record:i.value,created:i.timeReceived}}catch(i){e.error("Error deserializing record - %e",i)}}catch(n){throw t.onProgress?.(new k("ipns:routing:datastore:error",n)),n}}}}var a9=class{routing;constructor(e){this.routing=e}async put(e,t,n={}){try{await this.routing.put(e,t,n)}catch(o){throw n.onProgress?.(new k("ipns:routing:helia:error",o)),o}}async get(e,t={}){try{return await this.routing.get(e,t)}catch(n){throw t.onProgress?.(new k("ipns:routing:helia:error",n)),n}}toString(){return"HeliaRouting()"}};function c9(r){return new a9(r)}var l9=class{localStore;constructor(e){this.localStore=e}async put(e,t,n){await this.localStore.put(e,t,n)}async get(e,t){let{record:n}=await this.localStore.get(e,t);return n}toString(){return"LocalStoreRouting()"}};function ND(r){return new l9(r)}function OD(r,e={}){let t=LD(r.datastore,r.logger.forComponent("helia:ipns:local-store")),n=[ND(t),c9(r.routing),...e.routers??[]];return new Py(r,{routers:n,localStore:t})}var BD=42;function iX(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function sX(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=F.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new N(w.tag,BD),new N(w.bytes,t)]}function aX(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function cX(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 lX(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 u9={float64:!0,typeEncoders:{Map:lX,Object:sX,undefined:aX,number:cX}},CUe={...u9,typeEncoders:{...u9.typeEncoders}};function uX(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return F.decode(e.subarray(1))}var d9={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[BD]:uX}},IUe={...d9,tags:{...d9.tags}};var f9=r=>Ko(r,u9),h9=r=>Pr(iX(r),d9);var g9=Yt(Dy(),1);var y9=40;function w9(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=g9.default.decode(r);return e.seek(g9.default.decode.bytes),t}function b9(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}var Qs={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},Wh={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Qs.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Qs.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Wh["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=Wh["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:Qs.Int,CarV1HeaderOrV2Pragma:r=>{if(Qs.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=Wh["CarV1HeaderOrV2Pragma > roots (anon)"](r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=Wh.Int(r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},jh={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Qs.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Qs.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=jh["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=jh["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:Qs.Int,CarV1HeaderOrV2Pragma:r=>{if(Qs.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=jh["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=jh.Int(s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},x9={toTyped:Wh.CarV1HeaderOrV2Pragma,toRepresentation:jh.CarV1HeaderOrV2Pragma};var VUe=k5();var IX=Yt(Dy(),1);var jUe=[new N(w.map,2),new N(w.string,"version"),new N(w.uint,1),new N(w.string,"roots")],YUe=new N(w.tag,42);async function E9(r,e){let t=w9(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),o=h9(n);if(x9.toTyped(o)===void 0)throw new Error("Invalid CAR header format");if(o.version!==1&&o.version!==2||e!==void 0&&o.version!==e)throw new Error(`Invalid CAR version: ${o.version}${e!==void 0?` (expected ${e})`:""}`);if(o.version===1){if(!Array.isArray(o.roots))throw new Error("Invalid CAR header format");return o}if(o.roots!==void 0)throw new Error("Invalid CAR header format");let i=b9(await r.exactly(y9,!0));r.seek(i.dataOffset-r.pos);let s=await E9(r,1);return Object.assign(s,i)}function Yh(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let o=r.subarray(e,e+t);return n&&(e+=t),o},seek(t){e+=t},get pos(){return e}}}var v9=Yt(Dy(),1),jD=1;function S9(r){let e=f9({version:jD,roots:r}),t=v9.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function YD(r){return{async setRoots(e){let t=S9(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(v9.default.encode(t.bytes.length+n.length))),await r.write(t.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return jD}}}function Ly(){}function XD(){let r=[],e=null,t=Ly,n=!1,o=null,i=Ly,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=Ly,l()}})),e),a={write(l){r.push(l);let u=s();return i(),u},async end(){n=!0;let l=s();i(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&t(),{done:!1,value:l}):n?(t(),{done:!0,value:void 0}):(o||(o=new Promise(u=>{i=()=>(o=null,i=Ly,u(c.next()))})),o)}};return{writer:a,iterator:c}}var Xh=class r{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let t=F.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:t,bytes:e.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(e){e=DX(e);let{encoder:t,iterator:n}=QD(),o=new r(e,t),i=new Ny(n);return{writer:o,out:i}}static createAppender(){let{encoder:e,iterator:t}=QD();e.setRoots=()=>Promise.resolve();let n=new r([],e),o=new Ny(t);return{writer:n,out:o}}static async updateRootsInBytes(e,t){let n=Yh(e);await E9(n);let o=S9(t);if(Number(n.pos)!==o.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${o.length} bytes)`);return e.set(o,0),e}},Ny=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function QD(){let r=XD(),{writer:e,iterator:t}=r;return{encoder:YD(e),iterator:t}}function DX(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=F.asCID(r);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}let e=[];for(let t of r){let n=F.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var _u=class{walker;constructor(e){this.walker=e?.walker}async*export(e,t,n,o){let i,s={blockstore:t,getCodec:n};this.walker!=null?i=this.walker(s):i=d0()(s);for await(let a of i.walk(e,o))yield a.block}};var Oy=class{components;log;constructor(e){this.components=e,this.log=e.logger.forComponent("helia:car")}async import(e,t){await pr(this.components.blockstore.putMany(Ct(e.blocks(),({cid:n,bytes:o})=>({cid:n,bytes:o})),t))}async*export(e,t){let n=Array.isArray(e)?e:[e],{writer:o,out:i}=Xh.create(n),s=i[Symbol.asyncIterator](),a=new AbortController;for(this._export(n,o,t).catch(c=>{this.log.error("error during streaming export - %e",c),a.abort(c)});;){let{done:c,value:l}=await Me(s.next(),a.signal);if(a.signal.aborted)throw a.signal.reason;if(l!=null&&(yield l),c===!0)break}}async _export(e,t,n){let o=n?.traversal;for(let i of e){if(i.multihash.code===0)continue;let s=n?.exporter??(i.code===112?new Cu:new _u),a=i,c=!1;if(o!=null){for await(let{cid:l,bytes:u}of o.traverse(a,this.components.blockstore,this.components.getCodec,n))if(this.log.trace("next CID on path to %c is %c",i,l),a=l,i.equals(l)&&(c=!0),c||n?.includeTraversalBlocks===!0){if(n?.blockFilter?.has(l.multihash.bytes)===!0)continue;n?.blockFilter?.add(l.multihash.bytes),await t.put({cid:l,bytes:u})}}for await(let{cid:l,bytes:u}of s.export(a,this.components.blockstore,this.components.getCodec,n))n?.blockFilter?.has(l.multihash.bytes)!==!0&&l.multihash.code!==0&&(c&&l.equals(a)||(n?.blockFilter?.add(l.multihash.bytes),await t.put({cid:l,bytes:u})))}await t.close()}};var Qh=class{async*export(e,t,n,o){let i=await ue(t.get(e,o));yield Ss({cid:e,bytes:i,codec:await n(e.code)})}};var Zh=class r extends Error{static name="InvalidTypeError";static code="ERR_INVALID_TYPE";name=r.name;code=r.code;constructor(e="Invalid type"){super(e)}};var _o;(function(r){let e;(function(a){a.Raw="Raw",a.Directory="Directory",a.File="File",a.Metadata="Metadata",a.Symlink="Symlink",a.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(a){a[a.Raw=0]="Raw",a[a.Directory=1]="Directory",a[a.File=2]="File",a[a.Metadata=3]="Metadata",a[a.Symlink=4]="Symlink",a[a.HAMTShard=5]="HAMTShard"})(t||(t={})),(function(a){a.codec=()=>Ye(t)})(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=re((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.Type!=null&&(c.uint32(8),r.DataType.codec().encode(a.Type,c)),a.Data!=null&&(c.uint32(18),c.bytes(a.Data)),a.filesize!=null&&(c.uint32(24),c.uint64(a.filesize)),a.blocksizes!=null&&a.blocksizes.length>0)for(let u of a.blocksizes)c.uint32(32),c.uint64(u);a.hashType!=null&&(c.uint32(40),c.uint64(a.hashType)),a.fanout!=null&&(c.uint32(48),c.uint64(a.fanout)),a.mode!=null&&(c.uint32(56),c.uint32(a.mode)),a.mtime!=null&&(c.uint32(66),Jh.codec().encode(a.mtime,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={blocksizes:[]},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.Type=r.DataType.codec().decode(a);break}case 2:{u.Data=a.bytes();break}case 3:{u.filesize=a.uint64();break}case 4:{if(l.limits?.blocksizes!=null&&u.blocksizes.length===l.limits.blocksizes)throw new le('Decode error - repeated field "blocksizes" had too many elements');u.blocksizes.push(a.uint64());break}case 5:{u.hashType=a.uint64();break}case 6:{u.fanout=a.uint64();break}case 7:{u.mode=a.uint32();break}case 8:{u.mtime=Jh.codec().decode(a,a.uint32(),{limits:l.limits?.mtime});break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={blocksizes:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${l}.Type`,value:r.DataType.codec().decode(a)};break}case 2:{yield{field:`${l}.Data`,value:a.bytes()};break}case 3:{yield{field:`${l}.filesize`,value:a.uint64()};break}case 4:{if(u.limits?.blocksizes!=null&&d.blocksizes===u.limits.blocksizes)throw new le('Streaming decode error - repeated field "blocksizes" had too many elements');yield{field:`${l}.blocksizes[]`,index:d.blocksizes,value:a.uint64()},d.blocksizes++;break}case 5:{yield{field:`${l}.hashType`,value:a.uint64()};break}case 6:{yield{field:`${l}.fanout`,value:a.uint64()};break}case 7:{yield{field:`${l}.mode`,value:a.uint32()};break}case 8:{yield*Jh.codec().stream(a,a.uint32(),`${l}.mtime`,{limits:u.limits?.mtime});break}default:{a.skipType(h&7);break}}}})),n);function o(a){return ee(a,r.codec())}r.encode=o;function i(a,c){return J(a,r.codec(),c)}r.decode=i;function s(a,c){return te(a,r.codec(),c)}r.stream=s})(_o||(_o={}));var Jh;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Seconds!=null&&(s.uint32(8),s.int64(i.Seconds)),i.FractionalNanoseconds!=null&&(s.uint32(21),s.fixed32(i.FractionalNanoseconds)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.Seconds=i.int64();break}case 2:{c.FractionalNanoseconds=i.fixed32();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Seconds`,value:i.int64()};break}case 2:{yield{field:`${a}.FractionalNanoseconds`,value:i.fixed32()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Jh||(Jh={}));var JD;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.MimeType!=null&&(s.uint32(10),s.string(i.MimeType)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();u>>>3===1?c.MimeType=i.string():i.skipType(u&7)}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();u>>>3===1?yield{field:`${a}.MimeType`,value:i.string()}:i.skipType(u&7)}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(JD||(JD={}));var eL={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},NX=["directory","hamt-sharded-directory"],tL=parseInt("0644",8),rL=parseInt("0755",8),Er=class r{static unmarshal(e){let t=_o.decode(e),n=new r({type:eL[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:t,data:n,blockSizes:o,hashType:i,fanout:s,mtime:a,mode:c}=e;if(t!=null&&!Object.values(eL).includes(t))throw new Zh("Type: "+t+" is not valid");this.type=t??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?rL:tL:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return NX.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=_o.DataType.Raw;break;case"directory":e=_o.DataType.Directory;break;case"file":e=_o.DataType.File;break;case"metadata":e=_o.DataType.Metadata;break;case"symlink":e=_o.DataType.Symlink;break;case"hamt-sharded-directory":e=_o.DataType.HAMTShard;break;default:throw new Zh(`Type: ${e} is not valid`)}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===tL&&!this.isDirectory()&&(n=void 0),n===rL&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),_o.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var ep=class extends Error{static code="ERR_NOT_UNIXFS";static message="Not a UnixFS node";static name="NotUnixFSError";code="ERR_NOT_UNIXFS";message="Not a UnixFS node";name="NotUnixFSError"},By=class extends Error{static name="NotDescendantError";name="NotDescendantError"},My=class extends Error{static name="InvalidTraversalError";name="InvalidTraversalError"};function BX(r){return r.cid.code===85}function MX(r){return r.cid.code===112}function FX(r){if(BX(r))return!0;if(MX(r)&&r.value.Data!=null){let e=Er.unmarshal(r.value.Data);return e.type==="file"||e.type==="raw"}else throw new ep("Encountered non raw/dag-pb CID in UnixFS DAG")}var Cu=class{options;constructor(e){this.options=e}async*export(e,t,n,o){if(e.code!==112&&e.code!==85)throw new ep("Target CID was not UnixFS - use the SubGraphExporter to export arbitrary graphs");let i=Wl()({blockstore:t,getCodec:n}),s=this.options?.offset??0,a=this.options?.length??1/0,c=this.options?.listingOnly??!1;if(s<0)throw new E("Offset cannot be negative");if(a<0)throw new E("Length cannot be negative");let l,u=new AbortController,d=ae([u.signal,o?.signal]);u.signal;function f(h,p){if(l==null&&(l=FX(p)),!l){let D=p.value.Links.find(U=>U.Hash.equals(h)),O=Er.unmarshal(p.value.Data??new Uint8Array);return O.type==="directory"?!c:O.type==="hamt-sharded-directory"&&c?D?.Name?.length===2:!0}let y=p.value.Links.findIndex(D=>D.Hash.equals(h)),g=Er.unmarshal(p.value.Data??new Uint8Array),m=s,b=m+a,_=Number([...g.blockSizes].slice(0,y).reduce((D,O)=>D+O,0n)),R=_+Number(g.blockSizes[y]);return m>=_&&m<R||b>=_&&b<R||m<=_&&b>=R}try{for await(let h of i.walk(e,{...o,includeChild:f,signal:d}))yield h.block}finally{u.abort(),d.clear()}}};var Fy=class{path;constructor(e){this.path=e}async*traverse(e,t,n,o){if(!this.path.some(s=>s.equals(e)))throw new My(`CIDPath traversal must include ${e}`);let i;for(let s of this.path){if(i!=null){let l=!1;for(let[,u]of i.links())if(u.equals(s)){l=!0;break}if(!l)throw new By(`${s} is not a child of ${i.cid}`)}let a=await ue(t.get(s,o)),c=Ss({cid:s,bytes:a,codec:await n(s.code)});i=c,yield c}}};var Iu=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(e="Bad path"){super(e)}},xn=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not found"){super(e)}},ku=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(e="No resolver"){super(e)}},st=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(e="Not UnixFS"){super(e)}},Uy=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(e="Over read"){super(e)}},$y=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(e="Under read"){super(e)}},Gn=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};function Ru(r){return r==null?!1:F.asCID(r)===r}function Pu(r,e){let t,n=0,o="";for(;n<e.length;){let i=e[n];if(n++,!Object.hasOwnProperty.call(r,i))throw new Iu(`Object did not have key "${i}"`);if(o+=`/${i}`,t=r[i],r=t,Ru(t))break}return{value:t,rest:e.slice(n),path:o.substring(1)}}async function*A9(r,e,t,n){let o=await ue(t.get(r,n)),i=As(o),s=Pu(i,e);yield{cid:Ru(s.value)?s.value:r,name:s.path,rest:s.rest}}async function*nL(r,e,t,n){let o=await ue(t.get(r,n)),i=ql(o),s=Pu(i,e);yield{cid:Ru(s.value)?s.value:r,name:s.path,rest:s.rest}}function Zs(r,e){let t=r.lo+e.lo>>>0,n=r.hi+e.hi+(t<r.lo?1:0)>>>0;return{lo:t,hi:n}}function UX(r,e){return r+e>>>0}function Wn(r,e){let t=r.lo&65535,n=r.lo>>>16,o=e.lo&65535,i=e.lo>>>16,s=t*o,a=t*i,c=n*o,l=n*i,u=(s>>>16)+(a&65535)+(c&65535)>>>0,d=(u<<16|s&65535)>>>0,f=l+(a>>>16)+(c>>>16)+(u>>>16),h=Math.imul(r.lo,e.hi),p=Math.imul(r.hi,e.lo),y=f+h+p>>>0;return{lo:d,hi:y}}function Ac(r,e){return Math.imul(r,e)>>>0}function Du(r,e){if(e===0)return r;if(e===32)return{lo:r.hi,hi:r.lo};if(e<32){let o=(r.lo<<e|r.hi>>>32-e)>>>0,i=(r.hi<<e|r.lo>>>32-e)>>>0;return{lo:o,hi:i}}e-=32;let t=(r.hi<<e|r.lo>>>32-e)>>>0,n=(r.lo<<e|r.hi>>>32-e)>>>0;return{lo:t,hi:n}}function at(r,e){return{lo:(r.lo^e.lo)>>>0,hi:(r.hi^e.hi)>>>0}}function T9(r,e){if(e===0)return r;if(e<32){let t=(r.lo>>>e|r.hi<<32-e)>>>0,n=r.hi>>>e;return{lo:t,hi:n}}return{lo:r.hi>>>e-32,hi:0}}function je(r,e){return{lo:r>>>0,hi:e>>>0}}function _9(r,e){return(r<<e|r>>>32-e)>>>0}function oL(r,e){let t=e*8,n=r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24,o=r[t+4]|r[t+5]<<8|r[t+6]<<16|r[t+7]<<24;return{lo:n>>>0,hi:o>>>0}}function $X(r,e){let t=e*4;return(r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24)>>>0}function iL(r){return r=at(r,T9(r,33)),r=Wn(r,je(3981806797,4283543511)),r=at(r,T9(r,33)),r=Wn(r,je(444984403,3301882366)),r=at(r,T9(r,33)),r}function HX(r){return r^=r>>>16,r=Ac(r,2246822507),r^=r>>>13,r=Ac(r,3266489909),r^=r>>>16,r}function C9(r,e=0){let t=je(e,0),n=je(e,0),o=r.length,i=Math.floor(o/16),s=je(289559509,2277735313),a=je(658871167,1291169091);for(let f=0;f<i;f++){let h=oL(r,f*2),p=oL(r,f*2+1);h=Wn(h,s),h=Du(h,31),h=Wn(h,a),t=at(t,h),t=Du(t,27),t=Zs(t,n),t=Zs(Wn(t,je(5,0)),je(1390208809,0)),p=Wn(p,a),p=Du(p,33),p=Wn(p,s),n=at(n,p),n=Du(n,31),n=Zs(n,t),n=Zs(Wn(n,je(5,0)),je(944331445,0))}let c=je(0,0),l=je(0,0),u=r.slice(i*16);switch(u.length){case 15:l=at(l,je(0,u[14]<<16));case 14:l=at(l,je(0,u[13]<<8));case 13:l=at(l,je(0,u[12]));case 12:l=at(l,je(u[11]<<24,0));case 11:l=at(l,je(u[10]<<16,0));case 10:l=at(l,je(u[9]<<8,0));case 9:l=at(l,je(u[8],0)),l=Wn(l,a),l=Du(l,33),l=Wn(l,s),n=at(n,l);case 8:c=at(c,je(0,u[7]<<24));case 7:c=at(c,je(0,u[6]<<16));case 6:c=at(c,je(0,u[5]<<8));case 5:c=at(c,je(0,u[4]));case 4:c=at(c,je(u[3]<<24,0));case 3:c=at(c,je(u[2]<<16,0));case 2:c=at(c,je(u[1]<<8,0));case 1:c=at(c,je(u[0],0)),c=Wn(c,s),c=Du(c,31),c=Wn(c,a),t=at(t,c)}let d=je(o,0);return t=at(t,d),n=at(n,d),t=Zs(t,n),n=Zs(n,t),t=iL(t),n=iL(n),t=Zs(t,n),n=Zs(n,t),new Uint8Array([t.hi>>>24&255,t.hi>>>16&255,t.hi>>>8&255,t.hi&255,t.lo>>>24&255,t.lo>>>16&255,t.lo>>>8&255,t.lo&255,n.hi>>>24&255,n.hi>>>16&255,n.hi>>>8&255,n.hi&255,n.lo>>>24&255,n.lo>>>16&255,n.lo>>>8&255,n.lo&255])}function sL(r,e=0){let t=e>>>0,n=r.length,o=Math.floor(n/4),i=3432918353,s=461845907;for(let l=0;l<o;l++){let u=$X(r,l);u=Ac(u,i),u=_9(u,15),u=Ac(u,s),t^=u,t=_9(t,13),t=UX(Ac(t,5),3864292196)}let a=r.slice(o*4),c=0;switch(a.length){case 3:c^=a[2]<<16;case 2:c^=a[1]<<8;case 1:c^=a[0],c=Ac(c,i),c=_9(c,15),c=Ac(c,s),t^=c}return t^=n,t=HX(t),t}function VX(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var THe=li({name:"murmur3-32",code:35,encode:r=>VX(sL(r))}),aL=li({name:"murmur3-128",code:34,encode:r=>C9(r)}),_He=li({name:"murmur3-x64-64",code:34,encode:r=>C9(r).subarray(0,8)});var mL=Yt(uL(),1);function Hy(r=0){return new Uint8Array(r)}function fL(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var dL=fL("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),I9=fL("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=Hy(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),WX={utf8:dL,"utf-8":dL,hex:oe.base16,latin1:I9,ascii:I9,binary:I9,...oe},hL=WX;function pL(r,e="utf8"){let t=hL[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Tc=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new mL.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof r?o.push(i.serialize(e,t)):o.push(e(i,s))),o),n))}async asyncTransform(e,t){return gL(this,e,t)}toJSON(){return this.serialize(YX,XX)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?pL(e):e),n=await t.take(this._options.bits),o=this._children.get(n);return o instanceof r?o._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:o}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let o=await n._findPlace(t.existingChild.hash);return o.bucket._putAt(o,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(jX);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function jX(r){return!!r}function YX(r,e){return r.key}function XX(r){return r}async function gL(r,e,t){let n=[];for(let o of r._children.compactArray())if(o instanceof Tc)await gL(o,e,t);else{let i=await e(o);n.push({bitField:r._children.bitField(),children:i})}return t(n)}function QX(r){return r?.buffer instanceof ArrayBuffer}function yL(r){if(QX(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function wL(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=Hy(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return yL(t)}var ZX=[255,254,252,248,240,224,192,128],JX=[1,3,7,15,31,63,127,255],qy=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,t),a=eQ(o,i-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function eQ(r,e,t){let n=tQ(e,t);return(r&n)>>>e}function tQ(r,e){return ZX[r]&JX[Math.min(e+r-1,7)]}function bL(r){function e(t){return t instanceof Vy?t:new Vy(t,r)}return e}var Vy=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),t),s=o.take(i);n=(n<<i)+s,t-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),t);n.untake(o),t-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?wL([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new qy(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function xL(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:bL(r.hashFn)};return new Tc(e)}var rQ=async function(r){return(await aL.encode(r)).slice(0,8).reverse()},nQ=async(r,e,t)=>{let n=(e.tableSize()-1).toString(16).length;await Promise.all(r.map(async o=>{if(o.Name==null)throw new Error("Unexpected Link without a Name");if(o.Name.length===n){let i=parseInt(o.Name,16);e._putObjectAt(i,new Tc({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(o.Name.substring(2),!0)}))},EL=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),oQ=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()};async function*k9(r,e,t,n,o,i){if(o==null){if(r.Data==null)throw new st("No data in PBNode");let f;try{f=Er.unmarshal(r.Data)}catch(p){throw new st(p.message)}if(f.type!=="hamt-sharded-directory")throw new st("Not a HAMT");if(f.fanout==null)throw new st("Missing fanout");let h=xL({hashFn:rQ,bits:Math.log2(Number(f.fanout))});o={rootBucket:h,hamtDepth:1,lastBucket:h}}let s=(o.lastBucket.tableSize()-1).toString(16).length;await nQ(r.Links,o.lastBucket,o.rootBucket);let a=await o.rootBucket._findNewBucketAndPos(e),c=EL(a.pos,s),l=oQ(a);l.length>o.hamtDepth&&(o.lastBucket=l[o.hamtDepth],c=EL(o.lastBucket._posAtParent,s));let u=r.Links.find(f=>{if(f.Name==null)return!1;let h=f.Name.substring(0,s),p=f.Name.substring(s);return!(h!==c||p!==""&&p!==e)});if(u==null)return;if(u.Name!=null&&u.Name.substring(s)===e){yield{cid:u.Hash,name:u.Name.substring(s),rest:t};return}o.hamtDepth++;let d=await ue(n.get(u.Hash,i));r=hn(d),i?.yieldSubShards===!0&&(yield{cid:u.Hash,name:u.Name??"",rest:[e,...t]}),yield*k9(r,e,t,n,o,i)}async function*vL(r,e,t,n){let o=await ue(t.get(r,n)),i;try{i=hn(o)}catch(a){throw new st(a.message)}if(i.Data==null)throw new st("no data in PBNode");let s;try{s=Er.unmarshal(i.Data)}catch(a){throw new st(a.message)}if(s.type==="directory"||s.type==="hamt-sharded-directory"&&n?.translateHAMTPath===!1){let a=i.Links.find(c=>c.Name===e[0]);if(a==null)throw new xn(`No link "${e[0]}" found under ${r}`);yield{cid:a.Hash,name:e[0],rest:e.slice(1)}}else if(s.type==="hamt-sharded-directory"){let a=!1;for await(let c of k9(i,e[0],e.slice(1),t,void 0,n))c.name===e[0]&&(a=!0),yield c;if(!a)throw new xn(`No link "${e[0]}" found under ${r}`)}}async function*SL(r,e,t,n){if(e.length!==0)throw new Iu(`Cannot load path /${e.join("/")} from identity block`)}async function*AL(r,e,t,n){let o=await ue(t.get(r,n)),i=ua(o),s=Pu(i,e);yield{cid:r,name:s.path,rest:s.rest}}async function*TL(r,e,t,n){if(e.length!==0)throw new xn(`Cannot load path /${e.join("/")} from raw block`)}var sQ={[We]:vL,[Ie]:TL,[tr]:A9,81:A9,[rr]:nL,[Ke.code]:SL,[ar]:AL};async function*Js(r,e,t={}){for(r=r.toString(),r.startsWith("/ipfs/")&&(r=r.substring(6));r.endsWith("/");)r=r.substring(0,r.length-1);let[n,...o]=r.split(/(?<!\\)\//g).filter(Boolean),i=F.parse(n),s=[i],a=`${i}`;for(yield{cid:i,name:a,path:a,roots:s,remainder:o};o.length>0;){let c=sQ[i.code];if(c==null)throw new ku(`No resolver for code ${i.code}`);let l=!1;for await(let u of c(i,o,e,t)){if(i=u.cid,l=!s[s.length-1].equals(i),o=u.rest,!l)break;s=[...s,u.cid],a=`${a}/${u.name}`,yield{cid:u.cid,name:u.name,path:a,roots:s,remainder:u.rest}}if(!l)break}if(t?.signal?.throwIfAborted(),o.length!==0)throw new xn(`Could not resolve path /${o.join("/")} under ${r}`)}function aQ(r){return r[Symbol.asyncIterator]!=null}function cQ(r){if(aQ(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var Lu=cQ;async function R9(r,e,t,n,o){let i=await ue(n.get(r,o)),s=As(i);return{type:"object",cid:r,name:e,path:t,object:s,node:i}}async function _L(r,e,t,n,o){let i=await ue(n.get(r,o)),s=ql(i);return{type:"object",cid:r,name:e,path:t,object:s,node:i}}function tp(r,e,t,n){let o=BigInt(r.length),i=BigInt(e+o);return t>=i||n<e?new Uint8Array(0):(n>=e&&n<i&&(r=r.subarray(0,Number(n-e))),t>=e&&t<i&&(r=r.subarray(Number(t-e))),r)}var Ky=(r,e=0,t=r)=>{let n=BigInt(r),o=BigInt(e??0),i=BigInt(t);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw new Gn("Offset must be greater than or equal to 0");if(o>n)throw new Gn("Offset must be less than the file size");if(i<0n)throw new Gn("Length must be greater than or equal to 0");if(i>n)throw new Gn("Length must be less than the file size");return{start:o,end:i}};function zy(r,e){async function*t(n={}){let{start:o,end:i}=Ky(r.length,n.offset,n.length),s=tp(r,0n,o,i);n.onProgress?.(new k(e,{bytesRead:BigInt(s.byteLength),totalBytes:i-o,fileSize:BigInt(r.byteLength)})),yield s}return t}async function CL(r,e,t,n,o){let i=xe(r.multihash.bytes);return{type:"identity",cid:r,name:e,path:t,content:zy(i.digest,"unixfs:exporter:progress:identity"),size:BigInt(i.bytes.length),node:i.bytes}}async function IL(r,e,t,n,o){let i=await ue(n.get(r,o)),s=ua(i);return{type:"object",cid:r,name:e,path:t,object:s,node:i}}async function kL(r,e,t,n,o){let i=await ue(n.get(r,o));return{type:"raw",cid:r,name:e,path:t,content:zy(i,"unixfs:exporter:progress:raw"),size:BigInt(i.length),node:i}}function RL(r,e,t,n){async function*o(i={}){let s=i.offset??0,a=i.length??e.Links.length,c=e.Links.slice(s,a);i.onProgress?.(new k("unixfs:exporter:walk:directory",{cid:r})),yield*c.map(l=>({cid:l.Hash,name:l.Name??"",path:`${n}/${l.Name??""}`}))}return o}async function PL(r,e,t,n,o,i,s){if(e instanceof Uint8Array){let l=tp(e,n,o,i);t.push(l);return}if(e.Data==null)throw new st("no data in PBNode");let a;try{a=Er.unmarshal(e.Data)}catch(l){throw new st(l.message)}if(a.data!=null){let l=a.data,u=tp(l,n,o,i);t.push(u),n+=BigInt(u.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw new st("Inconsistent block sizes and dag links");for(let l=0;l<e.Links.length;l++){let u=e.Links[l],d=n,f=d+a.blockSizes[l];if((o>=d&&o<f||i>=d&&i<=f||o<d&&i>f)&&c.push({link:u,blockStart:n}),n=f,n>i)break}await on(c,l=>Ct(l,u=>async()=>{let d=await ue(r.get(u.link.Hash,s));return{...u,block:d}}),l=>yn(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:u,block:d,blockStart:f}of l){let h;switch(u.Hash.code){case We:h=hn(d);break;case Ie:h=d;break;default:t.end(new st(`Unsupported codec: ${u.Hash.code}`));return}let p=new _i({concurrency:1});p.on("error",y=>{t.end(y)}),p.add(async()=>{s.onProgress?.(new k("unixfs:exporter:walk:file",{cid:u.Hash})),await PL(r,h,t,f,o,i,s)}),await p.onIdle()}}),n>=i&&t.end()}function P9(r,e,t,n,o){async function*i(s={}){let a=t.fileSize();if(a===void 0)throw new Error("File was a directory");let{start:c,end:l}=Ky(a,s.offset,s.length);if(l===0n)return;let u=0n,d=l-c,f=Nt();s.onProgress?.(new k("unixfs:exporter:walk:file",{cid:r})),PL(o,e,f,0n,c,l,s).catch(h=>{f.end(h)});for await(let h of f)if(h!=null){if(u+=BigInt(h.byteLength),u>d)throw f.end(),new Uy("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");u===d&&f.end(),s.onProgress?.(new k("unixfs:exporter:progress:unixfs:file",{bytesRead:u,totalBytes:d,fileSize:a})),yield h}if(u<d)throw new $y("Traversed entire DAG but did not read enough bytes")}return i}async function*DL(r,e,t,n){let o=r.Links;if(r.Data==null)throw new st("no data in PBNode");let i;try{i=Er.unmarshal(r.Data)}catch(c){throw new st(c.message)}if(i.fanout==null)throw new st("missing fanout");let s=(i.fanout-1n).toString(16).length,a=on(o,c=>Ct(c,l=>async()=>{let u=l.Name!=null?l.Name.substring(s):null;if(u!=null&&u!=="")return{entries:[{cid:l.Hash,name:u,path:`${e}/${u}`}]};{let d=await ue(t.get(l.Hash,n));return r=hn(d),n.onProgress?.(new k("unixfs:exporter:walk:hamt-sharded-directory",{cid:l.Hash})),{entries:DL(r,e,t,n)}}}),c=>yn(c,{ordered:!0,concurrency:n.blockReadConcurrency}));for await(let{entries:c}of a)yield*c}function LL(r,e,t,n,o){function i(s={}){return s.onProgress?.(new k("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),DL(e,n,o,s)}return i}var lQ={raw:P9,file:P9,directory:RL,"hamt-sharded-directory":LL,metadata:(r,e,t,n)=>()=>[],symlink:(r,e,t,n)=>()=>[]};async function NL(r,e,t,n,o){let i=await ue(n.get(r,o)),s;try{s=hn(i)}catch(l){throw new st(l.message)}if(s.Data==null)throw new st("no data in PBNode");let a;try{a=Er.unmarshal(s.Data)}catch(l){throw new st(l.message)}let c=lQ[a.type](r,s,a,t,n);if(c==null)throw new xn("could not find content exporter");return a.isDirectory()?{type:"directory",cid:r,name:e,path:t,entries:c,unixfs:a,node:s}:{type:"file",cid:r,name:e,path:t,content:c,unixfs:a,node:s,size:a.fileSize()}}var uQ={[We]:NL,[Ie]:kL,[tr]:R9,81:R9,[rr]:_L,[Ke.code]:CL,[ar]:IL};async function jn(r,e,t={}){let n,o;if(r instanceof String||typeof r=="string"){let s=await Lu(Js(r,e,t));if(s==null)throw new xn(`Could not walk path to ${r}`);n=s.cid,o=s.name,r=s.path}else if(F.asCID(r)===r||r instanceof F)n=r,o=r=n.toString();else throw new Gn("Path must be string or CID");let i=uQ[n.code];if(i==null)throw new ku(`No resolver for code ${n.code}`);return i(n,o,r,e,t)}async function*OL(r,e,t={}){let n=await jn(r,e,t);if(n==null)return;if(yield{cid:n.cid,name:n.name,path:n.path,depth:0},n.type==="directory")for await(let i of o(n,0,`${r}`,t))yield i;async function*o(i,s,a,c){s++;for await(let l of i.entries(c)){let u=`${a}/${l.name}`;yield{...l,depth:s,path:u};let d=await jn(l.cid,e,c);d.type==="directory"&&(yield*o(d,s,u,c))}}}function BL(r){return new Oy(r)}var En="application/vnd.ipld.dag-cbor",vn="application/cbor",Sn="application/vnd.ipld.dag-json",An="application/json",sr="application/vnd.ipld.raw",Ft="application/octet-stream",_c="application/vnd.ipfs.ipns-record",Cc="application/vnd.ipld.car",Nu="application/x-tar",np="application/vnd.ipld.dag-pb",Gy={mediaType:Ft,codecs:[Ie,ar,rr,81,tr,We],immutable:!0,extension:".bin",etag:"",disposition:"attachment"},dQ={mediaType:En,codecs:[tr,Ie,We],immutable:!0,extension:".cbor",etag:".dag-cbor",disposition:"attachment"},fQ={mediaType:vn,codecs:[81,tr,Ie,We],immutable:!0,extension:".cbor",etag:".cbor",disposition:"attachment"},hQ={mediaType:Sn,codecs:[rr,Ie,We],immutable:!0,extension:".json",etag:".dag-json",disposition:"inline"},pQ={mediaType:An,codecs:[ar,rr,Ie,We],immutable:!0,extension:".json",etag:".json",disposition:"inline"},ML={mediaType:sr,codecs:[Ie,ar,rr,81,tr,We],immutable:!0,extension:".raw",etag:".raw",disposition:"attachment"},Ic={mediaType:_c,codecs:[],immutable:!1,extension:".bin",etag:".bin",disposition:"attachment"},D9={mediaType:Cc,codecs:[Ie,ar,rr,81,tr,We],immutable:!1,extension:".car",etag:".car",disposition:"attachment"},mQ={mediaType:Nu,codecs:[Ie,We],immutable:!1,extension:".x-tar",etag:".x-tar",disposition:"attachment"},FL=[dQ,fQ,hQ,pQ,ML,Ic,D9,mQ,Gy];function UL(r){return FL.find(e=>e.mediaType===r)}function op(r){return r==null?[]:FL.filter(e=>e.codecs.includes(r.code)).sort((e,t)=>{let n=e.codecs.indexOf(r.code),o=t.codecs.indexOf(r.code);return n<o?-1:o<n?1:0})}function $L(r="ipfs:",e){let t=op(e);return r==="ipfs:"&&t.length===0&&(t=[ML,Gy]),r==="ipns:"&&t.push(Ic),t}function jr(r){if(r==null)throw new E("Cannot get filename for Content-Disposition header - filename argument was missing");let e=gQ(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function gQ(r){return r.replace(/[^\x00-\x7F]/g,"_")}var Fr=class extends Error{static name="InvalidRangeError";name="InvalidRangeError"},L9=class extends Error{static name="NoContentError";name="NoContentError"},N9=class extends Error{static name="SubdomainNotSupportedError";name="SubdomainNotSupportedError"},ip=class extends Error{static name="RedirectsFileTooLargeError";name="RedirectsFileTooLargeError"},sp=class extends Error{static name="InvalidRedirectsFileError";name="InvalidRedirectsFileError"},ap=class extends Error{static name="InvalidRedirectStatusCodeError";name="InvalidRedirectStatusCodeError"},cp=class extends Error{static name="DuplicatePlaceholderError";name="DuplicatePlaceholderError"};function yQ(r){return typeof r?.serverTiming=="string"&&r?.name==="AbortError"}function HL({offset:r,length:e}){return{offset:Number(r),length:Number(e)}}function O9(r,e,t){if(r=BigInt(r),e!=null){if(e=BigInt(e),e<0n)throw new Fr("Range start cannot be negative");if(e>=r)throw new Fr("Range start cannot be larger than total bytes")}if(t!=null){if(t=BigInt(t),(t>0n?t:-t)>=r)throw new Fr("Range end cannot be larger than total bytes");if(t<0n)if(e==null)e=r+t,t=r-1n;else throw new Fr("Range end cannot be negative");t+=1n}return HL(VL(r,e,t))}function qL(r,e){r=BigInt(r);let t=(e??"0:*").split(":"),n=BigInt(t[0]),o=t[1]==="*"?r:BigInt(t[1]);return HL(VL(r,n,o))}function VL(r,e=0n,t=r){if(e>=0n)return t>=0n?{offset:e,length:t-e}:{offset:e,length:r-e+t};let n=r+e;return Math.abs(Number(e))>Number(r)&&(n=0n),t>=0n?{offset:n,length:t-n}:{offset:n,length:r-n+t}}function wQ(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r?.errors)}function kc(r){let e;return wQ(r)&&(e=r.errors.map(t=>kc(t))),{name:r.name,message:r.message,stack:r.stack,errors:e}}function KL({ttl:r,protocol:e,response:t}){if(t.headers.has("cache-control"))return;let n;e==="ipfs:"?n="public, max-age=29030400, immutable":r==null?n="public, max-age=300":n=`public, max-age=${r}`,t.headers.set("cache-control",n)}function B9(r,e,t){e!=null&&(e=BigInt(e)),t!=null&&(t=BigInt(t));let n=BigInt(r);if((t??0n)>=n)throw new Fr("Invalid range: Range-end index is greater than or equal to the size of the file.");if((e??0n)>=n)throw new Fr("Invalid range: Range-start index is greater than or equal to the size of the file.");let o="*";if(e==null)t!=null&&(t<0n?o=`${n+t}-${n-1n}`:o=`0-${t}`);else if(t==null){let i="*";r!=null&&(i=`${n-1n}`),o=`${e}-${i}`}else o=`${e}-${t}`;return`bytes ${o}/${n}`}function M9(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function Tn(r,e){r.type!==e&&M9(r,"type",e)}function _n(r,e){e=e.toString();let t=e.indexOf("#");t>-1&&(e=e.substring(0,t)),r.url!==e&&M9(r,"url",e)}function GL(r){M9(r,"redirected",!0)}function bQ(r){return r.buffer instanceof ArrayBuffer}function zL(r){if(bQ(r))return r;let e=new ArrayBuffer(r.byteLength),t=new Uint8Array(e);return t.set(r),t}function xQ(r){return r==null?!1:typeof r.pipeThrough=="function"&&typeof r.getReader=="function"}function lp(r){return r==null?r:r instanceof Uint8Array?zL(r):xQ(r)?r.pipeThrough(new TransformStream({transform(e,t){t.enqueue(zL(e))}})):r}function Cn(r,e,t){let n=new Response(lp(e),{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&GL(n),Tn(n,"basic"),_n(n,r),n}function F9(r,e,t){let n=new Response(JSON.stringify({error:kc(e)}),{...t??{},status:500,statusText:"Internal Server Error"});return n.headers.set("X-Content-Type-Options","nosniff"),n.headers.set("content-type","application/json"),n.headers.set("x-error-message",btoa(e.message)),Tn(n,"basic"),_n(n,r),n}function Wy(r,e,t){let n=new Response(lp(e),{...t??{},status:504,statusText:"Gateway Timeout"});return Tn(n,"basic"),_n(n,r),n}function Rc(r,e,t){let n=new Response(lp(e),{...t??{},status:502,statusText:"Bad Gateway"});return Tn(n,"basic"),_n(n,r),n}function U9(r,e,t){let n=new Response(lp(e),{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),Tn(n,"basic"),_n(n,r),n}function ea(r,e,t,n){let o=new Headers(n?.headers);o.set("content-type","application/json");let i=new Response(JSON.stringify({requested:e.map(s=>s.mediaType),acceptable:t.map(s=>s.mediaType)}),{...n??{},status:406,statusText:"Not Acceptable",headers:o});return Tn(i,"basic"),_n(i,r),i}function $9(r,e,t){let n=new Response(lp(e),{...t??{},status:404,statusText:"Not Found"});return Tn(n,"basic"),_n(n,r),n}function EQ(r){return Array.isArray(r)&&r.every(e=>e instanceof Error)}function Yr(r,e,t){let n,o;EQ(e)?(n=e[e.length-1].stack,o=e.map(a=>({message:a.message,stack:a.stack??""}))):e instanceof Error&&(n=e.stack,o=[{message:e.message,stack:e.stack??""}]);let i=JSON.stringify({stack:n,errors:o}),s=new Response(i,{status:400,statusText:"Bad Request",...t??{},headers:{...t?.headers??{},"Content-Type":"application/json"}});return Tn(s,"basic"),_n(s,r),s}function WL(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return Tn(n,"basic"),_n(n,r),n}function H9(r,e,t){let n=new Response(null,{...t??{},status:304,statusText:"Not Modified"});return["cache-control","content-location","date","etag","expires","vary"].forEach(i=>{let s=e.get(i);s!=null&&n.headers.set(i,s)}),Tn(n,"basic"),_n(n,r),n}function Ou(r,e,t,n,o){let i;if(t.ranges.length===1)i=vQ(r,e,t.ranges[0],n,o);else if(t.ranges.length>1)i=SQ(r,e,t,n,o);else return jy(r,n);return o?.redirected===!0&&GL(i),Tn(i,"basic"),_n(i,r),i}function vQ(r,e,t,n,o){try{let i=new Headers(o?.headers),{offset:s,length:a}=O9(n,t.start,t.end);i.set("content-length",`${a}`),i.set("content-range",B9(n,t.start,t.end));let c=Kn(e(s,a));return new Response(c,{...o??{},status:206,statusText:"Partial Content",headers:i})}catch(i){return i.name==="InvalidRangeError"?jy(r,n,o):F9(r,i,o)}}function SQ(r,e,t,n,o){let i=new Headers(o?.headers),s=i.get("content-type");if(s==null)throw new Error("Content-Type header must be set");i.delete("content-type");let a=0n,c=t.ranges.map(({start:d,end:f})=>{let h=K([`--${t.multipartBoundary}`,`Content-Type: ${s}`,`Content-Range: ${B9(n,d,f)}`,"",""].join(`\r
103
+ a=ice-pwd:`+e+t)}catch{}return r}var Jb=Yb("libp2p-webrtc-noise:");function cD(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=Yb(n,"hex"),i=Cr(ct.code,o),s=Xb.decode(Qb(e)),a=Jb.byteLength+i.bytes.byteLength+s.byteLength;return t==="server"?Wb([Jb,s,i.bytes],a):Wb([Jb,i.bytes,s],a)}function QY(r,e){return r.role==="server"}async function lD(r,e,t,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let d=await r.createOffer();n.log.trace("client created local offer %s",d.sdp);let f=Zb(d,t);n.log.trace("client setting local offer %s",f.sdp),await r.setLocalDescription(f);let h=iD(n.remoteAddr,t);n.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let d=sD(n.remoteAddr,t);n.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),n.log.trace("server creating local answer");let f=await r.createAnswer();n.log.trace("server created local answer");let h=Zb(f,t);n.log.trace("server setting local description %s",f.sdp),await r.setLocalDescription(h)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await ke(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),QY(n,r)){let d=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(oD(d))}let i=nD(r.localDescription?.sdp);if(i==null)throw new Ys("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let s=cD(i,n.remoteAddr,n.role),a=Pg({prologueBytes:s})(n),c=Hh({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),l=qh({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener("connectionstatechange",()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{n.log.error("error closing connection - %e",d),l.abort(d)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let d=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:d.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(i){throw o.close(),r.close(),i}}async function uD(r,e,t={}){let n=t.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t.rtcConfiguration=="function"?await t.rtcConfiguration():t.rtcConfiguration,i=new RTCPeerConnection({...o??{},certificates:[n]}),s=new js({peerConnection:i,metrics:t.events,dataChannelOptions:t.dataChannel});return{peerConnection:i,muxerFactory:s}}var by=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Xi]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[be]=["@libp2p/transport"];async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=Ee(o));let i=WP(),{peerConnection:s,muxerFactory:a}=await uD("client",i,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await lD(s,a,i,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw s.close(),c}}createListener(e){throw new fy("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(Fa.exactMatch)}};function xy(r){return e=>new by(e,r)}function dD(r){return e=>new yy(e,r)}function fD(){throw new Error("WebSocket Servers can not be created in the browser!")}function hD(r=0){return new Uint8Array(r)}function mD(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var pD=mD("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),e9=mD("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=hD(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ZY={utf8:pD,"utf-8":pD,hex:oe.base16,latin1:e9,ascii:e9,binary:e9,...oe},gD=ZY;function yD(r,e="utf8"){let t=gD[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function JY(r){return r.buffer instanceof ArrayBuffer}function wD(r){return JY(r)?r:r.slice()}var eX=1024*1024*4,tX=10,t9=class extends ps{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??eX,this.checkBufferedAmountTask=Ml(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??tX),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=yD(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(wD(n));let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function bD(r){return new t9(r)}var r9=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Xi]=!0;[Symbol.toStringTag]="@libp2p/websockets";[be]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=bD({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=Ts(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new k("websockets:open-connection")),await ke(o,"open",t)}catch(i){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new $c(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw i}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return fD({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>fo.exactMatch(t)||xi.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function Ey(r={}){return e=>new r9(e,r)}var n9=Yt(v0(),1);function vy(r,e){let t=e.map((n,o)=>({record:mn(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===qr.ValidityType.EOL&&o.record.validityType===qr.ValidityType.EOL){let a=n9.default.fromString(n.record.validity).toDate(),c=n9.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var xD="6.1.4",ED="helia";var vD={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function Vh(r={}){let e=`${ED}/${xD} ${_2()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[jk(),dD(),xy(),Ey()],connectionEncrypters:[Pg()],streamMuxers:[Ck(),NP()],peerDiscovery:[Dk(vD)],services:{autoNAT:Pk(),dcutr:Qk(),delegatedRouting:O0(Lw()),dht:CP({clientMode:!0,validators:{ipns:sc},selectors:{ipns:vy}}),identify:GR(),identifyPush:WR(),keychain:Eg(r.keychain),ping:$P(),http:BR()}}}async function SD(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await b7(r.datastore,r.keychain));let t=Vh(e);return t.datastore=t.datastore??r.datastore,await C2({...t,...e,start:!1})}async function AD(r={}){let e=r.datastore??new cc,t=r.blockstore??new Lf,n;return UC(r.libp2p)?n=r.libp2p:n=await SD({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[If(),Cf()],routers:r.routers??[Df(n),Pf()],metrics:n.metrics}}async function TD(r={}){let e=await AD(r),t=new h0(e);return e.start!==!1&&await t.start(),t}function _D(){let r=Vh();r.start=!1,r.addresses={listen:[]},r.transports=[xy(),Ey()],r.peerDiscovery=[];let e={dcutr:r.services.dcutr,identify:r.services.identify,keychain:r.services.keychain,ping:r.services.ping};return{...r,start:!1,services:e}}var Xs=class extends Map{#e=0;#t=new Map;#r=new Map;#i;#a;#d;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.#i=e.maxSize,this.#a=e.maxAge||Number.POSITIVE_INFINITY,this.#d=e.onEviction}get __oldCache(){return this.#r}#f(e){if(typeof this.#d=="function")for(let[t,n]of e)this.#d(t,n.value)}#c(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.#d=="function"&&this.#d(e,t.value),this.delete(e)):!1}#y(e,t){if(this.#c(e,t)===!1)return t.value}#h(e,t){return t.expiry?this.#y(e,t):t.value}#p(e,t){let n=t.get(e);return this.#h(e,n)}#u(e,t){this.#t.set(e,t),this.#e++,this.#e>=this.#i&&(this.#e=0,this.#f(this.#r),this.#r=this.#t,this.#t=new Map)}#l(e,t){this.#r.delete(e),this.#u(e,t)}*#o(){for(let e of this.#r){let[t,n]=e;this.#t.has(t)||this.#c(t,n)===!1&&(yield e)}for(let e of this.#t){let[t,n]=e;this.#c(t,n)===!1&&(yield e)}}get(e){if(this.#t.has(e)){let t=this.#t.get(e);return this.#h(e,t)}if(this.#r.has(e)){let t=this.#r.get(e);if(this.#c(e,t)===!1)return this.#l(e,t),t.value}}set(e,t,{maxAge:n=this.#a}={}){let o=typeof n=="number"&&n!==Number.POSITIVE_INFINITY?Date.now()+n:void 0;return this.#t.has(e)?this.#t.set(e,{value:t,expiry:o}):this.#u(e,{value:t,expiry:o}),this}has(e){return this.#t.has(e)?!this.#c(e,this.#t.get(e)):this.#r.has(e)?!this.#c(e,this.#r.get(e)):!1}peek(e){if(this.#t.has(e))return this.#p(e,this.#t);if(this.#r.has(e))return this.#p(e,this.#r)}expiresIn(e){let t=this.#t.get(e)??this.#r.get(e);if(t)return t.expiry?t.expiry-Date.now():Number.POSITIVE_INFINITY}delete(e){let t=this.#t.delete(e);return t&&this.#e--,this.#r.delete(e)||t}clear(){this.#t.clear(),this.#r.clear(),this.#e=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this.#o()],n=t.length-e;n<0?(this.#t=new Map(t),this.#r=new Map,this.#e=t.length):(n>0&&this.#f(t.slice(0,n)),this.#r=new Map(t.slice(n)),this.#t=new Map,this.#e=0),this.#i=e}evict(e=1){let t=Number(e);if(!t||t<=0)return;let n=[...this.#o()],o=Math.trunc(Math.min(t,Math.max(n.length-1,0)));o<=0||(this.#f(n.slice(0,o)),this.#r=new Map(n.slice(o)),this.#t=new Map,this.#e=0)}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.#t){let[t,n]=e;this.#c(t,n)===!1&&(yield[t,n.value])}for(let e of this.#r){let[t,n]=e;this.#t.has(t)||this.#c(t,n)===!1&&(yield[t,n.value])}}*entriesDescending(){let e=[...this.#t];for(let t=e.length-1;t>=0;--t){let n=e[t],[o,i]=n;this.#c(o,i)===!1&&(yield[o,i.value])}e=[...this.#r];for(let t=e.length-1;t>=0;--t){let n=e[t],[o,i]=n;this.#t.has(o)||this.#c(o,i)===!1&&(yield[o,i.value])}}*entriesAscending(){for(let[e,t]of this.#o())yield[e,t.value]}get size(){if(!this.#e)return this.#r.size;let e=0;for(let t of this.#r.keys())this.#t.has(t)||e++;return Math.min(this.#e+e,this.#i)}get maxSize(){return this.#i}get maxAge(){return this.#a}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,o]of this.entriesAscending())e.call(t,o,n,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};var Sy=class extends Error{static name="DNSLinkNotFoundError";constructor(e="DNSLink not found"){super(e),this.name="DNSLinkNotFoundError"}},Tu=class extends Error{static name="InvalidNamespaceError";constructor(e="Invalid namespace"){super(e),this.name="InvalidNamespaceError"}};var CD=(r,e)=>{let[,t,n,...o]=r.split("/");if(t!=="ipfs")throw new Tu(`Namespace ${t} was not "ipfs"`);return{namespace:"ipfs",cid:F.parse(n),path:o.length>0?`/${o.join("/")}`:"",answer:e}};var ID=(r,e)=>{let[,t,n,...o]=r.split("/");if(t!=="ipns")throw new Tu(`Namespace ${t} was not "ipns"`);try{return{namespace:"ipns",peerId:Ee(n),path:o.length>0?`/${o.join("/")}`:"",answer:e}}catch{return{namespace:"dnslink",value:n,path:o.length>0?`/${o.join("/")}`:"",answer:e}}};var Ay=class{dns;log;namespaces;cache;cacheMaxAnswers;constructor(e,t={}){this.dns=e.dns,this.log=e.logger.forComponent("helia:dnslink"),this.namespaces={ipfs:CD,ipns:ID,...t.namespaces},this.cache=new Xs({maxSize:t.cacheSize??1e3,maxAge:t.cacheMaxAge??3e4}),this.cacheMaxAnswers=t.cacheMaxAnswers??10}async resolve(e,t={}){if(t.nocache!==!0){let s=this.cache.get(e);if(s!=null){let a=[...s.values()];if(a.length>0)return a}}let n=await this.recursiveResolveDomain(e,t.maxRecursiveDepth??qT,t),o=new Xs({maxSize:this.cacheMaxAnswers});n.forEach((s,a)=>{o.set(a,s,{maxAge:s.answer.TTL*1e3})});let i=n.reduce((s,a)=>{let c=a.answer.TTL*1e3;return c>s?c:s},0);return this.cache.maxAge<i&&(i=this.cache.maxAge),this.cache.set(e,o,{maxAge:i}),n}async recursiveResolveDomain(e,t,n={}){if(t===0)throw new Error("recursion limit exceeded");e.startsWith("_dnslink.")||(e=`_dnslink.${e}`);try{return await this.recursiveResolveDnslink(e,t,n)}catch(o){if(o.code!=="ENOTFOUND"&&o.code!=="ENODATA"&&o.name!=="DNSLinkNotFoundError"&&o.name!=="NotFoundError")throw o;return e.startsWith("_dnslink.")?e=e.replace("_dnslink.",""):e=`_dnslink.${e}`,this.recursiveResolveDnslink(e,t,n)}}async recursiveResolveDnslink(e,t,n={}){if(t===0)throw new Error("recursion limit exceeded");this.log("query %s for TXT and CNAME records",e);let i=((await this.dns.query(e,{...n,types:[yr.TXT]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));this.log("found %d TXT records for %s",i.length,e);let s=[];for(let l of i)try{let u=l.data;if(u.startsWith('"')&&u.endsWith('"')&&(u=u.substring(1,u.length-1)),!u.startsWith("dnslink="))continue;this.log("%s TXT %s",l.name,u),u=u.replace("dnslink=","");let[,d,f]=u.split("/");if(d==="dnslink"){s.push(...await this.recursiveResolveDomain(f,t-1,n));continue}let h=this.namespaces[d];if(h==null){this.log('unknown protocol "%s" in DNSLink record for domain: %s',d,e);continue}let p=h(u,l);if(p.namespace==="dnslink"){s.push(...await this.recursiveResolveDomain(p.value,t-1,n));continue}s.push(h(u,l))}catch(u){this.log.error("could not parse DNS link record for domain %s, %s - %e",e,l.data,u)}if(s.length>0)return s;this.log("no DNSLink records found for %s, falling back to CNAME",e);let c=((await this.dns.query(e,{...n,types:[yr.CNAME]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));this.log("found %d CNAME records for %s",c.length,e);for(let l of c)try{return await this.recursiveResolveDomain(l.data,t-1,n)}catch(u){this.log.error("domain %s cname %s had no DNSLink records - %e",e,l.data,u)}throw new Sy(`No DNSLink records found for domain: ${e}`)}};function kD(r,e={}){return new Ay(r,e)}var RD=BigInt(6e4)*5000000n;var Ty=class extends Error{static name="RecordsFailedValidationError";constructor(e="Records failed validation"){super(e),this.name="RecordsFailedValidationError"}},_y=class extends Error{static name="UnsupportedMultibasePrefixError";constructor(e="Unsupported multibase prefix"){super(e),this.name="UnsupportedMultibasePrefixError"}},Cy=class extends Error{static name="UnsupportedMultihashCodecError";constructor(e="Unsupported multihash codec"){super(e),this.name="UnsupportedMultihashCodecError"}},Iy=class extends Error{static name="InvalidValueError";constructor(e="Invalid value"){super(e),this.name="InvalidValueError"}};var Kh=class extends Error{static name="RecordNotFoundError";name="RecordNotFoundError"};var rX=114,o9=0,i9=18;function s9(r,e){return r.code===e}var ky="/dht/record/",nX="/ipns/metadata/";function zh(r){return new He(ky+de(r,"base32"),!1)}function Ry(r){return new He(nX+de(r,"base32"),!1)}function oX(r){return r?.asCID===r}function PD(r){if(!oX(r))return!1;if(r.code!==rX)throw new E(`CID codec ${r.code} was not libp2p-key`);if(r.multihash.code!==o9&&r.multihash.code!==i9)throw new E(`Multihash algorithm codec ${r.multihash.code} was not Identity or SHA256 hash`);return!0}var DD={[_r.prefix]:_r,[Ce.prefix]:Ce},Py=class{routers;localStore;log;constructor(e,t){this.log=e.logger.forComponent("helia:ipns"),this.localStore=t.localStore,this.routers=t.routers}async resolve(e,t={}){let n=Pp(e)||pt(e)?e.toMultihash():PD(e)?e.multihash:e,o=ic(n),i=await this.#t(o,t);return{...await this.#e(i.value,t),record:i}}async#e(e,t={}){let n=e.split("/");try{let o=n[1];if(o==="ipns"){let i=n[2],s=i.substring(0,1),a;if(s==="1"||s==="Q")a=Ce.decode(`z${i}`);else if(DD[s]!=null)a=DD[s].decode(i);else throw new _y(`Unsupported multibase prefix "${s}"`);let c;try{c=xe(a)}catch{c=F.decode(a).multihash}if(!s9(c,o9)&&!s9(c,i9))throw new Cy(`Unsupported multihash codec "${c.code}"`);let{cid:l}=await this.resolve(c,t),u=n.slice(3).join("/");return{cid:l,path:u===""?void 0:u}}else if(o==="ipfs"){let i=F.parse(n[2]),s=n.slice(3).join("/");return{cid:i,path:s===""?void 0:s}}}catch(o){this.log.error("error parsing ipfs path - %e",o)}throw this.log.error("invalid ipfs path %s",e),new Iy("Invalid value")}async#t(e,t={}){let n=[];if(await this.localStore.has(e,t))if(this.log("record is present in the cache"),t.nocache!==!0)try{let{record:c,created:l}=await this.localStore.get(e,t);this.log("record retrieved from cache"),await sc(e,c),this.log("record was valid");let u=mn(c),d=Number((u.ttl??RD)/1000000n);if(l.getTime()+d>Date.now())return this.log("record TTL was valid"),u;if(t.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),u;this.log("record TTL has been reached, searching routing for updates"),n.push(c)}catch(c){this.log("cached record was invalid - %e",c),await this.localStore.delete(e,t)}else this.log("ignoring local cache due to nocache=true option");if(t.offline===!0)throw new Kh("Record was not present in the cache or has expired");this.log("did not have record locally");let i=0,s=[];if(await Promise.all(this.routers.map(async c=>{let l;try{l=await c.get(e,{...t,validate:!1})}catch(u){this.log.error("error finding IPNS record using router %s - %e",c.toString(),u),s.push(u);return}try{await sc(e,l),n.push(l)}catch(u){i++,this.log.error("error validating IPNS record from router %s - %e",c.toString(),u)}})),n.length===0)throw i>0?new Ty(`${i>1?`${i} records`:"Record"} found for routing key ${i>1?"were":"was"} invalid`):new Kh("Could not find record for routing key");let a=n[vy(e,n)];return await this.localStore.put(e,a,t),mn(a)}};var Gh;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.keyName!=null&&i.keyName!==""&&(s.uint32(10),s.string(i.keyName)),i.lifetime!=null&&i.lifetime!==0&&(s.uint32(16),s.uint32(i.lifetime)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={keyName:"",lifetime:0},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.keyName=i.string();break}case 2:{c.lifetime=i.uint32();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.keyName`,value:i.string()};break}case 2:{yield{field:`${a}.lifetime`,value:i.uint32()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Gh||(Gh={}));function LD(r,e){return{async put(t,n,o={}){try{let i=zh(t);try{let c=await r.get(i),l=ft.deserialize(c);if(gt(l.value,n))return}catch(c){if(c.name!=="NotFoundError")throw c}let s=new ft(t,n,new Date);o.onProgress?.(new k("ipns:routing:datastore:put"));let a=r.batch();a.put(i,s.serialize()),o.metadata!=null&&a.put(Ry(t),Gh.encode(o.metadata)),await a.commit(o)}catch(i){throw o.onProgress?.(new k("ipns:routing:datastore:error",i)),i}},async get(t,n={}){try{let o=zh(t);n.onProgress?.(new k("ipns:routing:datastore:get"));let i=await r.get(o,n),s=ft.deserialize(i);return{record:s.value,created:s.timeReceived}}catch(o){throw n.onProgress?.(new k("ipns:routing:datastore:error",o)),o}},async has(t,n={}){let o=zh(t);return r.has(o,n)},async delete(t,n){let o=zh(t),i=r.batch();i.delete(o),i.delete(Ry(t)),await i.commit(n)},async*list(t={}){try{t.onProgress?.(new k("ipns:routing:datastore:list"));for await(let{key:n,value:o}of r.query({prefix:ky},t))try{let i=ft.deserialize(o),a=n.toString().substring(ky.length),c=K(a,"base32"),l=Ry(c),u;try{let d=await r.get(l,t);u=Gh.decode(d)}catch(d){e.error("Error deserializing metadata for %s - %e",a,d)}yield{routingKey:c,metadata:u,record:i.value,created:i.timeReceived}}catch(i){e.error("Error deserializing record - %e",i)}}catch(n){throw t.onProgress?.(new k("ipns:routing:datastore:error",n)),n}}}}var a9=class{routing;constructor(e){this.routing=e}async put(e,t,n={}){try{await this.routing.put(e,t,n)}catch(o){throw n.onProgress?.(new k("ipns:routing:helia:error",o)),o}}async get(e,t={}){try{return await this.routing.get(e,t)}catch(n){throw t.onProgress?.(new k("ipns:routing:helia:error",n)),n}}toString(){return"HeliaRouting()"}};function c9(r){return new a9(r)}var l9=class{localStore;constructor(e){this.localStore=e}async put(e,t,n){await this.localStore.put(e,t,n)}async get(e,t){let{record:n}=await this.localStore.get(e,t);return n}toString(){return"LocalStoreRouting()"}};function ND(r){return new l9(r)}function OD(r,e={}){let t=LD(r.datastore,r.logger.forComponent("helia:ipns:local-store")),n=[ND(t),c9(r.routing),...e.routers??[]];return new Py(r,{routers:n,localStore:t})}var BD=42;function iX(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function sX(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=F.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new N(w.tag,BD),new N(w.bytes,t)]}function aX(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function cX(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 lX(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 u9={float64:!0,typeEncoders:{Map:lX,Object:sX,undefined:aX,number:cX}},CUe={...u9,typeEncoders:{...u9.typeEncoders}};function uX(r){let e=r();if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return F.decode(e.subarray(1))}var d9={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[BD]:uX}},IUe={...d9,tags:{...d9.tags}};var f9=r=>Ko(r,u9),h9=r=>Pr(iX(r),d9);var g9=Yt(Dy(),1);var y9=40;function w9(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=g9.default.decode(r);return e.seek(g9.default.decode.bytes),t}function b9(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}var Qs={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},Wh={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Qs.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Qs.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Wh["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=Wh["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:Qs.Int,CarV1HeaderOrV2Pragma:r=>{if(Qs.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=Wh["CarV1HeaderOrV2Pragma > roots (anon)"](r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=Wh.Int(r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},jh={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":Qs.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(Qs.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=jh["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=jh["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:Qs.Int,CarV1HeaderOrV2Pragma:r=>{if(Qs.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=jh["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=jh.Int(s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},x9={toTyped:Wh.CarV1HeaderOrV2Pragma,toRepresentation:jh.CarV1HeaderOrV2Pragma};var VUe=k5();var IX=Yt(Dy(),1);var jUe=[new N(w.map,2),new N(w.string,"version"),new N(w.uint,1),new N(w.string,"roots")],YUe=new N(w.tag,42);async function E9(r,e){let t=w9(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),o=h9(n);if(x9.toTyped(o)===void 0)throw new Error("Invalid CAR header format");if(o.version!==1&&o.version!==2||e!==void 0&&o.version!==e)throw new Error(`Invalid CAR version: ${o.version}${e!==void 0?` (expected ${e})`:""}`);if(o.version===1){if(!Array.isArray(o.roots))throw new Error("Invalid CAR header format");return o}if(o.roots!==void 0)throw new Error("Invalid CAR header format");let i=b9(await r.exactly(y9,!0));r.seek(i.dataOffset-r.pos);let s=await E9(r,1);return Object.assign(s,i)}function Yh(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let o=r.subarray(e,e+t);return n&&(e+=t),o},seek(t){e+=t},get pos(){return e}}}var v9=Yt(Dy(),1),jD=1;function S9(r){let e=f9({version:jD,roots:r}),t=v9.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function YD(r){return{async setRoots(e){let t=S9(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(v9.default.encode(t.bytes.length+n.length))),await r.write(t.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return jD}}}function Ly(){}function XD(){let r=[],e=null,t=Ly,n=!1,o=null,i=Ly,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=Ly,l()}})),e),a={write(l){r.push(l);let u=s();return i(),u},async end(){n=!0;let l=s();i(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&t(),{done:!1,value:l}):n?(t(),{done:!0,value:void 0}):(o||(o=new Promise(u=>{i=()=>(o=null,i=Ly,u(c.next()))})),o)}};return{writer:a,iterator:c}}var Xh=class r{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let t=F.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:t,bytes:e.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(e){e=DX(e);let{encoder:t,iterator:n}=QD(),o=new r(e,t),i=new Ny(n);return{writer:o,out:i}}static createAppender(){let{encoder:e,iterator:t}=QD();e.setRoots=()=>Promise.resolve();let n=new r([],e),o=new Ny(t);return{writer:n,out:o}}static async updateRootsInBytes(e,t){let n=Yh(e);await E9(n);let o=S9(t);if(Number(n.pos)!==o.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${o.length} bytes)`);return e.set(o,0),e}},Ny=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function QD(){let r=XD(),{writer:e,iterator:t}=r;return{encoder:YD(e),iterator:t}}function DX(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=F.asCID(r);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}let e=[];for(let t of r){let n=F.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var _u=class{walker;constructor(e){this.walker=e?.walker}async*export(e,t,n,o){let i,s={blockstore:t,getCodec:n};this.walker!=null?i=this.walker(s):i=d0()(s);for await(let a of i.walk(e,o))yield a.block}};var Oy=class{components;log;constructor(e){this.components=e,this.log=e.logger.forComponent("helia:car")}async import(e,t){await pr(this.components.blockstore.putMany(Ct(e.blocks(),({cid:n,bytes:o})=>({cid:n,bytes:o})),t))}async*export(e,t){let n=Array.isArray(e)?e:[e],{writer:o,out:i}=Xh.create(n),s=i[Symbol.asyncIterator](),a=new AbortController;for(this._export(n,o,t).catch(c=>{this.log.error("error during streaming export - %e",c),a.abort(c)});;){let{done:c,value:l}=await Me(s.next(),a.signal);if(a.signal.aborted)throw a.signal.reason;if(l!=null&&(yield l),c===!0)break}}async _export(e,t,n){let o=n?.traversal;for(let i of e){if(i.multihash.code===0)continue;let s=n?.exporter??(i.code===112?new Cu:new _u),a=i,c=!1;if(o!=null){for await(let{cid:l,bytes:u}of o.traverse(a,this.components.blockstore,this.components.getCodec,n))if(this.log.trace("next CID on path to %c is %c",i,l),a=l,i.equals(l)&&(c=!0),c||n?.includeTraversalBlocks===!0){if(n?.blockFilter?.has(l.multihash.bytes)===!0)continue;n?.blockFilter?.add(l.multihash.bytes),await t.put({cid:l,bytes:u})}}for await(let{cid:l,bytes:u}of s.export(a,this.components.blockstore,this.components.getCodec,n))n?.blockFilter?.has(l.multihash.bytes)!==!0&&l.multihash.code!==0&&(c&&l.equals(a)||(n?.blockFilter?.add(l.multihash.bytes),await t.put({cid:l,bytes:u})))}await t.close()}};var Qh=class{async*export(e,t,n,o){let i=await ue(t.get(e,o));yield Ss({cid:e,bytes:i,codec:await n(e.code)})}};var Zh=class r extends Error{static name="InvalidTypeError";static code="ERR_INVALID_TYPE";name=r.name;code=r.code;constructor(e="Invalid type"){super(e)}};var _o;(function(r){let e;(function(a){a.Raw="Raw",a.Directory="Directory",a.File="File",a.Metadata="Metadata",a.Symlink="Symlink",a.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(a){a[a.Raw=0]="Raw",a[a.Directory=1]="Directory",a[a.File=2]="File",a[a.Metadata=3]="Metadata",a[a.Symlink=4]="Symlink",a[a.HAMTShard=5]="HAMTShard"})(t||(t={})),(function(a){a.codec=()=>Ye(t)})(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=re((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.Type!=null&&(c.uint32(8),r.DataType.codec().encode(a.Type,c)),a.Data!=null&&(c.uint32(18),c.bytes(a.Data)),a.filesize!=null&&(c.uint32(24),c.uint64(a.filesize)),a.blocksizes!=null&&a.blocksizes.length>0)for(let u of a.blocksizes)c.uint32(32),c.uint64(u);a.hashType!=null&&(c.uint32(40),c.uint64(a.hashType)),a.fanout!=null&&(c.uint32(48),c.uint64(a.fanout)),a.mode!=null&&(c.uint32(56),c.uint32(a.mode)),a.mtime!=null&&(c.uint32(66),Jh.codec().encode(a.mtime,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={blocksizes:[]},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let f=a.uint32();switch(f>>>3){case 1:{u.Type=r.DataType.codec().decode(a);break}case 2:{u.Data=a.bytes();break}case 3:{u.filesize=a.uint64();break}case 4:{if(l.limits?.blocksizes!=null&&u.blocksizes.length===l.limits.blocksizes)throw new le('Decode error - repeated field "blocksizes" had too many elements');u.blocksizes.push(a.uint64());break}case 5:{u.hashType=a.uint64();break}case 6:{u.fanout=a.uint64();break}case 7:{u.mode=a.uint32();break}case 8:{u.mtime=Jh.codec().decode(a,a.uint32(),{limits:l.limits?.mtime});break}default:{a.skipType(f&7);break}}}return u},function*(a,c,l,u={}){let d={blocksizes:0},f=c==null?a.len:a.pos+c;for(;a.pos<f;){let h=a.uint32();switch(h>>>3){case 1:{yield{field:`${l}.Type`,value:r.DataType.codec().decode(a)};break}case 2:{yield{field:`${l}.Data`,value:a.bytes()};break}case 3:{yield{field:`${l}.filesize`,value:a.uint64()};break}case 4:{if(u.limits?.blocksizes!=null&&d.blocksizes===u.limits.blocksizes)throw new le('Streaming decode error - repeated field "blocksizes" had too many elements');yield{field:`${l}.blocksizes[]`,index:d.blocksizes,value:a.uint64()},d.blocksizes++;break}case 5:{yield{field:`${l}.hashType`,value:a.uint64()};break}case 6:{yield{field:`${l}.fanout`,value:a.uint64()};break}case 7:{yield{field:`${l}.mode`,value:a.uint32()};break}case 8:{yield*Jh.codec().stream(a,a.uint32(),`${l}.mtime`,{limits:u.limits?.mtime});break}default:{a.skipType(h&7);break}}}})),n);function o(a){return ee(a,r.codec())}r.encode=o;function i(a,c){return J(a,r.codec(),c)}r.decode=i;function s(a,c){return te(a,r.codec(),c)}r.stream=s})(_o||(_o={}));var Jh;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Seconds!=null&&(s.uint32(8),s.int64(i.Seconds)),i.FractionalNanoseconds!=null&&(s.uint32(21),s.fixed32(i.FractionalNanoseconds)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.Seconds=i.int64();break}case 2:{c.FractionalNanoseconds=i.fixed32();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Seconds`,value:i.int64()};break}case 2:{yield{field:`${a}.FractionalNanoseconds`,value:i.fixed32()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(Jh||(Jh={}));var JD;(function(r){let e;r.codec=()=>(e==null&&(e=re((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.MimeType!=null&&(s.uint32(10),s.string(i.MimeType)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();u>>>3===1?c.MimeType=i.string():i.skipType(u&7)}return c},function*(i,s,a,c={}){let l=s==null?i.len:i.pos+s;for(;i.pos<l;){let u=i.uint32();u>>>3===1?yield{field:`${a}.MimeType`,value:i.string()}:i.skipType(u&7)}})),e);function t(i){return ee(i,r.codec())}r.encode=t;function n(i,s){return J(i,r.codec(),s)}r.decode=n;function o(i,s){return te(i,r.codec(),s)}r.stream=o})(JD||(JD={}));var eL={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},NX=["directory","hamt-sharded-directory"],tL=parseInt("0644",8),rL=parseInt("0755",8),Er=class r{static unmarshal(e){let t=_o.decode(e),n=new r({type:eL[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:t,data:n,blockSizes:o,hashType:i,fanout:s,mtime:a,mode:c}=e;if(t!=null&&!Object.values(eL).includes(t))throw new Zh("Type: "+t+" is not valid");this.type=t??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?rL:tL:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return NX.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=_o.DataType.Raw;break;case"directory":e=_o.DataType.Directory;break;case"file":e=_o.DataType.File;break;case"metadata":e=_o.DataType.Metadata;break;case"symlink":e=_o.DataType.Symlink;break;case"hamt-sharded-directory":e=_o.DataType.HAMTShard;break;default:throw new Zh(`Type: ${e} is not valid`)}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===tL&&!this.isDirectory()&&(n=void 0),n===rL&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),_o.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var ep=class extends Error{static code="ERR_NOT_UNIXFS";static message="Not a UnixFS node";static name="NotUnixFSError";code="ERR_NOT_UNIXFS";message="Not a UnixFS node";name="NotUnixFSError"},By=class extends Error{static name="NotDescendantError";name="NotDescendantError"},My=class extends Error{static name="InvalidTraversalError";name="InvalidTraversalError"};function BX(r){return r.cid.code===85}function MX(r){return r.cid.code===112}function FX(r){if(BX(r))return!0;if(MX(r)&&r.value.Data!=null){let e=Er.unmarshal(r.value.Data);return e.type==="file"||e.type==="raw"}else throw new ep("Encountered non raw/dag-pb CID in UnixFS DAG")}var Cu=class{options;constructor(e){this.options=e}async*export(e,t,n,o){if(e.code!==112&&e.code!==85)throw new ep("Target CID was not UnixFS - use the SubGraphExporter to export arbitrary graphs");let i=Wl()({blockstore:t,getCodec:n}),s=this.options?.offset??0,a=this.options?.length??1/0,c=this.options?.listingOnly??!1;if(s<0)throw new E("Offset cannot be negative");if(a<0)throw new E("Length cannot be negative");let l,u=new AbortController,d=ae([u.signal,o?.signal]);u.signal;function f(h,p){if(l==null&&(l=FX(p)),!l){let D=p.value.Links.find(U=>U.Hash.equals(h)),O=Er.unmarshal(p.value.Data??new Uint8Array);return O.type==="directory"?!c:O.type==="hamt-sharded-directory"&&c?D?.Name?.length===2:!0}let y=p.value.Links.findIndex(D=>D.Hash.equals(h)),g=Er.unmarshal(p.value.Data??new Uint8Array),m=s,b=m+a,T=Number([...g.blockSizes].slice(0,y).reduce((D,O)=>D+O,0n)),R=T+Number(g.blockSizes[y]);return m>=T&&m<R||b>=T&&b<R||m<=T&&b>=R}try{for await(let h of i.walk(e,{...o,includeChild:f,signal:d}))yield h.block}finally{u.abort(),d.clear()}}};var Fy=class{path;constructor(e){this.path=e}async*traverse(e,t,n,o){if(!this.path.some(s=>s.equals(e)))throw new My(`CIDPath traversal must include ${e}`);let i;for(let s of this.path){if(i!=null){let l=!1;for(let[,u]of i.links())if(u.equals(s)){l=!0;break}if(!l)throw new By(`${s} is not a child of ${i.cid}`)}let a=await ue(t.get(s,o)),c=Ss({cid:s,bytes:a,codec:await n(s.code)});i=c,yield c}}};var Iu=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(e="Bad path"){super(e)}},xn=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not found"){super(e)}},ku=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(e="No resolver"){super(e)}},st=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(e="Not UnixFS"){super(e)}},Uy=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(e="Over read"){super(e)}},$y=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(e="Under read"){super(e)}},Gn=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};function Ru(r){return r==null?!1:F.asCID(r)===r}function Pu(r,e){let t,n=0,o="";for(;n<e.length;){let i=e[n];if(n++,!Object.hasOwnProperty.call(r,i))throw new Iu(`Object did not have key "${i}"`);if(o+=`/${i}`,t=r[i],r=t,Ru(t))break}return{value:t,rest:e.slice(n),path:o.substring(1)}}async function*A9(r,e,t,n){let o=await ue(t.get(r,n)),i=As(o),s=Pu(i,e);yield{cid:Ru(s.value)?s.value:r,name:s.path,rest:s.rest}}async function*nL(r,e,t,n){let o=await ue(t.get(r,n)),i=ql(o),s=Pu(i,e);yield{cid:Ru(s.value)?s.value:r,name:s.path,rest:s.rest}}function Zs(r,e){let t=r.lo+e.lo>>>0,n=r.hi+e.hi+(t<r.lo?1:0)>>>0;return{lo:t,hi:n}}function UX(r,e){return r+e>>>0}function Wn(r,e){let t=r.lo&65535,n=r.lo>>>16,o=e.lo&65535,i=e.lo>>>16,s=t*o,a=t*i,c=n*o,l=n*i,u=(s>>>16)+(a&65535)+(c&65535)>>>0,d=(u<<16|s&65535)>>>0,f=l+(a>>>16)+(c>>>16)+(u>>>16),h=Math.imul(r.lo,e.hi),p=Math.imul(r.hi,e.lo),y=f+h+p>>>0;return{lo:d,hi:y}}function Ac(r,e){return Math.imul(r,e)>>>0}function Du(r,e){if(e===0)return r;if(e===32)return{lo:r.hi,hi:r.lo};if(e<32){let o=(r.lo<<e|r.hi>>>32-e)>>>0,i=(r.hi<<e|r.lo>>>32-e)>>>0;return{lo:o,hi:i}}e-=32;let t=(r.hi<<e|r.lo>>>32-e)>>>0,n=(r.lo<<e|r.hi>>>32-e)>>>0;return{lo:t,hi:n}}function at(r,e){return{lo:(r.lo^e.lo)>>>0,hi:(r.hi^e.hi)>>>0}}function T9(r,e){if(e===0)return r;if(e<32){let t=(r.lo>>>e|r.hi<<32-e)>>>0,n=r.hi>>>e;return{lo:t,hi:n}}return{lo:r.hi>>>e-32,hi:0}}function je(r,e){return{lo:r>>>0,hi:e>>>0}}function _9(r,e){return(r<<e|r>>>32-e)>>>0}function oL(r,e){let t=e*8,n=r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24,o=r[t+4]|r[t+5]<<8|r[t+6]<<16|r[t+7]<<24;return{lo:n>>>0,hi:o>>>0}}function $X(r,e){let t=e*4;return(r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24)>>>0}function iL(r){return r=at(r,T9(r,33)),r=Wn(r,je(3981806797,4283543511)),r=at(r,T9(r,33)),r=Wn(r,je(444984403,3301882366)),r=at(r,T9(r,33)),r}function HX(r){return r^=r>>>16,r=Ac(r,2246822507),r^=r>>>13,r=Ac(r,3266489909),r^=r>>>16,r}function C9(r,e=0){let t=je(e,0),n=je(e,0),o=r.length,i=Math.floor(o/16),s=je(289559509,2277735313),a=je(658871167,1291169091);for(let f=0;f<i;f++){let h=oL(r,f*2),p=oL(r,f*2+1);h=Wn(h,s),h=Du(h,31),h=Wn(h,a),t=at(t,h),t=Du(t,27),t=Zs(t,n),t=Zs(Wn(t,je(5,0)),je(1390208809,0)),p=Wn(p,a),p=Du(p,33),p=Wn(p,s),n=at(n,p),n=Du(n,31),n=Zs(n,t),n=Zs(Wn(n,je(5,0)),je(944331445,0))}let c=je(0,0),l=je(0,0),u=r.slice(i*16);switch(u.length){case 15:l=at(l,je(0,u[14]<<16));case 14:l=at(l,je(0,u[13]<<8));case 13:l=at(l,je(0,u[12]));case 12:l=at(l,je(u[11]<<24,0));case 11:l=at(l,je(u[10]<<16,0));case 10:l=at(l,je(u[9]<<8,0));case 9:l=at(l,je(u[8],0)),l=Wn(l,a),l=Du(l,33),l=Wn(l,s),n=at(n,l);case 8:c=at(c,je(0,u[7]<<24));case 7:c=at(c,je(0,u[6]<<16));case 6:c=at(c,je(0,u[5]<<8));case 5:c=at(c,je(0,u[4]));case 4:c=at(c,je(u[3]<<24,0));case 3:c=at(c,je(u[2]<<16,0));case 2:c=at(c,je(u[1]<<8,0));case 1:c=at(c,je(u[0],0)),c=Wn(c,s),c=Du(c,31),c=Wn(c,a),t=at(t,c)}let d=je(o,0);return t=at(t,d),n=at(n,d),t=Zs(t,n),n=Zs(n,t),t=iL(t),n=iL(n),t=Zs(t,n),n=Zs(n,t),new Uint8Array([t.hi>>>24&255,t.hi>>>16&255,t.hi>>>8&255,t.hi&255,t.lo>>>24&255,t.lo>>>16&255,t.lo>>>8&255,t.lo&255,n.hi>>>24&255,n.hi>>>16&255,n.hi>>>8&255,n.hi&255,n.lo>>>24&255,n.lo>>>16&255,n.lo>>>8&255,n.lo&255])}function sL(r,e=0){let t=e>>>0,n=r.length,o=Math.floor(n/4),i=3432918353,s=461845907;for(let l=0;l<o;l++){let u=$X(r,l);u=Ac(u,i),u=_9(u,15),u=Ac(u,s),t^=u,t=_9(t,13),t=UX(Ac(t,5),3864292196)}let a=r.slice(o*4),c=0;switch(a.length){case 3:c^=a[2]<<16;case 2:c^=a[1]<<8;case 1:c^=a[0],c=Ac(c,i),c=_9(c,15),c=Ac(c,s),t^=c}return t^=n,t=HX(t),t}function VX(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var THe=li({name:"murmur3-32",code:35,encode:r=>VX(sL(r))}),aL=li({name:"murmur3-128",code:34,encode:r=>C9(r)}),_He=li({name:"murmur3-x64-64",code:34,encode:r=>C9(r).subarray(0,8)});var mL=Yt(uL(),1);function Hy(r=0){return new Uint8Array(r)}function fL(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var dL=fL("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),I9=fL("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=Hy(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),WX={utf8:dL,"utf-8":dL,hex:oe.base16,latin1:I9,ascii:I9,binary:I9,...oe},hL=WX;function pL(r,e="utf8"){let t=hL[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Tc=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new mL.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof r?o.push(i.serialize(e,t)):o.push(e(i,s))),o),n))}async asyncTransform(e,t){return gL(this,e,t)}toJSON(){return this.serialize(YX,XX)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?pL(e):e),n=await t.take(this._options.bits),o=this._children.get(n);return o instanceof r?o._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:o}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let o=await n._findPlace(t.existingChild.hash);return o.bucket._putAt(o,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(jX);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function jX(r){return!!r}function YX(r,e){return r.key}function XX(r){return r}async function gL(r,e,t){let n=[];for(let o of r._children.compactArray())if(o instanceof Tc)await gL(o,e,t);else{let i=await e(o);n.push({bitField:r._children.bitField(),children:i})}return t(n)}function QX(r){return r?.buffer instanceof ArrayBuffer}function yL(r){if(QX(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function wL(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=Hy(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return yL(t)}var ZX=[255,254,252,248,240,224,192,128],JX=[1,3,7,15,31,63,127,255],qy=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,t),a=eQ(o,i-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function eQ(r,e,t){let n=tQ(e,t);return(r&n)>>>e}function tQ(r,e){return ZX[r]&JX[Math.min(e+r-1,7)]}function bL(r){function e(t){return t instanceof Vy?t:new Vy(t,r)}return e}var Vy=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),t),s=o.take(i);n=(n<<i)+s,t-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),t);n.untake(o),t-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?wL([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new qy(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function xL(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:bL(r.hashFn)};return new Tc(e)}var rQ=async function(r){return(await aL.encode(r)).slice(0,8).reverse()},nQ=async(r,e,t)=>{let n=(e.tableSize()-1).toString(16).length;await Promise.all(r.map(async o=>{if(o.Name==null)throw new Error("Unexpected Link without a Name");if(o.Name.length===n){let i=parseInt(o.Name,16);e._putObjectAt(i,new Tc({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(o.Name.substring(2),!0)}))},EL=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),oQ=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()};async function*k9(r,e,t,n,o,i){if(o==null){if(r.Data==null)throw new st("No data in PBNode");let f;try{f=Er.unmarshal(r.Data)}catch(p){throw new st(p.message)}if(f.type!=="hamt-sharded-directory")throw new st("Not a HAMT");if(f.fanout==null)throw new st("Missing fanout");let h=xL({hashFn:rQ,bits:Math.log2(Number(f.fanout))});o={rootBucket:h,hamtDepth:1,lastBucket:h}}let s=(o.lastBucket.tableSize()-1).toString(16).length;await nQ(r.Links,o.lastBucket,o.rootBucket);let a=await o.rootBucket._findNewBucketAndPos(e),c=EL(a.pos,s),l=oQ(a);l.length>o.hamtDepth&&(o.lastBucket=l[o.hamtDepth],c=EL(o.lastBucket._posAtParent,s));let u=r.Links.find(f=>{if(f.Name==null)return!1;let h=f.Name.substring(0,s),p=f.Name.substring(s);return!(h!==c||p!==""&&p!==e)});if(u==null)return;if(u.Name!=null&&u.Name.substring(s)===e){yield{cid:u.Hash,name:u.Name.substring(s),rest:t};return}o.hamtDepth++;let d=await ue(n.get(u.Hash,i));r=hn(d),i?.yieldSubShards===!0&&(yield{cid:u.Hash,name:u.Name??"",rest:[e,...t]}),yield*k9(r,e,t,n,o,i)}async function*vL(r,e,t,n){let o=await ue(t.get(r,n)),i;try{i=hn(o)}catch(a){throw new st(a.message)}if(i.Data==null)throw new st("no data in PBNode");let s;try{s=Er.unmarshal(i.Data)}catch(a){throw new st(a.message)}if(s.type==="directory"||s.type==="hamt-sharded-directory"&&n?.translateHAMTPath===!1){let a=i.Links.find(c=>c.Name===e[0]);if(a==null)throw new xn(`No link "${e[0]}" found under ${r}`);yield{cid:a.Hash,name:e[0],rest:e.slice(1)}}else if(s.type==="hamt-sharded-directory"){let a=!1;for await(let c of k9(i,e[0],e.slice(1),t,void 0,n))c.name===e[0]&&(a=!0),yield c;if(!a)throw new xn(`No link "${e[0]}" found under ${r}`)}}async function*SL(r,e,t,n){if(e.length!==0)throw new Iu(`Cannot load path /${e.join("/")} from identity block`)}async function*AL(r,e,t,n){let o=await ue(t.get(r,n)),i=ua(o),s=Pu(i,e);yield{cid:r,name:s.path,rest:s.rest}}async function*TL(r,e,t,n){if(e.length!==0)throw new xn(`Cannot load path /${e.join("/")} from raw block`)}var sQ={[We]:vL,[Ie]:TL,[tr]:A9,81:A9,[rr]:nL,[Ke.code]:SL,[ar]:AL};async function*Js(r,e,t={}){for(r=r.toString(),r.startsWith("/ipfs/")&&(r=r.substring(6));r.endsWith("/");)r=r.substring(0,r.length-1);let[n,...o]=r.split(/(?<!\\)\//g).filter(Boolean),i=F.parse(n),s=[i],a=`${i}`;for(yield{cid:i,name:a,path:a,roots:s,remainder:o};o.length>0;){let c=sQ[i.code];if(c==null)throw new ku(`No resolver for code ${i.code}`);let l=!1;for await(let u of c(i,o,e,t)){if(i=u.cid,l=!s[s.length-1].equals(i),o=u.rest,!l)break;s=[...s,u.cid],a=`${a}/${u.name}`,yield{cid:u.cid,name:u.name,path:a,roots:s,remainder:u.rest}}if(!l)break}if(t?.signal?.throwIfAborted(),o.length!==0)throw new xn(`Could not resolve path /${o.join("/")} under ${r}`)}function aQ(r){return r[Symbol.asyncIterator]!=null}function cQ(r){if(aQ(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var Lu=cQ;async function R9(r,e,t,n,o){let i=await ue(n.get(r,o)),s=As(i);return{type:"object",cid:r,name:e,path:t,object:s,node:i}}async function _L(r,e,t,n,o){let i=await ue(n.get(r,o)),s=ql(i);return{type:"object",cid:r,name:e,path:t,object:s,node:i}}function tp(r,e,t,n){let o=BigInt(r.length),i=BigInt(e+o);return t>=i||n<e?new Uint8Array(0):(n>=e&&n<i&&(r=r.subarray(0,Number(n-e))),t>=e&&t<i&&(r=r.subarray(Number(t-e))),r)}var Ky=(r,e=0,t=r)=>{let n=BigInt(r),o=BigInt(e??0),i=BigInt(t);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw new Gn("Offset must be greater than or equal to 0");if(o>n)throw new Gn("Offset must be less than the file size");if(i<0n)throw new Gn("Length must be greater than or equal to 0");if(i>n)throw new Gn("Length must be less than the file size");return{start:o,end:i}};function zy(r,e){async function*t(n={}){let{start:o,end:i}=Ky(r.length,n.offset,n.length),s=tp(r,0n,o,i);n.onProgress?.(new k(e,{bytesRead:BigInt(s.byteLength),totalBytes:i-o,fileSize:BigInt(r.byteLength)})),yield s}return t}async function CL(r,e,t,n,o){let i=xe(r.multihash.bytes);return{type:"identity",cid:r,name:e,path:t,content:zy(i.digest,"unixfs:exporter:progress:identity"),size:BigInt(i.bytes.length),node:i.bytes}}async function IL(r,e,t,n,o){let i=await ue(n.get(r,o)),s=ua(i);return{type:"object",cid:r,name:e,path:t,object:s,node:i}}async function kL(r,e,t,n,o){let i=await ue(n.get(r,o));return{type:"raw",cid:r,name:e,path:t,content:zy(i,"unixfs:exporter:progress:raw"),size:BigInt(i.length),node:i}}function RL(r,e,t,n){async function*o(i={}){let s=i.offset??0,a=i.length??e.Links.length,c=e.Links.slice(s,a);i.onProgress?.(new k("unixfs:exporter:walk:directory",{cid:r})),yield*c.map(l=>({cid:l.Hash,name:l.Name??"",path:`${n}/${l.Name??""}`}))}return o}async function PL(r,e,t,n,o,i,s){if(e instanceof Uint8Array){let l=tp(e,n,o,i);t.push(l);return}if(e.Data==null)throw new st("no data in PBNode");let a;try{a=Er.unmarshal(e.Data)}catch(l){throw new st(l.message)}if(a.data!=null){let l=a.data,u=tp(l,n,o,i);t.push(u),n+=BigInt(u.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw new st("Inconsistent block sizes and dag links");for(let l=0;l<e.Links.length;l++){let u=e.Links[l],d=n,f=d+a.blockSizes[l];if((o>=d&&o<f||i>=d&&i<=f||o<d&&i>f)&&c.push({link:u,blockStart:n}),n=f,n>i)break}await on(c,l=>Ct(l,u=>async()=>{let d=await ue(r.get(u.link.Hash,s));return{...u,block:d}}),l=>yn(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:u,block:d,blockStart:f}of l){let h;switch(u.Hash.code){case We:h=hn(d);break;case Ie:h=d;break;default:t.end(new st(`Unsupported codec: ${u.Hash.code}`));return}let p=new _i({concurrency:1});p.on("error",y=>{t.end(y)}),p.add(async()=>{s.onProgress?.(new k("unixfs:exporter:walk:file",{cid:u.Hash})),await PL(r,h,t,f,o,i,s)}),await p.onIdle()}}),n>=i&&t.end()}function P9(r,e,t,n,o){async function*i(s={}){let a=t.fileSize();if(a===void 0)throw new Error("File was a directory");let{start:c,end:l}=Ky(a,s.offset,s.length);if(l===0n)return;let u=0n,d=l-c,f=Nt();s.onProgress?.(new k("unixfs:exporter:walk:file",{cid:r})),PL(o,e,f,0n,c,l,s).catch(h=>{f.end(h)});for await(let h of f)if(h!=null){if(u+=BigInt(h.byteLength),u>d)throw f.end(),new Uy("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");u===d&&f.end(),s.onProgress?.(new k("unixfs:exporter:progress:unixfs:file",{bytesRead:u,totalBytes:d,fileSize:a})),yield h}if(u<d)throw new $y("Traversed entire DAG but did not read enough bytes")}return i}async function*DL(r,e,t,n){let o=r.Links;if(r.Data==null)throw new st("no data in PBNode");let i;try{i=Er.unmarshal(r.Data)}catch(c){throw new st(c.message)}if(i.fanout==null)throw new st("missing fanout");let s=(i.fanout-1n).toString(16).length,a=on(o,c=>Ct(c,l=>async()=>{let u=l.Name!=null?l.Name.substring(s):null;if(u!=null&&u!=="")return{entries:[{cid:l.Hash,name:u,path:`${e}/${u}`}]};{let d=await ue(t.get(l.Hash,n));return r=hn(d),n.onProgress?.(new k("unixfs:exporter:walk:hamt-sharded-directory",{cid:l.Hash})),{entries:DL(r,e,t,n)}}}),c=>yn(c,{ordered:!0,concurrency:n.blockReadConcurrency}));for await(let{entries:c}of a)yield*c}function LL(r,e,t,n,o){function i(s={}){return s.onProgress?.(new k("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),DL(e,n,o,s)}return i}var lQ={raw:P9,file:P9,directory:RL,"hamt-sharded-directory":LL,metadata:(r,e,t,n)=>()=>[],symlink:(r,e,t,n)=>()=>[]};async function NL(r,e,t,n,o){let i=await ue(n.get(r,o)),s;try{s=hn(i)}catch(l){throw new st(l.message)}if(s.Data==null)throw new st("no data in PBNode");let a;try{a=Er.unmarshal(s.Data)}catch(l){throw new st(l.message)}let c=lQ[a.type](r,s,a,t,n);if(c==null)throw new xn("could not find content exporter");return a.isDirectory()?{type:"directory",cid:r,name:e,path:t,entries:c,unixfs:a,node:s}:{type:"file",cid:r,name:e,path:t,content:c,unixfs:a,node:s,size:a.fileSize()}}var uQ={[We]:NL,[Ie]:kL,[tr]:R9,81:R9,[rr]:_L,[Ke.code]:CL,[ar]:IL};async function jn(r,e,t={}){let n,o;if(r instanceof String||typeof r=="string"){let s=await Lu(Js(r,e,t));if(s==null)throw new xn(`Could not walk path to ${r}`);n=s.cid,o=s.name,r=s.path}else if(F.asCID(r)===r||r instanceof F)n=r,o=r=n.toString();else throw new Gn("Path must be string or CID");let i=uQ[n.code];if(i==null)throw new ku(`No resolver for code ${n.code}`);return i(n,o,r,e,t)}async function*OL(r,e,t={}){let n=await jn(r,e,t);if(n==null)return;if(yield{cid:n.cid,name:n.name,path:n.path,depth:0},n.type==="directory")for await(let i of o(n,0,`${r}`,t))yield i;async function*o(i,s,a,c){s++;for await(let l of i.entries(c)){let u=`${a}/${l.name}`;yield{...l,depth:s,path:u};let d=await jn(l.cid,e,c);d.type==="directory"&&(yield*o(d,s,u,c))}}}function BL(r){return new Oy(r)}var En="application/vnd.ipld.dag-cbor",vn="application/cbor",Sn="application/vnd.ipld.dag-json",An="application/json",sr="application/vnd.ipld.raw",Ft="application/octet-stream",_c="application/vnd.ipfs.ipns-record",Cc="application/vnd.ipld.car",Nu="application/x-tar",np="application/vnd.ipld.dag-pb",Gy={mediaType:Ft,codecs:[Ie,ar,rr,81,tr,We],immutable:!0,extension:".bin",etag:"",disposition:"attachment"},dQ={mediaType:En,codecs:[tr,Ie,We],immutable:!0,extension:".cbor",etag:".dag-cbor",disposition:"attachment"},fQ={mediaType:vn,codecs:[81,tr,Ie,We],immutable:!0,extension:".cbor",etag:".cbor",disposition:"attachment"},hQ={mediaType:Sn,codecs:[rr,Ie,We],immutable:!0,extension:".json",etag:".dag-json",disposition:"inline"},pQ={mediaType:An,codecs:[ar,rr,Ie,We],immutable:!0,extension:".json",etag:".json",disposition:"inline"},ML={mediaType:sr,codecs:[Ie,ar,rr,81,tr,We],immutable:!0,extension:".raw",etag:".raw",disposition:"attachment"},Ic={mediaType:_c,codecs:[],immutable:!1,extension:".bin",etag:".bin",disposition:"attachment"},D9={mediaType:Cc,codecs:[Ie,ar,rr,81,tr,We],immutable:!1,extension:".car",etag:".car",disposition:"attachment"},mQ={mediaType:Nu,codecs:[Ie,We],immutable:!1,extension:".x-tar",etag:".x-tar",disposition:"attachment"},FL=[dQ,fQ,hQ,pQ,ML,Ic,D9,mQ,Gy];function UL(r){return FL.find(e=>e.mediaType===r)}function op(r){return r==null?[]:FL.filter(e=>e.codecs.includes(r.code)).sort((e,t)=>{let n=e.codecs.indexOf(r.code),o=t.codecs.indexOf(r.code);return n<o?-1:o<n?1:0})}function $L(r="ipfs:",e){let t=op(e);return r==="ipfs:"&&t.length===0&&(t=[ML,Gy]),r==="ipns:"&&t.push(Ic),t}function jr(r){if(r==null)throw new E("Cannot get filename for Content-Disposition header - filename argument was missing");let e=gQ(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function gQ(r){return r.replace(/[^\x00-\x7F]/g,"_")}var Fr=class extends Error{static name="InvalidRangeError";name="InvalidRangeError"},L9=class extends Error{static name="NoContentError";name="NoContentError"},N9=class extends Error{static name="SubdomainNotSupportedError";name="SubdomainNotSupportedError"},ip=class extends Error{static name="RedirectsFileTooLargeError";name="RedirectsFileTooLargeError"},sp=class extends Error{static name="InvalidRedirectsFileError";name="InvalidRedirectsFileError"},ap=class extends Error{static name="InvalidRedirectStatusCodeError";name="InvalidRedirectStatusCodeError"},cp=class extends Error{static name="DuplicatePlaceholderError";name="DuplicatePlaceholderError"};function yQ(r){return typeof r?.serverTiming=="string"&&r?.name==="AbortError"}function HL({offset:r,length:e}){return{offset:Number(r),length:Number(e)}}function O9(r,e,t){if(r=BigInt(r),e!=null){if(e=BigInt(e),e<0n)throw new Fr("Range start cannot be negative");if(e>=r)throw new Fr("Range start cannot be larger than total bytes")}if(t!=null){if(t=BigInt(t),(t>0n?t:-t)>=r)throw new Fr("Range end cannot be larger than total bytes");if(t<0n)if(e==null)e=r+t,t=r-1n;else throw new Fr("Range end cannot be negative");t+=1n}return HL(VL(r,e,t))}function qL(r,e){r=BigInt(r);let t=(e??"0:*").split(":"),n=BigInt(t[0]),o=t[1]==="*"?r:BigInt(t[1]);return HL(VL(r,n,o))}function VL(r,e=0n,t=r){if(e>=0n)return t>=0n?{offset:e,length:t-e}:{offset:e,length:r-e+t};let n=r+e;return Math.abs(Number(e))>Number(r)&&(n=0n),t>=0n?{offset:n,length:t-n}:{offset:n,length:r-n+t}}function wQ(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r?.errors)}function kc(r){let e;return wQ(r)&&(e=r.errors.map(t=>kc(t))),{name:r.name,message:r.message,stack:r.stack,errors:e}}function KL({ttl:r,expires:e,protocol:t,response:n}){let o;if(t==="ipfs:"?o="public, max-age=29030400, immutable":r==null?o="public, max-age=300":o=`public, max-age=${r}`,e!=null){let i=Math.max(0,Math.round((e.getTime()-Date.now())/1e3));o+=`, stale-while-revalidate=${i}, stale-if-error=${i}`,n.headers.has("expires")||n.headers.set("expires",e.toUTCString())}n.headers.has("cache-control")||n.headers.set("cache-control",o)}function B9(r,e,t){e!=null&&(e=BigInt(e)),t!=null&&(t=BigInt(t));let n=BigInt(r);if((t??0n)>=n)throw new Fr("Invalid range: Range-end index is greater than or equal to the size of the file.");if((e??0n)>=n)throw new Fr("Invalid range: Range-start index is greater than or equal to the size of the file.");let o="*";if(e==null)t!=null&&(t<0n?o=`${n+t}-${n-1n}`:o=`0-${t}`);else if(t==null){let i="*";r!=null&&(i=`${n-1n}`),o=`${e}-${i}`}else o=`${e}-${t}`;return`bytes ${o}/${n}`}function M9(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function Tn(r,e){r.type!==e&&M9(r,"type",e)}function _n(r,e){e=e.toString();let t=e.indexOf("#");t>-1&&(e=e.substring(0,t)),r.url!==e&&M9(r,"url",e)}function GL(r){M9(r,"redirected",!0)}function bQ(r){return r.buffer instanceof ArrayBuffer}function zL(r){if(bQ(r))return r;let e=new ArrayBuffer(r.byteLength),t=new Uint8Array(e);return t.set(r),t}function xQ(r){return r==null?!1:typeof r.pipeThrough=="function"&&typeof r.getReader=="function"}function lp(r){return r==null?r:r instanceof Uint8Array?zL(r):xQ(r)?r.pipeThrough(new TransformStream({transform(e,t){t.enqueue(zL(e))}})):r}function Cn(r,e,t){let n=new Response(lp(e),{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&GL(n),Tn(n,"basic"),_n(n,r),n}function F9(r,e,t){let n=new Response(JSON.stringify({error:kc(e)}),{...t??{},status:500,statusText:"Internal Server Error"});return n.headers.set("X-Content-Type-Options","nosniff"),n.headers.set("content-type","application/json"),n.headers.set("x-error-message",btoa(e.message)),Tn(n,"basic"),_n(n,r),n}function Wy(r,e,t){let n=new Response(lp(e),{...t??{},status:504,statusText:"Gateway Timeout"});return Tn(n,"basic"),_n(n,r),n}function Rc(r,e,t){let n=new Response(lp(e),{...t??{},status:502,statusText:"Bad Gateway"});return Tn(n,"basic"),_n(n,r),n}function U9(r,e,t){let n=new Response(lp(e),{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),Tn(n,"basic"),_n(n,r),n}function ea(r,e,t,n){let o=new Headers(n?.headers);o.set("content-type","application/json");let i=new Response(JSON.stringify({requested:e.map(s=>s.mediaType),acceptable:t.map(s=>s.mediaType)}),{...n??{},status:406,statusText:"Not Acceptable",headers:o});return Tn(i,"basic"),_n(i,r),i}function $9(r,e,t){let n=new Response(lp(e),{...t??{},status:404,statusText:"Not Found"});return Tn(n,"basic"),_n(n,r),n}function EQ(r){return Array.isArray(r)&&r.every(e=>e instanceof Error)}function Yr(r,e,t){let n,o;EQ(e)?(n=e[e.length-1].stack,o=e.map(a=>({message:a.message,stack:a.stack??""}))):e instanceof Error&&(n=e.stack,o=[{message:e.message,stack:e.stack??""}]);let i=JSON.stringify({stack:n,errors:o}),s=new Response(i,{status:400,statusText:"Bad Request",...t??{},headers:{...t?.headers??{},"Content-Type":"application/json"}});return Tn(s,"basic"),_n(s,r),s}function WL(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return Tn(n,"basic"),_n(n,r),n}function H9(r,e,t){let n=new Response(null,{...t??{},status:304,statusText:"Not Modified"});return["cache-control","content-location","date","etag","expires","vary"].forEach(i=>{let s=e.get(i);s!=null&&n.headers.set(i,s)}),Tn(n,"basic"),_n(n,r),n}function Ou(r,e,t,n,o){let i;if(t.ranges.length===1)i=vQ(r,e,t.ranges[0],n,o);else if(t.ranges.length>1)i=SQ(r,e,t,n,o);else return jy(r,n);return o?.redirected===!0&&GL(i),Tn(i,"basic"),_n(i,r),i}function vQ(r,e,t,n,o){try{let i=new Headers(o?.headers),{offset:s,length:a}=O9(n,t.start,t.end);i.set("content-length",`${a}`),i.set("content-range",B9(n,t.start,t.end));let c=Kn(e(s,a));return new Response(c,{...o??{},status:206,statusText:"Partial Content",headers:i})}catch(i){return i.name==="InvalidRangeError"?jy(r,n,o):F9(r,i,o)}}function SQ(r,e,t,n,o){let i=new Headers(o?.headers),s=i.get("content-type");if(s==null)throw new Error("Content-Type header must be set");i.delete("content-type");let a=0n,c=t.ranges.map(({start:d,end:f})=>{let h=K([`--${t.multipartBoundary}`,`Content-Type: ${s}`,`Content-Range: ${B9(n,d,f)}`,"",""].join(`\r
104
104
  `));return a+=BigInt(h.byteLength)+(BigInt(f??n)-BigInt(d??0)),h}),l=K([`--${t.multipartBoundary}--`,""].join(`\r
105
105
  `));a+=BigInt(l.byteLength),i.set("content-length",`${a}`),i.set("content-type",`multipart/byteranges; boundary=${t.multipartBoundary}`);let u=Kn((async function*(){for(let d=0;d<c.length;d++){yield c[d];let{offset:f,length:h}=O9(n,t.ranges[d].start,t.ranges[d].end);yield*e(f,h),yield K(`\r
106
- `)}yield l})());return new Response(u,{...o??{},status:206,statusText:"Partial Content",headers:i})}function jy(r,e,t){let n=new Headers(t?.headers);e!=null&&n.set("content-range",`bytes */${e}`);let o=new Response("Range Not Satisfiable",{...t,headers:n,status:416,statusText:"Range Not Satisfiable"});return Tn(o,"basic"),_n(o,r),o}function jL(r,e){let t=new Headers(e?.headers),n=new Response("Precondition Failed",{...e,headers:t,status:412,statusText:"Precondition Failed"});return Tn(n,"basic"),_n(n,r),n}var vr=class{pluginOptions;_log;get log(){return this._log==null&&(this._log=this.pluginOptions.logger.newScope(this.id)),this._log}constructor(e){this.pluginOptions=e}};function AQ(r){return`${r.replace(/\/ipfs\//,"").replace(/\/ipns\//,"").replace(/\/+$/g,"").replace(/\//g,"_")}.car`}function TQ({url:r}){let e=r.searchParams.get("dag-scope");return e==="all"||e==="entity"||e==="block"?e:r.searchParams.has("entity-bytes")?"entity":"all"}var Yy=class extends vr{id="car-plugin";canHandle({accept:e}){return e.some(t=>t.contentType.mediaType===Cc)}async handle(e){let{url:t,accept:n,resource:o,blockstore:i,range:s,ipfsRoots:a,terminalElement:c,requestedMimeTypes:l}=e;if(s!=null)return Yr(o,new Error("Range requests are not supported for CAR files"));let u=n.filter(_=>_.contentType.mediaType===Cc).pop();if(u==null)return Yr(o,new Error("Could not find CAR media type in accept header"));let d=u.options.order==="dfs"?"dfs":"unk",f=u.options.dups!=="n";if(u.options.version==="2"||t.searchParams.get("car-version")==="2")return ea(o,l,[D9]);let h=this.pluginOptions.helia,p=BL({blockstore:i,getCodec:h.getCodec,logger:h.logger}),y={...e,includeTraversalBlocks:!0};f||(y.blockFilter=Lt(1024)),a.length>1&&(y.traversal=new Fy(a));let g=TQ(e),m=c.cid;if(g==="block")y.exporter=new Qh;else if(g==="entity")if(m.code===We){let _={listingOnly:!0},R=await jn(c.cid,i,e);if(R.type==="file"){let D=qL(R.size,t.searchParams.get("entity-bytes"));_.offset=D.offset,_.length=D.length}y.exporter=new Cu(_)}else y.exporter=new Qh;else y.exporter=new _u({walker:d==="dfs"?Wl():f0()});let b=Kn(p.export(m,y));return Cn(o,b,{redirected:e.redirected,headers:{"content-type":`${Cc}; version=1; order=${d}; dups=${f?"y":"n"}`,"content-disposition":`attachment; ${jr(t.searchParams.get("filename")??AQ(`/ipfs/${t.hostname}${t.pathname}`))}`,"x-content-type-options":"nosniff","accept-ranges":"none"}})}};var _Q={[tr]:{[vn]:r=>r,[En]:r=>r,[An]:r=>Hl(As(r)),[Sn]:()=>{throw new Error("Cannot perform conversion since IPIP-0524")},[sr]:r=>r,[Ft]:r=>r},81:{[vn]:r=>r,[En]:r=>r,[An]:r=>r,[Sn]:r=>Hl(As(r)),[sr]:r=>r,[Ft]:r=>r},[rr]:{[vn]:r=>r,[En]:()=>{throw new Error("Cannot perform conversion since IPIP-0524")},[An]:r=>r,[Sn]:r=>r,[sr]:r=>r,[Ft]:r=>r},[ar]:{[vn]:r=>r,[En]:r=>o0(ua(r)),[An]:r=>r,[Sn]:r=>r,[sr]:r=>r,[Ft]:r=>r},[We]:{[vn]:r=>r,[En]:()=>{throw new Error("Cannot perform conversion since IPIP-0524")},[An]:r=>r,[Sn]:()=>{throw new Error("Cannot perform conversion since IPIP-0524")},[sr]:r=>r,[Ft]:r=>r},[Ie]:{[vn]:r=>r,[En]:r=>{throw new Error("Cannot perform conversion since IPIP-0524")},[An]:r=>r,[Sn]:r=>{throw new Error("Cannot perform conversion since IPIP-0524")},[sr]:r=>r,[Ft]:r=>r},[Ke.code]:{[vn]:r=>r,[En]:r=>o0(r),[An]:r=>r,[Sn]:r=>Hl(r),[sr]:r=>r,[Ft]:r=>r}};function YL(r,e,t){if(t.length===0)return{contentType:op(r)[0],output:e};for(let n of t){let o=_Q[r.code]?.[n.contentType.mediaType];if(o!=null)return{contentType:n.contentType,output:o(e)}}throw new Error(`Could not convert ${r} to any of ${t.map(n=>n.contentType.mediaType).join(", ")}`)}var Xy=class extends vr{id="ipld-plugin";codes=[81,tr,rr,ar,Ie,We,Ke.code];canHandle({terminalElement:e,accept:t}){let n=this.codes.includes(e.cid.code),o=t.length===0||t.some(i=>i.contentType.mediaType===vn||i.contentType.mediaType===En||i.contentType.mediaType===An||i.contentType.mediaType===Sn);return n&&o}async handle(e){let{url:t,resource:n,accept:o,ipfsRoots:i,terminalElement:s,blockstore:a,requestedMimeTypes:c}=e;this.log.trace("fetching %c%s",s.cid,t.pathname);let l=await ue(a.get(s.cid,e)),u;try{let f=YL(s.cid,l,o);l=f.output,u=f.contentType}catch(f){return this.log.error("could not decode object from block - %e",f),ea(n,c,op(s.cid))}let d={"content-length":`${l.byteLength}`,"content-type":u.mediaType,"content-disposition":`${t.searchParams.get("download")==="true"?"attachment":u.disposition}; ${jr(t.searchParams.get("filename")??`${s.cid}${u.extension}`)}`,"x-ipfs-roots":i.map(f=>f.toV1()).join(","),"x-content-type-options":"nosniff","accept-ranges":"bytes"};return e.range!=null?Ou(n,async function*(f,h){yield l.subarray(f,f+h)},e.range,l.byteLength,{redirected:e.redirected,headers:d}):Cn(n,l,{redirected:e.redirected,headers:d})}};var Qy=class extends vr{id="ipns-record-plugin";codes=[];canHandle({accept:e}){return e.some(t=>t.contentType.mediaType===_c)}async handle(e){let{resource:t,url:n,range:o}=e,{ipnsResolver:i}=this.pluginOptions;if(n.pathname!==""&&n.pathname!=="/"||n.protocol!=="ipns:")return this.log.error('invalid request for IPNS name "%s" and path "%s"',n,n.pathname),Yr(t,new Error("Invalid IPNS name"));if(o!=null)return Yr(t,new Error("Range requests are not supported for IPNS records"));let s;try{this.log.trace('trying to parse peer id from "%s"',n.hostname),s=Ee(n.hostname)}catch(l){return this.log.error("could not parse peer id from IPNS url %s",t,l),Yr(t,l)}let a=await i.resolve(s,e),c=oc(a.record);return Cn(t,c,{redirected:e.redirected,headers:{"content-length":`${c.byteLength}`,"content-type":Ic.mediaType,"content-disposition":`attachment; ${jr(n.searchParams.get("filename")??`${s}${Ic.extension}`)}`,"x-ipfs-roots":a.cid.toV1().toString(),"cache-control":`public, max-age=${Number((a.record.ttl??0n)/BigInt(1e9))}`,"accept-ranges":"none"}})}};var Zy=class extends vr{id="raw-plugin";canHandle({accept:e}){return e.length===0||e.some(n=>n.contentType.mediaType===sr||n.contentType.mediaType===Ft)}async handle(e){let{url:t,resource:n,accept:o,ipfsRoots:i,terminalElement:s,blockstore:a,requestedMimeTypes:c}=e;this.log.trace("fetching %c%s",s.cid,t.pathname);let l=await ue(a.get(s.cid,e)),u=o.find(h=>h.contentType.mediaType===sr||h.contentType.mediaType===Ft)?.contentType.mediaType??sr,d=c.some(h=>h.mediaType===sr||h.mediaType===Ft);if(u===sr&&!d&&this.pluginOptions.contentTypeParser!=null){let h=t.searchParams.get("filename")??void 0;try{let p=this.pluginOptions.contentTypeParser(l,h),y=ms(p)?await p:p;y!=null&&(this.log.trace("sniffed content type %s for raw block %c",y,s.cid),u=y)}catch(p){this.log.error("error parsing content type - %e",p)}}let f={"content-length":`${l.byteLength}`,"content-type":u,"content-disposition":`${t.searchParams.get("download")==="false"?"inline":"attachment"}; ${jr(t.searchParams.get("filename")??`${s.cid}.raw`)}`,"x-ipfs-roots":i.map(h=>h.toV1()).join(","),"x-content-type-options":"nosniff","accept-ranges":"bytes"};return e.range!=null?Ou(n,async function*(h,p){yield l.subarray(h,h+p)},e.range,l.byteLength,{redirected:e.redirected,headers:f}):Cn(n,l,{redirected:e.redirected,headers:f})}};var Jy=class extends Error{name;code;constructor(e,t,n){super(e),this.name=t,this.code=n}},Pc=class extends Jy{constructor(e="not a Unixfs node"){super(e,"NotUnixFSError","ERR_NOT_UNIXFS")}};var e4=class extends Jy{constructor(e="path does not exist"){super(e,"DoesNotExistError","ERR_DOES_NOT_EXIST")}};var WKe=K("ustar\0","binary"),jKe=K("ustar ","binary"),YKe=K(" \0","binary");var JL=Yt(QL(),1);var IQ="0000000000000000000",kQ="7777777777777777777",RQ=48,PQ=K("ustar\0","binary"),DQ=K("00","binary"),LQ=parseInt("7777",8),NQ=257,OQ=263,BQ=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},MQ=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},ta=function(r,e){let t=r.toString(8);return t.length>e?K(kQ.slice(0,e)+" "):K(IQ.slice(0,e-t.length)+t+" ")},q9=function(r){let e=K(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function ZL(r){let e="";r.name!=null&&(e+=q9(" path="+r.name+`
106
+ `)}yield l})());return new Response(u,{...o??{},status:206,statusText:"Partial Content",headers:i})}function jy(r,e,t){let n=new Headers(t?.headers);e!=null&&n.set("content-range",`bytes */${e}`);let o=new Response("Range Not Satisfiable",{...t,headers:n,status:416,statusText:"Range Not Satisfiable"});return Tn(o,"basic"),_n(o,r),o}function jL(r,e){let t=new Headers(e?.headers),n=new Response("Precondition Failed",{...e,headers:t,status:412,statusText:"Precondition Failed"});return Tn(n,"basic"),_n(n,r),n}var vr=class{pluginOptions;_log;get log(){return this._log==null&&(this._log=this.pluginOptions.logger.newScope(this.id)),this._log}constructor(e){this.pluginOptions=e}};function AQ(r){return`${r.replace(/\/ipfs\//,"").replace(/\/ipns\//,"").replace(/\/+$/g,"").replace(/\//g,"_")}.car`}function TQ({url:r}){let e=r.searchParams.get("dag-scope");return e==="all"||e==="entity"||e==="block"?e:r.searchParams.has("entity-bytes")?"entity":"all"}var Yy=class extends vr{id="car-plugin";canHandle({accept:e}){return e.some(t=>t.contentType.mediaType===Cc)}async handle(e){let{url:t,accept:n,resource:o,blockstore:i,range:s,ipfsRoots:a,terminalElement:c,requestedMimeTypes:l}=e;if(s!=null)return Yr(o,new Error("Range requests are not supported for CAR files"));let u=n.filter(T=>T.contentType.mediaType===Cc).pop();if(u==null)return Yr(o,new Error("Could not find CAR media type in accept header"));let d=u.options.order==="dfs"?"dfs":"unk",f=u.options.dups!=="n";if(u.options.version==="2"||t.searchParams.get("car-version")==="2")return ea(o,l,[D9]);let h=this.pluginOptions.helia,p=BL({blockstore:i,getCodec:h.getCodec,logger:h.logger}),y={...e,includeTraversalBlocks:!0};f||(y.blockFilter=Lt(1024)),a.length>1&&(y.traversal=new Fy(a));let g=TQ(e),m=c.cid;if(g==="block")y.exporter=new Qh;else if(g==="entity")if(m.code===We){let T={listingOnly:!0},R=await jn(c.cid,i,e);if(R.type==="file"){let D=qL(R.size,t.searchParams.get("entity-bytes"));T.offset=D.offset,T.length=D.length}y.exporter=new Cu(T)}else y.exporter=new Qh;else y.exporter=new _u({walker:d==="dfs"?Wl():f0()});let b=Kn(p.export(m,y));return Cn(o,b,{redirected:e.redirected,headers:{"content-type":`${Cc}; version=1; order=${d}; dups=${f?"y":"n"}`,"content-disposition":`attachment; ${jr(t.searchParams.get("filename")??AQ(`/ipfs/${t.hostname}${t.pathname}`))}`,"x-content-type-options":"nosniff","accept-ranges":"none"}})}};var _Q={[tr]:{[vn]:r=>r,[En]:r=>r,[An]:r=>Hl(As(r)),[Sn]:()=>{throw new Error("Cannot perform conversion since IPIP-0524")},[sr]:r=>r,[Ft]:r=>r},81:{[vn]:r=>r,[En]:r=>r,[An]:r=>r,[Sn]:r=>Hl(As(r)),[sr]:r=>r,[Ft]:r=>r},[rr]:{[vn]:r=>r,[En]:()=>{throw new Error("Cannot perform conversion since IPIP-0524")},[An]:r=>r,[Sn]:r=>r,[sr]:r=>r,[Ft]:r=>r},[ar]:{[vn]:r=>r,[En]:r=>o0(ua(r)),[An]:r=>r,[Sn]:r=>r,[sr]:r=>r,[Ft]:r=>r},[We]:{[vn]:r=>r,[En]:()=>{throw new Error("Cannot perform conversion since IPIP-0524")},[An]:r=>r,[Sn]:()=>{throw new Error("Cannot perform conversion since IPIP-0524")},[sr]:r=>r,[Ft]:r=>r},[Ie]:{[vn]:r=>r,[En]:r=>{throw new Error("Cannot perform conversion since IPIP-0524")},[An]:r=>r,[Sn]:r=>{throw new Error("Cannot perform conversion since IPIP-0524")},[sr]:r=>r,[Ft]:r=>r},[Ke.code]:{[vn]:r=>r,[En]:r=>o0(r),[An]:r=>r,[Sn]:r=>Hl(r),[sr]:r=>r,[Ft]:r=>r}};function YL(r,e,t){if(t.length===0)return{contentType:op(r)[0],output:e};for(let n of t){let o=_Q[r.code]?.[n.contentType.mediaType];if(o!=null)return{contentType:n.contentType,output:o(e)}}throw new Error(`Could not convert ${r} to any of ${t.map(n=>n.contentType.mediaType).join(", ")}`)}var Xy=class extends vr{id="ipld-plugin";codes=[81,tr,rr,ar,Ie,We,Ke.code];canHandle({terminalElement:e,accept:t}){let n=this.codes.includes(e.cid.code),o=t.length===0||t.some(i=>i.contentType.mediaType===vn||i.contentType.mediaType===En||i.contentType.mediaType===An||i.contentType.mediaType===Sn);return n&&o}async handle(e){let{url:t,resource:n,accept:o,ipfsRoots:i,terminalElement:s,blockstore:a,requestedMimeTypes:c}=e;this.log.trace("fetching %c%s",s.cid,t.pathname);let l=await ue(a.get(s.cid,e)),u;try{let f=YL(s.cid,l,o);l=f.output,u=f.contentType}catch(f){return this.log.error("could not decode object from block - %e",f),ea(n,c,op(s.cid))}let d={"content-length":`${l.byteLength}`,"content-type":u.mediaType,"content-disposition":`${t.searchParams.get("download")==="true"?"attachment":u.disposition}; ${jr(t.searchParams.get("filename")??`${s.cid}${u.extension}`)}`,"x-ipfs-roots":i.map(f=>f.toV1()).join(","),"x-content-type-options":"nosniff","accept-ranges":"bytes"};return e.range!=null?Ou(n,async function*(f,h){yield l.subarray(f,f+h)},e.range,l.byteLength,{redirected:e.redirected,headers:d}):Cn(n,l,{redirected:e.redirected,headers:d})}};var Qy=class extends vr{id="ipns-record-plugin";codes=[];canHandle({accept:e}){return e.some(t=>t.contentType.mediaType===_c)}async handle(e){let{resource:t,url:n,range:o}=e,{ipnsResolver:i}=this.pluginOptions;if(n.pathname!==""&&n.pathname!=="/"||n.protocol!=="ipns:")return this.log.error('invalid request for IPNS name "%s" and path "%s"',n,n.pathname),Yr(t,new Error("Invalid IPNS name"));if(o!=null)return Yr(t,new Error("Range requests are not supported for IPNS records"));let s;try{this.log.trace('trying to parse peer id from "%s"',n.hostname),s=Ee(n.hostname)}catch(l){return this.log.error("could not parse peer id from IPNS url %s",t,l),Yr(t,l)}let a=await i.resolve(s,e),c=oc(a.record);if(a.record.validityType==="EOL"){let l=new Date(a.record.validity);e.expires=l,e.ttl=Math.round(Number((a.record.ttl??0n)/BigInt(1e9)))}return Cn(t,c,{redirected:e.redirected,headers:{"content-length":`${c.byteLength}`,"content-type":Ic.mediaType,"content-disposition":`attachment; ${jr(n.searchParams.get("filename")??`${s}${Ic.extension}`)}`,"x-ipfs-roots":a.cid.toV1().toString(),"accept-ranges":"none"}})}};var Zy=class extends vr{id="raw-plugin";canHandle({accept:e}){return e.length===0||e.some(n=>n.contentType.mediaType===sr||n.contentType.mediaType===Ft)}async handle(e){let{url:t,resource:n,accept:o,ipfsRoots:i,terminalElement:s,blockstore:a,requestedMimeTypes:c}=e;this.log.trace("fetching %c%s",s.cid,t.pathname);let l=await ue(a.get(s.cid,e)),u=o.find(h=>h.contentType.mediaType===sr||h.contentType.mediaType===Ft)?.contentType.mediaType??sr,d=c.some(h=>h.mediaType===sr||h.mediaType===Ft);if(u===sr&&!d&&this.pluginOptions.contentTypeParser!=null){let h=t.searchParams.get("filename")??void 0;try{let p=this.pluginOptions.contentTypeParser(l,h),y=ms(p)?await p:p;y!=null&&(this.log.trace("sniffed content type %s for raw block %c",y,s.cid),u=y)}catch(p){this.log.error("error parsing content type - %e",p)}}let f={"content-length":`${l.byteLength}`,"content-type":u,"content-disposition":`${t.searchParams.get("download")==="false"?"inline":"attachment"}; ${jr(t.searchParams.get("filename")??`${s.cid}.raw`)}`,"x-ipfs-roots":i.map(h=>h.toV1()).join(","),"x-content-type-options":"nosniff","accept-ranges":"bytes"};return e.range!=null?Ou(n,async function*(h,p){yield l.subarray(h,h+p)},e.range,l.byteLength,{redirected:e.redirected,headers:f}):Cn(n,l,{redirected:e.redirected,headers:f})}};var Jy=class extends Error{name;code;constructor(e,t,n){super(e),this.name=t,this.code=n}},Pc=class extends Jy{constructor(e="not a Unixfs node"){super(e,"NotUnixFSError","ERR_NOT_UNIXFS")}};var e4=class extends Jy{constructor(e="path does not exist"){super(e,"DoesNotExistError","ERR_DOES_NOT_EXIST")}};var WKe=K("ustar\0","binary"),jKe=K("ustar ","binary"),YKe=K(" \0","binary");var JL=Yt(QL(),1);var IQ="0000000000000000000",kQ="7777777777777777777",RQ=48,PQ=K("ustar\0","binary"),DQ=K("00","binary"),LQ=parseInt("7777",8),NQ=257,OQ=263,BQ=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},MQ=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},ta=function(r,e){let t=r.toString(8);return t.length>e?K(kQ.slice(0,e)+" "):K(IQ.slice(0,e-t.length)+t+" ")},q9=function(r){let e=K(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function ZL(r){let e="";r.name!=null&&(e+=q9(" path="+r.name+`
107
107
  `)),r.linkname!=null&&(e+=q9(" linkpath="+r.linkname+`
108
108
  `));let t=r.pax;if(t!=null)for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e+=q9(" "+n+"="+t[n]+`
109
109
  `));return K(e)}function t4(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),K(t).byteLength!==t.length)return null;for(;K(t).byteLength>100;){let o=t.indexOf("/");if(o===-1)return null;n+=n!==""?"/"+t.slice(0,o):t.slice(0,o),t=t.slice(o+1)}return K(t).byteLength>100||K(n).byteLength>155||r.linkname!=null&&K(r.linkname).byteLength>100?null:(e.set(K(t),0),e.set(ta(r.mode&LQ,6),100),e.set(ta(r.uid,6),108),e.set(ta(r.gid,6),116),e.set(ta(r.size,11),124),e.set(ta(r.mtime.getTime()/1e3|0,11),136),e[156]=RQ+BQ(r.type),r.linkname!=null&&e.set(K(r.linkname),157),e.set(PQ,NQ),e.set(DQ,OQ),r.uname!=null&&e.set(K(r.uname),265),r.gname!=null&&e.set(K(r.gname),297),e.set(ta(r.devmajor??0,6),329),e.set(ta(r.devminor??0,6),337),n!=null&&e.set(K(n),345),e.set(ta(MQ(e),6),148),e)}var{S_IFMT:UQ,S_IFBLK:$Q,S_IFCHR:HQ,S_IFDIR:qQ,S_IFIFO:VQ,S_IFLNK:KQ}=JL.default,zQ=parseInt("755",8),GQ=parseInt("644",8),eN=new Uint8Array(1024);function WQ(r=0){switch(r&UQ){case $Q:return"block-device";case HQ:return"character-device";case qQ:return"directory";case VQ:return"fifo";case KQ:return"symlink";default:return"file"}}function K9(r){return r&=511,r!==0?eN.subarray(0,512-r):new Uint8Array(0)}function V9(r){if(r.pax==null){let e=t4(r);if(e!=null)return e}return jQ(r)}function jQ(r){let e=ZL(r),t={name:"PaxHeader",mode:r.mode,uid:r.uid,gid:r.gid,size:e.length,mtime:r.mtime,type:"pax-header",linkname:r.linkname,uname:r.uname,gname:r.gname,devmajor:r.devmajor,devminor:r.devminor};return new G(t4(t)??new Uint8Array(0),e,K9(e.length),t4({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function r4(){return async function*(r){for await(let{header:e,body:t}of r){let n={...e,size:e.type==="symlink"?0:e.size??0,type:e.type??WQ(e.mode),mode:e.mode??(e.type==="directory"?zQ:GQ),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=K(t)),t instanceof Uint8Array||Nn(t)){n.size=t.length,yield V9(n),yield Nn(t)?t.subarray():t,yield K9(n.size);continue}if(n.type==="symlink"&&n.linkname==null){if(t==null)throw new Error("type was symlink but no linkname or body specified");n.linkname=de(await ue(t)),yield V9(n);continue}if(yield V9(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let o=0;for await(let i of t??[])o+=i.length,yield Nn(i)?i.subarray():i;if(o!==n.size)throw new Error(`size mismatch, wrote ${o} of ${n.size} bytes`);yield K9(n.size)}yield eN}}var YQ=["file","raw","directory"];function XQ(r,e){let t,n,o=0n;return(r.type==="file"||r.type==="raw"||r.type==="identity")&&(o=r.size),(r.type==="file"||r.type==="directory")&&(t=r.unixfs.mode,n=r.unixfs.mtime!=null?new Date(Number(r.unixfs.mtime.secs*1000n)):void 0),{name:e,mode:t,mtime:n,size:Number(o),type:r.type==="directory"?"directory":"file"}}function tN(r,e){if(!YQ.includes(r.type))throw new Pc(`${r.type} is not a UnixFS node`);let t={header:XQ(r,e)};return(r.type==="file"||r.type==="raw")&&(t.body=r.content()),t}async function*rN(r,e,t){let n=await Lu(Js(r,e,t));if(n==null)throw new E(`Could not walk path "${r}"`);let o=await jn(n.cid,e,t);if(o.type==="file"||o.type==="raw"){yield*on([tN(o,n.path)],r4());return}if(o.type==="directory"){yield*on(OL(o.cid,e,t),i=>Ct(i,async s=>{let a=await jn(s.cid,e,t);return tN(a,s.path)}),r4());return}throw new Pc("Not a UnixFS node")}var n4=class extends vr{id="tar-plugin";codes=[];canHandle({accept:e}){return e.some(t=>t.contentType.mediaType===Nu)}async handle(e){let{terminalElement:t,url:n,resource:o,blockstore:i,range:s}=e;if(t.cid.code!==We&&t.cid.code!==Ie)return Yr(o,new Pc("Only UnixFS data can be returned in a TAR file"));if(s!=null)return Yr(o,new Error("Range requests are not supported for TAR files"));let a=Kn(rN(`/ipfs/${t.cid}${n.pathname}`,i,e));return Cn(o,a,{redirected:e.redirected,headers:{"content-type":Nu,"content-disposition":`attachment; ${jr(n.searchParams.get("filename")??`${t.cid.toString()}.tar`)}`,"accept-ranges":"none"}})}};var QQ=new Uint8Array(0);function ZQ(r,e){let t;try{t=new URL(r.toString())}catch{t=e}if(!t.pathname.endsWith("/"))return t.pathname+="/",t.toString()}var o4=class extends vr{id="unixfs-plugin";codes=[We,Ie];canHandle({terminalElement:e,accept:t}){let n=this.codes.includes(e.cid.code),o=t.length===0||t.some(i=>i.contentType.mediaType===Ft||i.contentType.mediaType===np);return n&&o}async handle(e){let{url:t,resource:n,terminalElement:o,ipfsRoots:i,blockstore:s}=e,a=t.searchParams.get("filename")??o.name,c=e.redirected,l;try{l=await jn(`/ipfs/${o.cid}`,s,e)}catch(u){if(e?.signal?.throwIfAborted(),u.name==="BlockNotFoundWhileOfflineError")throw u;return this.log.error("could not export %c - %e",o.cid,u),Rc(n,"Unable to stream content")}if(l.type==="directory"){let u=ZQ(n,t);if(u!=null){if(this.log.trace("directory url normalization spec requires redirect"),e?.redirect==="error")throw this.log('could not redirect to %s as redirect option was set to "error"',u),new TypeError("Failed to fetch");if(e?.redirect==="manual")return this.log("returning 301 permanent redirect to %s",u),WL(e.resource,u);this.log("following redirect to %s",u),n=u,c=!0}let d=o.cid;if(e?.supportDirectoryIndexes!==!1){let h="index.html";try{this.log.trace("found directory at %c%s, looking for index.html",d,t.pathname);let p=await e.serverTiming.time("exporter-dir","",Lu(Js(`/ipfs/${d}/${h}`,e.blockstore,e)));if(p==null)return Rc(n,"Unable to stream content");let y=await e.serverTiming.time("exporter-dir","",jn(p.cid,e.blockstore,e));return y.type!=="file"&&y.type!=="raw"&&y.type!=="identity"?Rc(n,"Unable to stream content"):(a=h,this.log.trace("found directory index at %c%s with cid %c",d,h,l.cid),await this.streamFile(n,y,a,i,c,e.range,e))}catch(p){if(p.name!=="NotFoundError")throw this.log.error("error loading path %c/%s - %e",d,h,p),p}}let f=await ue(e.blockstore.get(d,e));if(l.unixfs.type==="hamt-sharded-directory"){let h=[],p=hn(f);for await(let y of l.entries())h.push({Name:y.name,Hash:y.cid,Tsize:y.size});f=gw({Data:p.Data,Links:h.sort((y,g)=>y.Name?.localeCompare(g.Name??"")??0)})}return Cn(n,f,{headers:{"content-type":np,"content-length":`${f.byteLength}`,"content-disposition":`${t.searchParams.get("download")==="true"?"attachment":"inline"}; ${jr(`${d}.dir`)}`,"x-ipfs-roots":i.map(h=>h.toV1()).join(","),"accept-ranges":"bytes","x-unixfs-type":l.unixfs.type},redirected:c})}else return l.type==="file"||l.type==="raw"||l.type==="identity"?(this.log("streaming file"),this.streamFile(n,l,a,i,c,e.range,e)):(this.log.error("cannot stream terminal element type %s",l.type),Rc(n,"Unable to stream content"))}async streamFile(e,t,n,o,i,s,a){let c=Ft;return s==null&&(c=await this.detectContentType(t,n,a)),s!=null?Ou(e,(l,u)=>t.content({...a??{},offset:l,length:u}),s,t.size,{headers:{"content-type":c,"content-disposition":`inline; ${jr(n)}`,"x-ipfs-roots":o.map(l=>l.toV1()).join(","),"accept-ranges":"bytes","x-unixfs-type":t.type},redirected:i}):Cn(e,Kn(t.content(a)),{headers:{"content-type":c,"content-length":`${t.size}`,"content-disposition":`inline; ${jr(n)}`,"x-ipfs-roots":o.map(l=>l.toV1()).join(","),"accept-ranges":"bytes","x-unixfs-type":t.type},redirected:i})}async detectContentType(e,t,n){let o;e.type==="raw"||e.type==="identity"?o=e.node:o=await R0(e.content(n)),o==null&&(o=QQ);let i;if(this.pluginOptions.contentTypeParser!=null)try{let s=this.pluginOptions.contentTypeParser(o,t);if(ms(s)){let a=await s;a!=null&&(i=a)}else s!=null&&(i=s);this.log.trace("contentTypeParser returned %s for file with name %s",i,t)}catch(s){this.log.error("error parsing content type - %e",s)}return i??Ft}};var JQ={"ipfs.resolve":"i","dnsLink.resolve":"d","ipns.resolve":"n","found-provider":"p","find-providers":"f",connect:"c",block:"b","http-gateway-router":"h","libp2p-router":"l","trustless-gateway":"t",bitswap:"b"};function In(r){return JQ[r]??r}function nN(r){return bi.exactMatch(r)?"t":Om.exactMatch(r)||Bm.exactMatch(r)?"h":fo.exactMatch(r)||xi.exactMatch(r)?"w":Ua.exactMatch(r)?"r":Fa.exactMatch(r)?"d":XS.exactMatch(r)||Nm.exactMatch(r)?"q":Zd.exactMatch(r)?"b":"u"}var fM=Yt(lM(),1);var zee=[200,301,302,303,307,308,404,410,451],uM=65536;function hM(r,e,t={}){try{if(e.length>uM)throw new ip(`_redirects file size cannot exceed ${uM} bytes`);let n=e.split(`
110
- `).filter(o=>(o=o.trim(),o!==""&&!o.startsWith("#"))).map(o=>{let[i,s,a]=o.split(/\s+/).map(f=>f.trim());if(a!=null&&a!==""&&!a.match(/^\d+$/))throw new sp("Invalid status code in _redirects file");let c=parseInt(a);if(isNaN(c)&&(c=301),!zee.includes(c))throw new ap(`Status code ${c} is not allowed`);let l=new Set,u=i.split("/"),d=u.map((f,h)=>{if(f.startsWith(":")){let p=f.substring(1);if(l.has(p))throw new cp("Duplicate placeholders in from path");return l.add(p),`(?<${p}>[^/]+)`}return f==="*"&&h===u.length-1?"(?<splat>.+)":(0,fM.default)(f)}).join("\\/");return{from:new RegExp(d),to:s,status:c}});for(let{from:o,to:i,status:s}of n){let a=r.pathname.match(o);if(a!=null)return Gee(r,i,s,a.groups,t)}}catch(n){return new Response(JSON.stringify(kc(n),null,2),{status:500})}}function Gee(r,e,t,n,o={}){if(o.redirect==="error")throw new TypeError("Failed to fetch");if(n!=null)for(let[c,l]of Object.entries(n))e=e.replaceAll(`:${c}`,l);let i=Wee(r,new URL(`${r.protocol}//${r.host}${e}`)),s=new URL(`${r.protocol}//${r.host}${e}`),a=new URL(`${r.protocol}//${r.host}${s.pathname}${jee(i)}${r.hash}`);return o.redirect==="manual"?new Response("",{status:t,headers:{location:a.toString()}}):a}function Wee(r,e){let t={};for(let[n,o]of r.searchParams)e.searchParams.delete(n),dM(n,o,t);for(let[n,o]of e.searchParams)dM(n,o,t);return t}function dM(r,e,t){typeof t[r]=="string"&&(t[r]=[t[r]]),Array.isArray(t[r])?t[r].push(e):t[r]=e}function jee(r){let e=[...Object.entries(r)].map(([t,n])=>(Array.isArray(n)||(n=[n]),n.map(o=>`${encodeURIComponent(t)}=${encodeURIComponent(o)}`).join("&"))).join("&");return e===""?e:`?${e}`}var zu=class{headers;constructor(){this.headers=[]}getHeader(){return this.headers.join(",")}async time(e,t,n){let o=performance.now();try{return await n}finally{let s=performance.now()-o;this.add(e,t,s)}}add(e,t,n){this.headers.push(`${e};dur=${Math.round(n)}${t===""?"":`;desc="${t}"`}`)}};var Yee=29030400;function Xee(r){return{cid:r,name:r.toString(),path:r.toString(),roots:[r],remainder:[]}}var S4=class{log;components;blockstoreSessions;constructor(e,t={}){this.components=e,this.log=e.helia.logger.forComponent("helia-verified-fetch:url-resolver"),this.blockstoreSessions=new Xs({maxSize:t.sessionCacheSize??100,maxAge:t.sessionTTLms??6e4,onEviction:(n,o)=>{o.close()}})}async resolve(e,t=new zu,n={}){if(e.protocol==="ipfs:")return this.resolveIPFSPath(e,t,n);if(e.protocol==="ipns:")return this.resolveIPNSName(e,t,n);if(e.protocol==="dnslink:")return this.resolveDNSLink(e,t,n);throw new Gn(`Invalid resource. Unsupported protocol in URL, must be ipfs:, ipns:, or dnslink: ${e}`)}async getBlockstore(e,t={}){if(t.session===!1)return this.components.helia.blockstore;let n=`ipfs:${e}`,o=this.blockstoreSessions.get(n),i=!1;if(o==null&&(this.log("create session with %d initial providers for root %c",t.providers?.length??0,e),i=!0,o=this.components.helia.blockstore.createSession(e,t),this.blockstoreSessions.set(n,o)),!i&&t.providers!=null&&t.providers.length>0){this.log("adding %d providers to existing session for root %c",t.providers.length,e);try{let s=await Promise.all(t.providers.map(async a=>{await o.addPeer(a,t)})??[]);this.log("result was %o",s)}catch(s){this.log.error("could not add provs - %e",s)}}return o}async resolveDNSLink(e,t,n){let i=(await t.time(In("dnsLink.resolve"),"",this.components.dnsLink.resolve(e.hostname,n)))?.[0];if(i==null)throw new TypeError(`Invalid resource. Cannot resolve DNSLink from domain: ${e.hostname}`);let s,a=pM(`${i.path}/${e.pathname}`);if(i.namespace==="ipns"){let c=new URL(`ipns://${i.peerId}${a}`);s=await this.resolveIPNSName(c,t,n)}else if(i.namespace==="ipfs"){let c=new URL(`ipfs://${i.cid}${a}`);s=await this.resolveIPFSPath(c,t,n)}else throw new TypeError(`Invalid resource. Unexpected DNSLink namespace ${i.namespace} from domain: ${e.hostname}`);return s instanceof Response?s:{...s,url:e,ttl:i.answer.TTL}}async resolveIPNSName(e,t,n){let o=Ee(e.hostname),i=await t.time(In("ipns.resolve"),"",this.components.ipnsResolver.resolve(o,n)),s=pM(`${i.path??""}/${e.pathname}`),a=new URL(`ipfs://${i.cid}${s}`),c=await this.resolveIPFSPath(a,t,n);return c instanceof Response?c:{...c,url:e,ttl:Number((i.record.ttl??0n)/BigInt(1e9))}}async resolveIPFSPath(e,t,n){let o=await t.time(In("ipfs.resolve"),"",this.walkPath(e,n));if(o instanceof Response)return o;if(o.terminalElement.cid.code===114){let i=new URL(`ipns://${Lr(o.terminalElement.cid)}`),s=await this.resolveIPNSName(i,t,n);return s instanceof Response?s:{...s,url:e}}return{...o,url:e,ttl:Yee,blockstore:o.blockstore}}async walkPath(e,t={}){let n;try{n=F.parse(e.hostname)}catch(i){throw new Gn(`Could not parse CID - ${i}`)}let o=await this.getBlockstore(n,t);try{let i=[],s,a=Qee(e);for await(let c of Js(a,o,{...t,yieldSubShards:!0}))i.push(c.cid),s=c;if(s==null)throw new e4("No terminal element found");return{ipfsRoots:i,terminalElement:s,blockstore:o,redirected:t.redirected===!0}}catch(i){if(i.name==="NotFoundError"&&t.redirected!==!0){let s;try{s=await jn(`${n}/_redirects`,o,t)}catch(a){if(a.name!=="NotFoundError")throw a}if(s?.type==="file"||s?.type==="raw"){let a=de(await ue(s.content(t))),c=hM(e,a,t);if(c instanceof Response)return c;if(c instanceof URL)return this.walkPath(c,{...t,redirected:!0})}}if(i.name==="NoResolverError")return{ipfsRoots:[n],terminalElement:Xee(n),blockstore:o,redirected:!1};throw i}}};function Qee(r){let e=r.pathname.split("/").map(t=>decodeURIComponent(t)).join("/").trim();return e.length>0&&!e.startsWith("/")&&(e=`/${e}`),r.protocol==="ipns:"&&e==="/"&&(e=""),`/${r.protocol==="ipfs:"?"ipfs":"ipns"}/${r.hostname}${e}`}function pM(r){return r=r.split("/").map(e=>e.trim()).filter(Boolean).join("/"),r!==""?`/${r}`:""}var wM=Yt(mM(),1);var gM={128:"\u20AC",130:"\u201A",131:"\u0192",132:"\u201E",133:"\u2026",134:"\u2020",135:"\u2021",136:"\u02C6",137:"\u2030",138:"\u0160",139:"\u2039",140:"\u0152",142:"\u017D",145:"\u2018",146:"\u2019",147:"\u201C",148:"\u201D",149:"\u2022",150:"\u2013",151:"\u2014",152:"\u02DC",153:"\u2122",154:"\u0161",155:"\u203A",156:"\u0153",158:"\u017E",159:"\u0178"},Zee={};for(let[r,e]of Object.entries(gM))Zee[e]=Number.parseInt(r,10);var A4;function Jee(){if(!(typeof globalThis.TextDecoder>"u"))return A4??(A4=new globalThis.TextDecoder("utf-8"))}var Gu=32*1024,Co=65533;function yM(r,e="utf-8"){switch(e.toLowerCase()){case"utf-8":case"utf8":{let t=Jee();return t?t.decode(r):tte(r)}case"utf-16le":return rte(r);case"us-ascii":case"ascii":return nte(r);case"latin1":case"iso-8859-1":return ote(r);case"windows-1252":return ite(r);default:throw new RangeError(`Encoding '${e}' not supported`)}}function kx(r,e){e.length!==0&&(r.push(String.fromCharCode.apply(null,e)),e.length=0)}function kt(r,e,t){e.push(t),e.length>=Gu&&kx(r,e)}function ete(r,e,t){if(t<=65535){kt(r,e,t);return}t-=65536,kt(r,e,55296+(t>>10)),kt(r,e,56320+(t&1023))}function tte(r){let e=[],t=[],n=0;for(r.length>=3&&r[0]===239&&r[1]===187&&r[2]===191&&(n=3);n<r.length;){let o=r[n];if(o<=127){kt(e,t,o),n++;continue}if(o<194||o>244){kt(e,t,Co),n++;continue}if(o<=223){if(n+1>=r.length){kt(e,t,Co),n++;continue}let u=r[n+1];if((u&192)!==128){kt(e,t,Co),n++;continue}let d=(o&31)<<6|u&63;kt(e,t,d),n+=2;continue}if(o<=239){if(n+2>=r.length){kt(e,t,Co),n++;continue}let u=r[n+1],d=r[n+2];if(!((u&192)===128&&(d&192)===128&&!(o===224&&u<160)&&!(o===237&&u>=160))){kt(e,t,Co),n++;continue}let h=(o&15)<<12|(u&63)<<6|d&63;kt(e,t,h),n+=3;continue}if(n+3>=r.length){kt(e,t,Co),n++;continue}let i=r[n+1],s=r[n+2],a=r[n+3];if(!((i&192)===128&&(s&192)===128&&(a&192)===128&&!(o===240&&i<144)&&!(o===244&&i>143))){kt(e,t,Co),n++;continue}let l=(o&7)<<18|(i&63)<<12|(s&63)<<6|a&63;ete(e,t,l),n+=4}return kx(e,t),e.join("")}function rte(r){let e=[],t=[],n=r.length,o=0;for(;o+1<n;){let i=r[o]|r[o+1]<<8;if(o+=2,i>=55296&&i<=56319){if(o+1<n){let s=r[o]|r[o+1]<<8;s>=56320&&s<=57343?(kt(e,t,i),kt(e,t,s),o+=2):kt(e,t,Co)}else kt(e,t,Co);continue}if(i>=56320&&i<=57343){kt(e,t,Co);continue}kt(e,t,i)}return o<n&&kt(e,t,Co),kx(e,t),e.join("")}function nte(r){let e=[];for(let t=0;t<r.length;t+=Gu){let n=Math.min(r.length,t+Gu),o=new Array(n-t);for(let i=t,s=0;i<n;i++,s++)o[s]=r[i]&127;e.push(String.fromCharCode.apply(null,o))}return e.join("")}function ote(r){let e=[];for(let t=0;t<r.length;t+=Gu){let n=Math.min(r.length,t+Gu),o=new Array(n-t);for(let i=t,s=0;i<n;i++,s++)o[s]=r[i];e.push(String.fromCharCode.apply(null,o))}return e.join("")}function ite(r){let e=[],t="";for(let n=0;n<r.length;n++){let o=r[n],i=o>=128&&o<=159?gM[o]:void 0;t+=i??String.fromCharCode(o),t.length>=Gu&&(e.push(t),t="")}return t&&e.push(t),e.join("")}function Xr(r){return new DataView(r.buffer,r.byteOffset)}var bM={len:1,get(r,e){return Xr(r).getUint8(e)},put(r,e,t){return Xr(r).setUint8(e,t),e+1}},ht={len:2,get(r,e){return Xr(r).getUint16(e,!0)},put(r,e,t){return Xr(r).setUint16(e,t,!0),e+2}},Lc={len:2,get(r,e){return Xr(r).getUint16(e)},put(r,e,t){return Xr(r).setUint16(e,t),e+2}};var et={len:4,get(r,e){return Xr(r).getUint32(e,!0)},put(r,e,t){return Xr(r).setUint32(e,t,!0),e+4}},Rx={len:4,get(r,e){return Xr(r).getUint32(e)},put(r,e,t){return Xr(r).setUint32(e,t),e+4}};var xM={len:4,get(r,e){return Xr(r).getInt32(e)},put(r,e,t){return Xr(r).setInt32(e,t),e+4}};var EM={len:8,get(r,e){return Xr(r).getBigUint64(e,!0)},put(r,e,t){return Xr(r).setBigUint64(e,t,!0),e+8}};var Ar=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return yM(n,this.encoding)}};var ste="End-Of-Stream",Se=class extends Error{constructor(){super(ste),this.name="EndOfStreamError"}},Nc=class extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Oc=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new Se;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let o=this.peekQueue.pop();if(!o)throw new Error("peekData should be defined");let i=Math.min(o.length,t);e.set(o.subarray(0,i),n),n+=i,t-=i,i<o.length&&this.peekQueue.push(o.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new Nc;let o=await this.readFromStream(e.subarray(n),t);if(o===0)break;n+=o}if(!t&&n<e.length)throw new Se;return n}};var T4=class extends Oc{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}};var wp=class extends T4{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}};var Wu=class extends Oc{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let o=await this.reader.read();if(o.done){this.endOfStream=!0;break}o.value&&(n+=this.writeChunk(e.subarray(n),o.value))}if(!t&&n===0&&this.endOfStream)throw new Se;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function Px(r){try{let e=r.getReader({mode:"byob"});return e instanceof ReadableStreamDefaultReader?new Wu(e):new wp(e)}catch(e){if(e instanceof TypeError)return new Wu(r.getReader());throw e}}var Ki=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new Se;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new Se;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new Se;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new Se;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw new RangeError("ignore length must be \u2265 0 bytes");if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};var cte=256e3,_4=class extends Ki{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),o=n.position-this.position;if(o>0)return await this.ignore(o),this.readBuffer(e,t);if(o<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new Se;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),o=0;if(n.position){let i=n.position-this.position;if(i>0){let s=new Uint8Array(n.length+i);return o=await this.peekBuffer(s,{mayBeLess:n.mayBeLess}),e.set(s.subarray(i)),o-i}if(i<0)throw new Error("Cannot peek from a negative offset in a stream")}if(n.length>0){try{o=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(i){if(t?.mayBeLess&&i instanceof Se)return 0;throw i}if(!n.mayBeLess&&o<n.length)throw new Se}return o}async ignore(e){if(e<0)throw new RangeError("ignore length must be \u2265 0 bytes");let t=Math.min(cte,e),n=new Uint8Array(t),o=0;for(;o<e;){let i=e-o,s=await this.readBuffer(n,{length:Math.min(t,i)});if(s<0)return s;o+=s}return o}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}};var C4=class extends Ki{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),o=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&o<n.length)throw new Se;return e.set(this.uint8Array.subarray(n.position,n.position+o)),o}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};var I4=class extends Ki{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),o=Math.min(this.blob.size-n.position,n.length);if(!n.mayBeLess&&o<n.length)throw new Se;let i=await this.blob.slice(n.position,n.position+o).arrayBuffer();return e.set(new Uint8Array(i)),o}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function vM(r,e){let t=Px(r),n=e??{},o=n.onClose;return n.onClose=async()=>{if(await t.close(),o)return o()},new _4(t,n)}function SM(r,e){return new C4(r,e)}function AM(r,e){return new I4(r,e)}var LM=Yt(kM(),1);var Mc={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},Dx={get(r){return{signature:et.get(r,0),compressedSize:et.get(r,8),uncompressedSize:et.get(r,12)}},len:16},RM={get(r){let e=ht.get(r,6);return{signature:et.get(r,0),minVersion:ht.get(r,4),dataDescriptor:!!(e&8),compressedMethod:ht.get(r,8),compressedSize:et.get(r,18),uncompressedSize:et.get(r,22),filenameLength:ht.get(r,26),extraFieldLength:ht.get(r,28),filename:null}},len:30},PM={get(r){return{signature:et.get(r,0),nrOfThisDisk:ht.get(r,4),nrOfThisDiskWithTheStart:ht.get(r,6),nrOfEntriesOnThisDisk:ht.get(r,8),nrOfEntriesOfSize:ht.get(r,10),sizeOfCd:et.get(r,12),offsetOfStartOfCd:et.get(r,16),zipFileCommentLength:ht.get(r,20)}},len:22},DM={get(r){let e=ht.get(r,8);return{signature:et.get(r,0),minVersion:ht.get(r,6),dataDescriptor:!!(e&8),compressedMethod:ht.get(r,10),compressedSize:et.get(r,20),uncompressedSize:et.get(r,24),filenameLength:ht.get(r,28),extraFieldLength:ht.get(r,30),fileCommentLength:ht.get(r,32),relativeOffsetOfLocalHeader:et.get(r,42),filename:null}},len:46};function NM(r){let e=new Uint8Array(et.len);return et.put(e,0,r),e}var oi=(0,LM.default)("tokenizer:inflate"),Lx=256*1024,Ete=NM(Mc.DataDescriptor),D4=NM(Mc.EndOfCentralDirectory),Fc=class r{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(Lx)}async isZip(){return await this.peekSignature()===Mc.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(et)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let o=n.length-4;o>=0;o--)if(n[o]===D4[0]&&n[o+1]===D4[1]&&n[o+2]===D4[2]&&n[o+3]===D4[3])return e.fileInfo.size-t+o;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){oi("Cannot reading central-directory without random-read support");return}oi("Reading central-directory...");let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){oi("Central-directory 32-bit signature found");let n=await this.tokenizer.readToken(PM,t),o=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let i=0;i<n.nrOfEntriesOfSize;++i){let s=await this.tokenizer.readToken(DM);if(s.signature!==Mc.CentralFileHeader)throw new Error("Expected Central-File-Header signature");s.filename=await this.tokenizer.readToken(new Ar(s.filenameLength,"utf-8")),await this.tokenizer.ignore(s.extraFieldLength),await this.tokenizer.ignore(s.fileCommentLength),o.push(s),oi(`Add central-directory file-entry: n=${i+1}/${o.length}: filename=${o[i].filename}`)}return this.tokenizer.setPosition(e),o}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let o=await this.readLocalFileHeader();if(!o)break;let i=e(o);n=!!i.stop;let s;if(await this.tokenizer.ignore(o.extraFieldLength),o.dataDescriptor&&o.compressedSize===0){let a=[],c=Lx;oi("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let l=-1;for(;l<0&&c===Lx;){c=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),l=vte(this.syncBuffer.subarray(0,c),Ete);let u=l>=0?l:c;if(i.handler){let d=new Uint8Array(u);await this.tokenizer.readBuffer(d),a.push(d)}else await this.tokenizer.ignore(u)}oi(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),i.handler&&await this.inflate(o,Ste(a),i.handler)}else i.handler?(oi(`Reading compressed-file-data: ${o.compressedSize} bytes`),s=new Uint8Array(o.compressedSize),await this.tokenizer.readBuffer(s),await this.inflate(o,s,i.handler)):(oi(`Ignoring compressed-file-data: ${o.compressedSize} bytes`),await this.tokenizer.ignore(o.compressedSize));if(oi(`Reading data-descriptor at pos=${this.tokenizer.position}`),o.dataDescriptor&&(await this.tokenizer.readToken(Dx)).signature!==134695760)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-Dx.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let o=t(n);if(o.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let i=await this.readLocalFileHeader();if(i){await this.tokenizer.ignore(i.extraFieldLength);let s=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(s),await this.inflate(i,s,o.handler)}}if(o.stop)break}}async inflate(e,t,n){if(e.compressedMethod===0)return n(t);if(e.compressedMethod!==8)throw new Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);oi(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let o=await r.decompressDeflateRaw(t);return n(o)}static async decompressDeflateRaw(e){let t=new ReadableStream({start(i){i.enqueue(e),i.close()}}),n=new DecompressionStream("deflate-raw"),o=t.pipeThrough(n);try{let s=await new Response(o).arrayBuffer();return new Uint8Array(s)}catch(i){let s=i instanceof Error?`Failed to deflate ZIP entry: ${i.message}`:"Unknown decompression error in ZIP entry";throw new TypeError(s)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(et);if(e===Mc.LocalFileHeader){let t=await this.tokenizer.readToken(RM);return t.filename=await this.tokenizer.readToken(new Ar(t.filenameLength,"utf-8")),t}if(e===Mc.CentralFileHeader)return!1;throw e===3759263696?new Error("Encrypted ZIP"):new Error("Unexpected signature")}};function vte(r,e){let t=r.length,n=e.length;if(n>t)return-1;for(let o=0;o<=t-n;o++){let i=!0;for(let s=0;s<n;s++)if(r[o+s]!==e[s]){i=!1;break}if(i)return o}return-1}function Ste(r){let e=r.reduce((o,i)=>o+i.length,0),t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var bp=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let n=new Uint8Array(1024),o=await e.readBuffer(n,{mayBeLess:!0});if(o===0){t.close();return}t.enqueue(n.subarray(0,o))}}).pipeThrough(new DecompressionStream("gzip"))}};var Ate=Object.prototype.toString,Tte="[object Uint8Array]";function _te(r,e,t){return r?r.constructor===e?!0:Ate.call(r)===t:!1}function Cte(r){return _te(r,Uint8Array,Tte)}function Ite(r){if(!Cte(r))throw new TypeError(`Expected \`Uint8Array\`, got \`${typeof r}\``)}function OM(r,e){if(r.length===0)return new Uint8Array(0);e??=r.reduce((o,i)=>o+i.length,0);let t=new Uint8Array(e),n=0;for(let o of r)Ite(o),t.set(o,n),n+=o.length;return t}var Nje={utf8:new globalThis.TextDecoder("utf8")};var Oje=new globalThis.TextEncoder;var Bje=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Nx(r){let{byteLength:e}=r;if(e===6)return r.getUint16(0)*2**32+r.getUint32(2);if(e===5)return r.getUint8(0)*2**32+r.getUint32(1);if(e===4)return r.getUint32(0);if(e===3)return r.getUint8(0)*2**16+r.getUint16(1);if(e===2)return r.getUint16(0);if(e===1)return r.getUint8(0)}function BM(r,e){if(e==="utf-16le"){let t=[];for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);t.push(o&255,o>>8&255)}return t}if(e==="utf-16be"){let t=[];for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);t.push(o>>8&255,o&255)}return t}return[...r].map(t=>t.charCodeAt(0))}function MM(r,e=0){let t=Number.parseInt(new Ar(6).get(r,148).replace(/\0.*$/v,"").trim(),8);if(Number.isNaN(t))return!1;let n=256;for(let o=e;o<e+148;o++)n+=r[o];for(let o=e+156;o<e+512;o++)n+=r[o];return t===n}var FM={get:(r,e)=>r[e+3]&127|(r[e+2]&127)<<7|(r[e+1]&127)<<14|(r[e]&127)<<21,len:4};var UM=["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ttc","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk","drc","lz4","potx","xltx","dotx","xltm","ott","ots","otp","odg","otg","xlsm","docm","dotm","potm","pptm","jar","jmp","rm","sav","ppsm","ppsx","tar.gz","reg","dat","key","numbers","pages"],$M=["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.ms-powerpoint.slideshow.macroenabled.12","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.slideshow","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/vnd.apache.arrow.file","video/mp4","audio/midi","video/matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","font/collection","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x-ms-shortcut","application/x-ft-apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/vnd.apache.parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x-ft-fbx","application/vnd.visio","application/vnd.android.package-archive","application/x-ft-draco","application/x-lz4","application/vnd.openxmlformats-officedocument.presentationml.template","application/vnd.openxmlformats-officedocument.spreadsheetml.template","application/vnd.openxmlformats-officedocument.wordprocessingml.template","application/vnd.ms-excel.template.macroenabled.12","application/vnd.oasis.opendocument.text-template","application/vnd.oasis.opendocument.spreadsheet-template","application/vnd.oasis.opendocument.presentation-template","application/vnd.oasis.opendocument.graphics","application/vnd.oasis.opendocument.graphics-template","application/vnd.ms-excel.sheet.macroenabled.12","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-word.template.macroenabled.12","application/vnd.ms-powerpoint.template.macroenabled.12","application/vnd.ms-powerpoint.presentation.macroenabled.12","application/java-archive","application/vnd.rn-realmedia","application/x-spss-sav","application/x-ms-regedit","application/x-ft-windows-registry-hive","application/x-jmp-data","application/vnd.apple.keynote","application/vnd.apple.numbers","application/vnd.apple.pages"];var kn=class extends Error{};function L4(r,e,t){if(!Number.isFinite(r)||r<0||r>e)throw new kn(`${t} has invalid size ${r} (maximum ${e} bytes)`);return r}async function Rn(r,e,{maximumLength:t=16777216,reason:n="skip"}={}){let o=L4(e,t,n);await r.ignore(o)}async function xp(r,e,t,{maximumLength:n=e.length,reason:o="read"}={}){let i=t?.length??e.length,s=L4(i,n,o);return r.readBuffer(e,{...t,length:s})}function Yn(r,e,t){t={offset:0,...t};for(let[n,o]of e.entries())if(t.mask){if(o!==(t.mask[n]&r[n+t.offset]))return!1}else if(o!==r[n+t.offset])return!1;return!0}function St(r){let e=r.fileInfo.size;return!Number.isFinite(e)||e===Number.MAX_SAFE_INTEGER}function zi(r,e,t){return St(r)&&r.position-e>t}var Gi=1024*1024,HM=1024,kte=2**31-1,qM=Gi,Rte=new Set(["Unexpected signature","Encrypted ZIP","Expected Central-File-Header signature"]),Pte=["ZIP entry count exceeds ","Unsupported ZIP compression method:","ZIP entry compressed data exceeds ","ZIP entry decompressed data exceeds ","Expected data-descriptor-signature at position "],Dte=new Set(["Z_BUF_ERROR","Z_DATA_ERROR","ERR_INVALID_STATE"]);async function Lte(r,{maximumLength:e=Gi}={}){let o=new ReadableStream({start(l){l.enqueue(r),l.close()}}).pipeThrough(new DecompressionStream("deflate-raw")).getReader(),i=[],s=0;try{for(;;){let{done:l,value:u}=await o.read();if(l)break;if(s+=u.length,s>e)throw await o.cancel(),new Error(`ZIP entry decompressed data exceeds ${e} bytes`);i.push(u)}}finally{o.releaseLock()}let a=new Uint8Array(s),c=0;for(let l of i)a.set(l,c),c+=l.length;return a}function Nte(r,e){let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function Ote(r){let e=r.fileInfo.size,t=Number.isFinite(e)?Math.max(0,e-r.position):Number.MAX_SAFE_INTEGER;return Math.min(t,kte)}function Bte(r){if(r instanceof Se||r instanceof kn)return!0;if(!(r instanceof Error))return!1;if(Rte.has(r.message)||Dte.has(r.code))return!0;for(let e of Pte)if(r.message.startsWith(e))return!0;return!1}function VM(r,e=Gi){let t=[r.compressedSize,r.uncompressedSize];for(let n of t)if(!Number.isFinite(n)||n<0||n>e)return!1;return!0}function Mte(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function Fte(r,e){e==="Index/Document.iwa"&&(r.hasDocumentEntry=!0),e.startsWith("Index/MasterSlide")&&(r.hasMasterSlideEntry=!0),e.startsWith("Index/Tables/")&&(r.hasTablesEntry=!0),e==="Index/CalculationEngine.iwa"&&(r.hasCalculationEngineEntry=!0)}function KM(r){if(r.hasDocumentEntry)return r.hasMasterSlideEntry?{ext:"key",mime:"application/vnd.apple.keynote"}:r.hasTablesEntry?{ext:"numbers",mime:"application/vnd.apple.numbers"}:{ext:"pages",mime:"application/vnd.apple.pages"}}function zM(r){switch(r=r.toLowerCase(),r){case"application/epub+zip":return{ext:"epub",mime:r};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:r};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:r};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:r};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:r};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:r};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:r};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:r};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:r};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:r};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:r};case"application/vnd.ms-excel.sheet.macroenabled":return{ext:"xlsm",mime:"application/vnd.ms-excel.sheet.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":return{ext:"xltx",mime:r};case"application/vnd.ms-excel.template.macroenabled":return{ext:"xltm",mime:"application/vnd.ms-excel.template.macroenabled.12"};case"application/vnd.ms-powerpoint.slideshow.macroenabled":return{ext:"ppsm",mime:"application/vnd.ms-powerpoint.slideshow.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return{ext:"docx",mime:r};case"application/vnd.ms-word.document.macroenabled":return{ext:"docm",mime:"application/vnd.ms-word.document.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.template":return{ext:"dotx",mime:r};case"application/vnd.ms-word.template.macroenabledtemplate":return{ext:"dotm",mime:"application/vnd.ms-word.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.template":return{ext:"potx",mime:r};case"application/vnd.ms-powerpoint.template.macroenabled":return{ext:"potm",mime:"application/vnd.ms-powerpoint.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return{ext:"pptx",mime:r};case"application/vnd.ms-powerpoint.presentation.macroenabled":return{ext:"pptm",mime:"application/vnd.ms-powerpoint.presentation.macroenabled.12"};case"application/vnd.ms-visio.drawing":return{ext:"vsdx",mime:"application/vnd.visio"};case"application/vnd.ms-package.3dmanufacturing-3dmodel+xml":return{ext:"3mf",mime:"model/3mf"};default:}}function Ute(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function $te(r,e){e.startsWith("word/")&&(r.hasWordDirectory=!0),e.startsWith("ppt/")&&(r.hasPresentationDirectory=!0),e.startsWith("xl/")&&(r.hasSpreadsheetDirectory=!0),e.startsWith("3D/")&&e.endsWith(".model")&&(r.hasThreeDimensionalModelEntry=!0)}function WM(r){if(r.hasWordDirectory)return{ext:"docx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};if(r.hasPresentationDirectory)return{ext:"pptx",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};if(r.hasSpreadsheetDirectory)return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};if(r.hasThreeDimensionalModelEntry)return{ext:"3mf",mime:"model/3mf"}}function GM(r){if(!(!r.hasContentTypesEntry||r.hasUnparseableContentTypes||r.isParsingContentTypes||r.hasParsedContentTypesEntry))return WM(r)}function Hte(r){let e=r.indexOf('.main+xml"');if(e===-1){let o="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";return r.includes(`ContentType="${o}"`)?o:void 0}let t=r.slice(0,e),n=t.lastIndexOf('"');return t.slice(n+1)}var jM=134695760,N4=16,qte=N4-1;function Vte(r,e){if(r.length<N4)return-1;let t=r.length-N4;for(let n=0;n<=t;n++)if(et.get(r,n)===jM&&et.get(r,n+8)===e+n)return n;return-1}async function Kte(r,{shouldBuffer:e,maximumLength:t=Gi}={}){let{syncBuffer:n}=r,{length:o}=n,i=[],s=0;for(;;){let a=await r.tokenizer.peekBuffer(n,{mayBeLess:!0}),c=Vte(n.subarray(0,a),s),l=c>=0?0:a===o?Math.min(qte,a-1):0,u=c>=0?c:a-l;if(u===0)break;if(s+=u,s>t)throw new Error(`ZIP entry compressed data exceeds ${t} bytes`);if(e){let d=new Uint8Array(u);await r.tokenizer.readBuffer(d),i.push(d)}else await r.tokenizer.ignore(u);if(c>=0)break}if(St(r.tokenizer)||(r.knownSizeDescriptorScannedBytes+=s),!!e)return Nte(i,s)}function zte(r,e){return St(r.tokenizer)?Math.max(0,16777216-(r.tokenizer.position-e)):Math.max(0,Gi-r.knownSizeDescriptorScannedBytes)}async function Gte(r,e,{shouldBuffer:t,maximumDescriptorLength:n=Gi}={}){if(e.dataDescriptor&&e.compressedSize===0)return Kte(r,{shouldBuffer:t,maximumLength:n});if(!t){await Rn(r.tokenizer,e.compressedSize,{maximumLength:St(r.tokenizer)?Gi:r.tokenizer.fileInfo.size,reason:"ZIP entry compressed data"});return}let o=Ote(r.tokenizer);if(!Number.isFinite(e.compressedSize)||e.compressedSize<0||e.compressedSize>o)throw new Error(`ZIP entry compressed data exceeds ${o} bytes`);let i=new Uint8Array(e.compressedSize);return await r.tokenizer.readBuffer(i),i}Fc.prototype.inflate=async function(r,e,t){if(r.compressedMethod===0)return t(e);if(r.compressedMethod!==8)throw new Error(`Unsupported ZIP compression method: ${r.compressedMethod}`);let n=await Lte(e,{maximumLength:Gi});return t(n)};Fc.prototype.unzip=async function(r){let e=!1,t=0,n=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(zi(this.tokenizer,n,16777216))throw new kn(`ZIP stream probing exceeds ${16777216} bytes`);let o=await this.readLocalFileHeader();if(!o)break;if(t++,t>HM)throw new Error(`ZIP entry count exceeds ${HM}`);let i=r(o);e=!!i.stop,await this.tokenizer.ignore(o.extraFieldLength);let s=await Gte(this,o,{shouldBuffer:!!i.handler,maximumDescriptorLength:Math.min(Gi,zte(this,n))});if(i.handler&&await this.inflate(o,s,i.handler),o.dataDescriptor){let a=new Uint8Array(N4);if(await this.tokenizer.readBuffer(a),et.get(a,0)!==jM)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-a.length}`)}if(zi(this.tokenizer,n,16777216))throw new kn(`ZIP stream probing exceeds ${16777216} bytes`)}while(!e)};async function YM(r){let e,t=Ute(),n=Mte();try{await new Fc(r).unzip(i=>{if($te(t,i.filename),Fte(n,i.filename),n.hasDocumentEntry&&(n.hasMasterSlideEntry||n.hasTablesEntry))return e=KM(n),{stop:!0};let s=i.filename==="[Content_Types].xml",a=GM(t);if(!s&&a)return e=a,{stop:!0};switch(i.filename){case"META-INF/mozilla.rsa":return e={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return e={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return VM(i,qM)?{async handler(c){let l=new TextDecoder("utf-8").decode(c).trim();e=zM(l)},stop:!0}:{};case"[Content_Types].xml":return t.hasContentTypesEntry=!0,VM(i,qM)?(t.isParsingContentTypes=!0,{async handler(c){let l=new TextDecoder("utf-8").decode(c),u=Hte(l);u&&(e=zM(u)),t.hasParsedContentTypesEntry=!0,t.isParsingContentTypes=!1},stop:!0}):(t.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/v.test(i.filename)?(e={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}})}catch(i){if(!Bte(i))throw i;t.isParsingContentTypes&&(t.isParsingContentTypes=!1,t.hasUnparseableContentTypes=!0),!e&&i instanceof Se&&!t.hasContentTypesEntry&&(e=WM(t))}let o=St(r)&&n.hasDocumentEntry&&!n.hasMasterSlideEntry&&!n.hasTablesEntry&&!n.hasCalculationEngineEntry?void 0:KM(n);return e??GM(t)??o??{ext:"zip",mime:"application/zip"}}var XM=64,QM=1024*1024,Wte=256;async function ZM(r){async function e(){let a=await r.peekNumber(bM),c=128,l=0;for(;(a&c)===0&&c!==0;)++l,c>>=1;let u=new Uint8Array(l+1);return await xp(r,u,void 0,{maximumLength:u.length,reason:"EBML field"}),u}async function t(){let a=await e(),c=await e();c[0]^=128>>c.length-1;let l=Math.min(6,c.length),u=new DataView(a.buffer),d=new DataView(c.buffer,c.length-l,l);return{id:Nx(u),len:Nx(d)}}async function n(a){let c=0;for(;a>0;){if(c++,c>Wte||zi(r,i,16777216))return;let l=r.position,u=await t();if(u.id===17026){if(u.len>XM)return;let d=L4(u.len,XM,"EBML DocType");return(await r.readToken(new Ar(d))).replaceAll(/\0.*$/gv,"")}if(St(r)&&(!Number.isFinite(u.len)||u.len<0||u.len>QM)||(await Rn(r,u.len,{maximumLength:St(r)?QM:r.fileInfo.size,reason:"EBML payload"}),--a,r.position<=l))return}}let o=await t(),i=r.position;switch(await n(o.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/matroska"};default:}}var jte=512,Yte=16*1024*1024,JM=1024*1024;function Xte(r){return(r.codePointAt(0)&32)!==0}async function eF(r){let e={ext:"png",mime:"image/png"},t={ext:"apng",mime:"image/apng"};await r.ignore(8);async function n(){return{length:await r.readToken(xM),type:await r.readToken(new Ar(4,"latin1"))}}let o=St(r),i=r.position,s=0,a=!1;do{if(s++,s>jte||zi(r,i,Yte))break;let c=r.position,l=await n();if(l.length<0)return;if(l.type==="IHDR"){if(l.length!==13)return;a=!0}switch(l.type){case"IDAT":return e;case"acTL":return t;default:if(!a&&l.type!=="CgBI")return;if(o&&l.length>JM)return a&&Xte(l.type)?e:void 0;try{await Rn(r,l.length+4,{maximumLength:o?JM+4:r.fileInfo.size,reason:"PNG chunk payload"})}catch(u){if(!o&&(u instanceof kn||u instanceof Se))return e;throw u}}if(r.position<=c)break}while(r.position+8<r.fileInfo.size);return e}var Qte=512,tF=1024*1024;async function rF(r){let e=!1;try{async function t(){let s=new Uint8Array(16);return await xp(r,s,void 0,{maximumLength:s.length,reason:"ASF header GUID"}),{id:s,size:Number(await r.readToken(EM))}}await Rn(r,30,{maximumLength:30,reason:"ASF header prelude"});let n=St(r),o=r.position,i=0;for(;r.position+24<r.fileInfo.size&&(i++,!(i>Qte||zi(r,o,16777216)));){let s=r.position,a=await t(),c=a.size-24;if(!Number.isFinite(c)||c<0){e=!0;break}if(Yn(a.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let l=new Uint8Array(16);if(c-=await xp(r,l,void 0,{maximumLength:l.length,reason:"ASF stream type GUID"}),Yn(l,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(Yn(l,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}if(n&&c>tF){e=!0;break}if(await Rn(r,c,{maximumLength:n?tF:r.fileInfo.size,reason:"ASF header payload"}),r.position<=s){e=!0;break}}}catch(t){if(t instanceof Se||t instanceof kn)St(r)&&(e=!0);else throw t}if(!e)return{ext:"asf",mime:"application/vnd.ms-asf"}}var Ep=4100,Zte=Ep-2,Jte=16777216,ere=1,nF=100,Ox=16777216,tre=512,oF=256,rre=1024*1024,iF=16777216;function nre(r){return Number.isFinite(r)?Math.max(1,Math.trunc(r)):Ep}function ore(r){return Number.isFinite(r)?Math.max(0,Math.min(Zte,Math.trunc(r))):0}function ire(r){return Number.isFinite(r)?Math.max(0,r):Number.MAX_SAFE_INTEGER}function sF(r){return import(r)}function sre(r){return r.pipeThrough(new TransformStream)}function aF(r,e){return e===void 0?r.read():(e.throwIfAborted(),Promise.race([r.read(),new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason),r.cancel(e.reason).catch(()=>{})},{once:!0})})]))}function are(r,e){let t=r.getReader(),n=0,o=!1,i=!1,s=async a=>{o||i||(i=!0,await t.cancel(a))};return new ReadableStream({async pull(a){if(n>=e){a.close(),await s();return}let{done:c,value:l}=await t.read();if(c||!l){o=!0,a.close();return}let u=e-n;if(l.length>u){a.enqueue(l.subarray(0,u)),n+=u,a.close(),await s();return}a.enqueue(l),n+=l.length},async cancel(a){await s(a)}})}async function cF(r,e){return new Bx(e).fromBuffer(r)}var Bx=class r{constructor(e){let t=ore(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return vM(sre(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let n=e.position;for(let o of this.detectors){let i;try{i=await o.detect(e)}catch(s){if(s instanceof Se||s instanceof kn)return;throw s}if(i)return i;if(n!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(SM(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=AM(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:n}]=await Promise.all([sF("node:fs/promises"),sF("strtok3")]),o=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),i=await o.stat();if(!i.isFile()){await o.close();return}let s=new n(o,{...this.getTokenizerOptions(),fileInfo:{path:e,size:i.size}});return this.fromTokenizer(s)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let n=nre(t?.sampleSize??Ep),o,i=!1,s=e.getReader(),a=[],c=0;try{for(;c<n;){let{value:d,done:f}=await aF(s,this.options.signal);if(f||!d){i=!0;break}a.push(d),c+=d.length}if(!i&&c===n){let{value:d,done:f}=await aF(s,this.options.signal);f||!d?i=!0:(a.push(d),c+=d.length)}}finally{s.releaseLock()}if(c>0){let d=a.length===1?a[0]:OM(a);try{o=await this.fromBuffer(d.subarray(0,n))}catch(f){if(!(f instanceof Se))throw f;o=void 0}!i&&o?.ext==="pages"&&(o={ext:"zip",mime:"application/zip"})}let l=new TransformStream({start(d){for(let f of a)d.enqueue(f)},transform(d,f){f.enqueue(d)}}),u=e.pipeThrough(l);return u.fileType=o,u}async detectGzip(e){if(this.gzipProbeDepth>=ere)return{ext:"gz",mime:"application/gzip"};let t=new bp(e),n=are(t.inflate(),Jte),o=St(e),i,s,a,c;if(o){let l=new AbortController;i=setTimeout(()=>{l.abort(new DOMException(`Operation timed out after ${nF} ms`,"TimeoutError"))},nF),s=this.options.signal===void 0?l.signal:AbortSignal.any([this.options.signal,l.signal]),a=new r({...this.options,signal:s}),a.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{c=await(a??this).fromStream(n)}catch(l){if(l?.name==="AbortError"&&s?.reason?.name!=="TimeoutError")throw l}finally{clearTimeout(i),o||this.gzipProbeDepth--}return c?.ext==="tar"?{ext:"tar.gz",mime:"application/gzip"}:{ext:"gz",mime:"application/gzip"}}check(e,t){return Yn(this.buffer,e,t)}checkString(e,t){return this.check(BM(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(Ep),e.fileInfo.size===void 0&&(e.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=e,St(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.detectionReentryCount>=oF?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await Rn(e,6,{maximumLength:6,reason:"ID3 header prefix"});let t=await e.readToken(FM),n=St(e);if(!Number.isFinite(t)||t<0||n&&(t>Ox||e.position+t>Ox))return;if(e.position+t>e.fileInfo.size)return n?void 0:{ext:"mp3",mime:"audio/mpeg"};try{await Rn(e,t,{maximumLength:n?Ox:e.fileInfo.size,reason:"ID3 payload"})}catch(o){if(o instanceof Se)return;throw o}return this.detectionReentryCount>=oF?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4]))return YM(e);if(this.checkString("OggS")){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),Yn(t,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:Yn(t,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Yn(t,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Yn(t,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Yn(t,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Yn(t,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:"zip",mime:"application/zip"};if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF"))return{ext:"pdf",mime:"application/pdf"};if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){let t=await this.readTiffHeader(!1);if(t)return t}if(this.check([77,77])){let t=await this.readTiffHeader(!0);if(t)return t}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163]))return ZM(e);if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1")||this.checkString("PARE"))return{ext:"parquet",mime:"application/vnd.apache.parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([4,34,77,24]))return{ext:"lz4",mime:"application/x-lz4"};if(this.checkString("regf"))return{ext:"dat",mime:"application/x-ft-windows-registry-hive"};if(this.checkString("$FL2")||this.checkString("$FL3"))return{ext:"sav",mime:"application/x-spss-sav"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString(String.raw`{\rtf`))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190])){let t=Rx.get(this.buffer,4),n=Lc.get(this.buffer,6);if(t>0&&t<=30)return{ext:"macho",mime:"application/x-mach-binary"};if(n>30)return{ext:"class",mime:"application/java-vm"}}if(this.checkString(".RMF"))return{ext:"rm",mime:"application/vnd.rn-realmedia"};if(this.checkString("DRACO"))return{ext:"drc",mime:"application/x-ft-draco"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){let t=new Ar(4,"latin1").get(this.buffer,2);if(/^\d+$/v.test(t)&&t>=1e3&&t<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>"))return await e.ignore(8),await e.readToken(new Ar(13,"ascii"))==="debian-binary"?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"};if(this.checkString("WEBVTT")&&[`
110
+ `).filter(o=>(o=o.trim(),o!==""&&!o.startsWith("#"))).map(o=>{let[i,s,a]=o.split(/\s+/).map(f=>f.trim());if(a!=null&&a!==""&&!a.match(/^\d+$/))throw new sp("Invalid status code in _redirects file");let c=parseInt(a);if(isNaN(c)&&(c=301),!zee.includes(c))throw new ap(`Status code ${c} is not allowed`);let l=new Set,u=i.split("/"),d=u.map((f,h)=>{if(f.startsWith(":")){let p=f.substring(1);if(l.has(p))throw new cp("Duplicate placeholders in from path");return l.add(p),`(?<${p}>[^/]+)`}return f==="*"&&h===u.length-1?"(?<splat>.+)":(0,fM.default)(f)}).join("\\/");return{from:new RegExp(d),to:s,status:c}});for(let{from:o,to:i,status:s}of n){let a=r.pathname.match(o);if(a!=null)return Gee(r,i,s,a.groups,t)}}catch(n){return new Response(JSON.stringify(kc(n),null,2),{status:500})}}function Gee(r,e,t,n,o={}){if(o.redirect==="error")throw new TypeError("Failed to fetch");if(n!=null)for(let[c,l]of Object.entries(n))e=e.replaceAll(`:${c}`,l);let i=Wee(r,new URL(`${r.protocol}//${r.host}${e}`)),s=new URL(`${r.protocol}//${r.host}${e}`),a=new URL(`${r.protocol}//${r.host}${s.pathname}${jee(i)}${r.hash}`);return o.redirect==="manual"?new Response("",{status:t,headers:{location:a.toString()}}):a}function Wee(r,e){let t={};for(let[n,o]of r.searchParams)e.searchParams.delete(n),dM(n,o,t);for(let[n,o]of e.searchParams)dM(n,o,t);return t}function dM(r,e,t){typeof t[r]=="string"&&(t[r]=[t[r]]),Array.isArray(t[r])?t[r].push(e):t[r]=e}function jee(r){let e=[...Object.entries(r)].map(([t,n])=>(Array.isArray(n)||(n=[n]),n.map(o=>`${encodeURIComponent(t)}=${encodeURIComponent(o)}`).join("&"))).join("&");return e===""?e:`?${e}`}var zu=class{headers;constructor(){this.headers=[]}getHeader(){return this.headers.join(",")}async time(e,t,n){let o=performance.now();try{return await n}finally{let s=performance.now()-o;this.add(e,t,s)}}add(e,t,n){this.headers.push(`${e};dur=${Math.round(n)}${t===""?"":`;desc="${t}"`}`)}};var Yee=29030400;function Xee(r){return{cid:r,name:r.toString(),path:r.toString(),roots:[r],remainder:[]}}var S4=class{log;components;blockstoreSessions;constructor(e,t={}){this.components=e,this.log=e.helia.logger.forComponent("helia-verified-fetch:url-resolver"),this.blockstoreSessions=new Xs({maxSize:t.sessionCacheSize??100,maxAge:t.sessionTTLms??6e4,onEviction:(n,o)=>{o.close()}})}async resolve(e,t=new zu,n={}){if(e.protocol==="ipfs:")return this.resolveIPFSPath(e,t,n);if(e.protocol==="ipns:")return this.resolveIPNSName(e,t,n);if(e.protocol==="dnslink:")return this.resolveDNSLink(e,t,n);throw new Gn(`Invalid resource. Unsupported protocol in URL, must be ipfs:, ipns:, or dnslink: ${e}`)}async getBlockstore(e,t={}){if(t.session===!1)return this.components.helia.blockstore;let n=`ipfs:${e}`,o=this.blockstoreSessions.get(n),i=!1;if(o==null&&(this.log("create session with %d initial providers for root %c",t.providers?.length??0,e),i=!0,o=this.components.helia.blockstore.createSession(e,t),this.blockstoreSessions.set(n,o)),!i&&t.providers!=null&&t.providers.length>0){this.log("adding %d providers to existing session for root %c",t.providers.length,e);try{let s=await Promise.all(t.providers.map(async a=>{await o.addPeer(a,t)})??[]);this.log("result was %o",s)}catch(s){this.log.error("could not add provs - %e",s)}}return o}async resolveDNSLink(e,t,n){let i=(await t.time(In("dnsLink.resolve"),"",this.components.dnsLink.resolve(e.hostname,n)))?.[0];if(i==null)throw new TypeError(`Invalid resource. Cannot resolve DNSLink from domain: ${e.hostname}`);let s,a=pM(`${i.path}/${e.pathname}`);if(i.namespace==="ipns"){let c=new URL(`ipns://${i.peerId}${a}`);s=await this.resolveIPNSName(c,t,n)}else if(i.namespace==="ipfs"){let c=new URL(`ipfs://${i.cid}${a}`);s=await this.resolveIPFSPath(c,t,n)}else throw new TypeError(`Invalid resource. Unexpected DNSLink namespace ${i.namespace} from domain: ${e.hostname}`);return s instanceof Response?s:{...s,url:e,ttl:i.answer.TTL}}async resolveIPNSName(e,t,n){let o=Ee(e.hostname),i=await t.time(In("ipns.resolve"),"",this.components.ipnsResolver.resolve(o,n)),s=pM(`${i.path??""}/${e.pathname}`),a=new URL(`ipfs://${i.cid}${s}`),c=await this.resolveIPFSPath(a,t,n);if(c instanceof Response)return c;let l;return i.record.validityType==="EOL"&&(l=new Date(i.record.validity)),{...c,url:e,ttl:Math.round(Number((i.record.ttl??0n)/BigInt(1e9))),expires:l}}async resolveIPFSPath(e,t,n){let o=await t.time(In("ipfs.resolve"),"",this.walkPath(e,n));if(o instanceof Response)return o;if(o.terminalElement.cid.code===114){let i=new URL(`ipns://${Lr(o.terminalElement.cid)}`),s=await this.resolveIPNSName(i,t,n);return s instanceof Response?s:{...s,url:e}}return{...o,url:e,ttl:Yee,blockstore:o.blockstore}}async walkPath(e,t={}){let n;try{n=F.parse(e.hostname)}catch(i){throw new Gn(`Could not parse CID - ${i}`)}let o=await this.getBlockstore(n,t);try{let i=[],s,a=Qee(e);for await(let c of Js(a,o,{...t,yieldSubShards:!0}))i.push(c.cid),s=c;if(s==null)throw new e4("No terminal element found");return{ipfsRoots:i,terminalElement:s,blockstore:o,redirected:t.redirected===!0}}catch(i){if(i.name==="NotFoundError"&&t.redirected!==!0){let s;try{s=await jn(`${n}/_redirects`,o,t)}catch(a){if(a.name!=="NotFoundError")throw a}if(s?.type==="file"||s?.type==="raw"){let a=de(await ue(s.content(t))),c=hM(e,a,t);if(c instanceof Response)return c;if(c instanceof URL)return this.walkPath(c,{...t,redirected:!0})}}if(i.name==="NoResolverError")return{ipfsRoots:[n],terminalElement:Xee(n),blockstore:o,redirected:!1};throw i}}};function Qee(r){let e=r.pathname.split("/").map(t=>decodeURIComponent(t)).join("/").trim();return e.length>0&&!e.startsWith("/")&&(e=`/${e}`),r.protocol==="ipns:"&&e==="/"&&(e=""),`/${r.protocol==="ipfs:"?"ipfs":"ipns"}/${r.hostname}${e}`}function pM(r){return r=r.split("/").map(e=>e.trim()).filter(Boolean).join("/"),r!==""?`/${r}`:""}var wM=Yt(mM(),1);var gM={128:"\u20AC",130:"\u201A",131:"\u0192",132:"\u201E",133:"\u2026",134:"\u2020",135:"\u2021",136:"\u02C6",137:"\u2030",138:"\u0160",139:"\u2039",140:"\u0152",142:"\u017D",145:"\u2018",146:"\u2019",147:"\u201C",148:"\u201D",149:"\u2022",150:"\u2013",151:"\u2014",152:"\u02DC",153:"\u2122",154:"\u0161",155:"\u203A",156:"\u0153",158:"\u017E",159:"\u0178"},Zee={};for(let[r,e]of Object.entries(gM))Zee[e]=Number.parseInt(r,10);var A4;function Jee(){if(!(typeof globalThis.TextDecoder>"u"))return A4??(A4=new globalThis.TextDecoder("utf-8"))}var Gu=32*1024,Co=65533;function yM(r,e="utf-8"){switch(e.toLowerCase()){case"utf-8":case"utf8":{let t=Jee();return t?t.decode(r):tte(r)}case"utf-16le":return rte(r);case"us-ascii":case"ascii":return nte(r);case"latin1":case"iso-8859-1":return ote(r);case"windows-1252":return ite(r);default:throw new RangeError(`Encoding '${e}' not supported`)}}function kx(r,e){e.length!==0&&(r.push(String.fromCharCode.apply(null,e)),e.length=0)}function kt(r,e,t){e.push(t),e.length>=Gu&&kx(r,e)}function ete(r,e,t){if(t<=65535){kt(r,e,t);return}t-=65536,kt(r,e,55296+(t>>10)),kt(r,e,56320+(t&1023))}function tte(r){let e=[],t=[],n=0;for(r.length>=3&&r[0]===239&&r[1]===187&&r[2]===191&&(n=3);n<r.length;){let o=r[n];if(o<=127){kt(e,t,o),n++;continue}if(o<194||o>244){kt(e,t,Co),n++;continue}if(o<=223){if(n+1>=r.length){kt(e,t,Co),n++;continue}let u=r[n+1];if((u&192)!==128){kt(e,t,Co),n++;continue}let d=(o&31)<<6|u&63;kt(e,t,d),n+=2;continue}if(o<=239){if(n+2>=r.length){kt(e,t,Co),n++;continue}let u=r[n+1],d=r[n+2];if(!((u&192)===128&&(d&192)===128&&!(o===224&&u<160)&&!(o===237&&u>=160))){kt(e,t,Co),n++;continue}let h=(o&15)<<12|(u&63)<<6|d&63;kt(e,t,h),n+=3;continue}if(n+3>=r.length){kt(e,t,Co),n++;continue}let i=r[n+1],s=r[n+2],a=r[n+3];if(!((i&192)===128&&(s&192)===128&&(a&192)===128&&!(o===240&&i<144)&&!(o===244&&i>143))){kt(e,t,Co),n++;continue}let l=(o&7)<<18|(i&63)<<12|(s&63)<<6|a&63;ete(e,t,l),n+=4}return kx(e,t),e.join("")}function rte(r){let e=[],t=[],n=r.length,o=0;for(;o+1<n;){let i=r[o]|r[o+1]<<8;if(o+=2,i>=55296&&i<=56319){if(o+1<n){let s=r[o]|r[o+1]<<8;s>=56320&&s<=57343?(kt(e,t,i),kt(e,t,s),o+=2):kt(e,t,Co)}else kt(e,t,Co);continue}if(i>=56320&&i<=57343){kt(e,t,Co);continue}kt(e,t,i)}return o<n&&kt(e,t,Co),kx(e,t),e.join("")}function nte(r){let e=[];for(let t=0;t<r.length;t+=Gu){let n=Math.min(r.length,t+Gu),o=new Array(n-t);for(let i=t,s=0;i<n;i++,s++)o[s]=r[i]&127;e.push(String.fromCharCode.apply(null,o))}return e.join("")}function ote(r){let e=[];for(let t=0;t<r.length;t+=Gu){let n=Math.min(r.length,t+Gu),o=new Array(n-t);for(let i=t,s=0;i<n;i++,s++)o[s]=r[i];e.push(String.fromCharCode.apply(null,o))}return e.join("")}function ite(r){let e=[],t="";for(let n=0;n<r.length;n++){let o=r[n],i=o>=128&&o<=159?gM[o]:void 0;t+=i??String.fromCharCode(o),t.length>=Gu&&(e.push(t),t="")}return t&&e.push(t),e.join("")}function Xr(r){return new DataView(r.buffer,r.byteOffset)}var bM={len:1,get(r,e){return Xr(r).getUint8(e)},put(r,e,t){return Xr(r).setUint8(e,t),e+1}},ht={len:2,get(r,e){return Xr(r).getUint16(e,!0)},put(r,e,t){return Xr(r).setUint16(e,t,!0),e+2}},Lc={len:2,get(r,e){return Xr(r).getUint16(e)},put(r,e,t){return Xr(r).setUint16(e,t),e+2}};var et={len:4,get(r,e){return Xr(r).getUint32(e,!0)},put(r,e,t){return Xr(r).setUint32(e,t,!0),e+4}},Rx={len:4,get(r,e){return Xr(r).getUint32(e)},put(r,e,t){return Xr(r).setUint32(e,t),e+4}};var xM={len:4,get(r,e){return Xr(r).getInt32(e)},put(r,e,t){return Xr(r).setInt32(e,t),e+4}};var EM={len:8,get(r,e){return Xr(r).getBigUint64(e,!0)},put(r,e,t){return Xr(r).setBigUint64(e,t,!0),e+8}};var Ar=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return yM(n,this.encoding)}};var ste="End-Of-Stream",Se=class extends Error{constructor(){super(ste),this.name="EndOfStreamError"}},Nc=class extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Oc=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new Se;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let o=this.peekQueue.pop();if(!o)throw new Error("peekData should be defined");let i=Math.min(o.length,t);e.set(o.subarray(0,i),n),n+=i,t-=i,i<o.length&&this.peekQueue.push(o.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new Nc;let o=await this.readFromStream(e.subarray(n),t);if(o===0)break;n+=o}if(!t&&n<e.length)throw new Se;return n}};var T4=class extends Oc{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}};var wp=class extends T4{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}};var Wu=class extends Oc{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let o=await this.reader.read();if(o.done){this.endOfStream=!0;break}o.value&&(n+=this.writeChunk(e.subarray(n),o.value))}if(!t&&n===0&&this.endOfStream)throw new Se;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function Px(r){try{let e=r.getReader({mode:"byob"});return e instanceof ReadableStreamDefaultReader?new Wu(e):new wp(e)}catch(e){if(e instanceof TypeError)return new Wu(r.getReader());throw e}}var Ki=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new Se;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new Se;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new Se;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new Se;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw new RangeError("ignore length must be \u2265 0 bytes");if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};var cte=256e3,_4=class extends Ki{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),o=n.position-this.position;if(o>0)return await this.ignore(o),this.readBuffer(e,t);if(o<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new Se;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),o=0;if(n.position){let i=n.position-this.position;if(i>0){let s=new Uint8Array(n.length+i);return o=await this.peekBuffer(s,{mayBeLess:n.mayBeLess}),e.set(s.subarray(i)),o-i}if(i<0)throw new Error("Cannot peek from a negative offset in a stream")}if(n.length>0){try{o=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(i){if(t?.mayBeLess&&i instanceof Se)return 0;throw i}if(!n.mayBeLess&&o<n.length)throw new Se}return o}async ignore(e){if(e<0)throw new RangeError("ignore length must be \u2265 0 bytes");let t=Math.min(cte,e),n=new Uint8Array(t),o=0;for(;o<e;){let i=e-o,s=await this.readBuffer(n,{length:Math.min(t,i)});if(s<0)return s;o+=s}return o}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}};var C4=class extends Ki{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),o=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&o<n.length)throw new Se;return e.set(this.uint8Array.subarray(n.position,n.position+o)),o}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};var I4=class extends Ki{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),o=Math.min(this.blob.size-n.position,n.length);if(!n.mayBeLess&&o<n.length)throw new Se;let i=await this.blob.slice(n.position,n.position+o).arrayBuffer();return e.set(new Uint8Array(i)),o}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function vM(r,e){let t=Px(r),n=e??{},o=n.onClose;return n.onClose=async()=>{if(await t.close(),o)return o()},new _4(t,n)}function SM(r,e){return new C4(r,e)}function AM(r,e){return new I4(r,e)}var LM=Yt(kM(),1);var Mc={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},Dx={get(r){return{signature:et.get(r,0),compressedSize:et.get(r,8),uncompressedSize:et.get(r,12)}},len:16},RM={get(r){let e=ht.get(r,6);return{signature:et.get(r,0),minVersion:ht.get(r,4),dataDescriptor:!!(e&8),compressedMethod:ht.get(r,8),compressedSize:et.get(r,18),uncompressedSize:et.get(r,22),filenameLength:ht.get(r,26),extraFieldLength:ht.get(r,28),filename:null}},len:30},PM={get(r){return{signature:et.get(r,0),nrOfThisDisk:ht.get(r,4),nrOfThisDiskWithTheStart:ht.get(r,6),nrOfEntriesOnThisDisk:ht.get(r,8),nrOfEntriesOfSize:ht.get(r,10),sizeOfCd:et.get(r,12),offsetOfStartOfCd:et.get(r,16),zipFileCommentLength:ht.get(r,20)}},len:22},DM={get(r){let e=ht.get(r,8);return{signature:et.get(r,0),minVersion:ht.get(r,6),dataDescriptor:!!(e&8),compressedMethod:ht.get(r,10),compressedSize:et.get(r,20),uncompressedSize:et.get(r,24),filenameLength:ht.get(r,28),extraFieldLength:ht.get(r,30),fileCommentLength:ht.get(r,32),relativeOffsetOfLocalHeader:et.get(r,42),filename:null}},len:46};function NM(r){let e=new Uint8Array(et.len);return et.put(e,0,r),e}var oi=(0,LM.default)("tokenizer:inflate"),Lx=256*1024,Ete=NM(Mc.DataDescriptor),D4=NM(Mc.EndOfCentralDirectory),Fc=class r{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(Lx)}async isZip(){return await this.peekSignature()===Mc.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(et)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let o=n.length-4;o>=0;o--)if(n[o]===D4[0]&&n[o+1]===D4[1]&&n[o+2]===D4[2]&&n[o+3]===D4[3])return e.fileInfo.size-t+o;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){oi("Cannot reading central-directory without random-read support");return}oi("Reading central-directory...");let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){oi("Central-directory 32-bit signature found");let n=await this.tokenizer.readToken(PM,t),o=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let i=0;i<n.nrOfEntriesOfSize;++i){let s=await this.tokenizer.readToken(DM);if(s.signature!==Mc.CentralFileHeader)throw new Error("Expected Central-File-Header signature");s.filename=await this.tokenizer.readToken(new Ar(s.filenameLength,"utf-8")),await this.tokenizer.ignore(s.extraFieldLength),await this.tokenizer.ignore(s.fileCommentLength),o.push(s),oi(`Add central-directory file-entry: n=${i+1}/${o.length}: filename=${o[i].filename}`)}return this.tokenizer.setPosition(e),o}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let o=await this.readLocalFileHeader();if(!o)break;let i=e(o);n=!!i.stop;let s;if(await this.tokenizer.ignore(o.extraFieldLength),o.dataDescriptor&&o.compressedSize===0){let a=[],c=Lx;oi("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let l=-1;for(;l<0&&c===Lx;){c=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),l=vte(this.syncBuffer.subarray(0,c),Ete);let u=l>=0?l:c;if(i.handler){let d=new Uint8Array(u);await this.tokenizer.readBuffer(d),a.push(d)}else await this.tokenizer.ignore(u)}oi(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),i.handler&&await this.inflate(o,Ste(a),i.handler)}else i.handler?(oi(`Reading compressed-file-data: ${o.compressedSize} bytes`),s=new Uint8Array(o.compressedSize),await this.tokenizer.readBuffer(s),await this.inflate(o,s,i.handler)):(oi(`Ignoring compressed-file-data: ${o.compressedSize} bytes`),await this.tokenizer.ignore(o.compressedSize));if(oi(`Reading data-descriptor at pos=${this.tokenizer.position}`),o.dataDescriptor&&(await this.tokenizer.readToken(Dx)).signature!==134695760)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-Dx.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let o=t(n);if(o.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let i=await this.readLocalFileHeader();if(i){await this.tokenizer.ignore(i.extraFieldLength);let s=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(s),await this.inflate(i,s,o.handler)}}if(o.stop)break}}async inflate(e,t,n){if(e.compressedMethod===0)return n(t);if(e.compressedMethod!==8)throw new Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);oi(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let o=await r.decompressDeflateRaw(t);return n(o)}static async decompressDeflateRaw(e){let t=new ReadableStream({start(i){i.enqueue(e),i.close()}}),n=new DecompressionStream("deflate-raw"),o=t.pipeThrough(n);try{let s=await new Response(o).arrayBuffer();return new Uint8Array(s)}catch(i){let s=i instanceof Error?`Failed to deflate ZIP entry: ${i.message}`:"Unknown decompression error in ZIP entry";throw new TypeError(s)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(et);if(e===Mc.LocalFileHeader){let t=await this.tokenizer.readToken(RM);return t.filename=await this.tokenizer.readToken(new Ar(t.filenameLength,"utf-8")),t}if(e===Mc.CentralFileHeader)return!1;throw e===3759263696?new Error("Encrypted ZIP"):new Error("Unexpected signature")}};function vte(r,e){let t=r.length,n=e.length;if(n>t)return-1;for(let o=0;o<=t-n;o++){let i=!0;for(let s=0;s<n;s++)if(r[o+s]!==e[s]){i=!1;break}if(i)return o}return-1}function Ste(r){let e=r.reduce((o,i)=>o+i.length,0),t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var bp=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let n=new Uint8Array(1024),o=await e.readBuffer(n,{mayBeLess:!0});if(o===0){t.close();return}t.enqueue(n.subarray(0,o))}}).pipeThrough(new DecompressionStream("gzip"))}};var Ate=Object.prototype.toString,Tte="[object Uint8Array]";function _te(r,e,t){return r?r.constructor===e?!0:Ate.call(r)===t:!1}function Cte(r){return _te(r,Uint8Array,Tte)}function Ite(r){if(!Cte(r))throw new TypeError(`Expected \`Uint8Array\`, got \`${typeof r}\``)}function OM(r,e){if(r.length===0)return new Uint8Array(0);e??=r.reduce((o,i)=>o+i.length,0);let t=new Uint8Array(e),n=0;for(let o of r)Ite(o),t.set(o,n),n+=o.length;return t}var Nje={utf8:new globalThis.TextDecoder("utf8")};var Oje=new globalThis.TextEncoder;var Bje=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Nx(r){let{byteLength:e}=r;if(e===6)return r.getUint16(0)*2**32+r.getUint32(2);if(e===5)return r.getUint8(0)*2**32+r.getUint32(1);if(e===4)return r.getUint32(0);if(e===3)return r.getUint8(0)*2**16+r.getUint16(1);if(e===2)return r.getUint16(0);if(e===1)return r.getUint8(0)}function BM(r,e){if(e==="utf-16le"){let t=[];for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);t.push(o&255,o>>8&255)}return t}if(e==="utf-16be"){let t=[];for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);t.push(o>>8&255,o&255)}return t}return[...r].map(t=>t.charCodeAt(0))}function MM(r,e=0){let t=Number.parseInt(new Ar(6).get(r,148).replace(/\0.*$/v,"").trim(),8);if(Number.isNaN(t))return!1;let n=256;for(let o=e;o<e+148;o++)n+=r[o];for(let o=e+156;o<e+512;o++)n+=r[o];return t===n}var FM={get:(r,e)=>r[e+3]&127|(r[e+2]&127)<<7|(r[e+1]&127)<<14|(r[e]&127)<<21,len:4};var UM=["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ttc","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk","drc","lz4","potx","xltx","dotx","xltm","ott","ots","otp","odg","otg","xlsm","docm","dotm","potm","pptm","jar","jmp","rm","sav","ppsm","ppsx","tar.gz","reg","dat","key","numbers","pages"],$M=["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.ms-powerpoint.slideshow.macroenabled.12","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.slideshow","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/vnd.apache.arrow.file","video/mp4","audio/midi","video/matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","font/collection","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x-ms-shortcut","application/x-ft-apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/vnd.apache.parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x-ft-fbx","application/vnd.visio","application/vnd.android.package-archive","application/x-ft-draco","application/x-lz4","application/vnd.openxmlformats-officedocument.presentationml.template","application/vnd.openxmlformats-officedocument.spreadsheetml.template","application/vnd.openxmlformats-officedocument.wordprocessingml.template","application/vnd.ms-excel.template.macroenabled.12","application/vnd.oasis.opendocument.text-template","application/vnd.oasis.opendocument.spreadsheet-template","application/vnd.oasis.opendocument.presentation-template","application/vnd.oasis.opendocument.graphics","application/vnd.oasis.opendocument.graphics-template","application/vnd.ms-excel.sheet.macroenabled.12","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-word.template.macroenabled.12","application/vnd.ms-powerpoint.template.macroenabled.12","application/vnd.ms-powerpoint.presentation.macroenabled.12","application/java-archive","application/vnd.rn-realmedia","application/x-spss-sav","application/x-ms-regedit","application/x-ft-windows-registry-hive","application/x-jmp-data","application/vnd.apple.keynote","application/vnd.apple.numbers","application/vnd.apple.pages"];var kn=class extends Error{};function L4(r,e,t){if(!Number.isFinite(r)||r<0||r>e)throw new kn(`${t} has invalid size ${r} (maximum ${e} bytes)`);return r}async function Rn(r,e,{maximumLength:t=16777216,reason:n="skip"}={}){let o=L4(e,t,n);await r.ignore(o)}async function xp(r,e,t,{maximumLength:n=e.length,reason:o="read"}={}){let i=t?.length??e.length,s=L4(i,n,o);return r.readBuffer(e,{...t,length:s})}function Yn(r,e,t){t={offset:0,...t};for(let[n,o]of e.entries())if(t.mask){if(o!==(t.mask[n]&r[n+t.offset]))return!1}else if(o!==r[n+t.offset])return!1;return!0}function St(r){let e=r.fileInfo.size;return!Number.isFinite(e)||e===Number.MAX_SAFE_INTEGER}function zi(r,e,t){return St(r)&&r.position-e>t}var Gi=1024*1024,HM=1024,kte=2**31-1,qM=Gi,Rte=new Set(["Unexpected signature","Encrypted ZIP","Expected Central-File-Header signature"]),Pte=["ZIP entry count exceeds ","Unsupported ZIP compression method:","ZIP entry compressed data exceeds ","ZIP entry decompressed data exceeds ","Expected data-descriptor-signature at position "],Dte=new Set(["Z_BUF_ERROR","Z_DATA_ERROR","ERR_INVALID_STATE"]);async function Lte(r,{maximumLength:e=Gi}={}){let o=new ReadableStream({start(l){l.enqueue(r),l.close()}}).pipeThrough(new DecompressionStream("deflate-raw")).getReader(),i=[],s=0;try{for(;;){let{done:l,value:u}=await o.read();if(l)break;if(s+=u.length,s>e)throw await o.cancel(),new Error(`ZIP entry decompressed data exceeds ${e} bytes`);i.push(u)}}finally{o.releaseLock()}let a=new Uint8Array(s),c=0;for(let l of i)a.set(l,c),c+=l.length;return a}function Nte(r,e){let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function Ote(r){let e=r.fileInfo.size,t=Number.isFinite(e)?Math.max(0,e-r.position):Number.MAX_SAFE_INTEGER;return Math.min(t,kte)}function Bte(r){if(r instanceof Se||r instanceof kn)return!0;if(!(r instanceof Error))return!1;if(Rte.has(r.message)||Dte.has(r.code))return!0;for(let e of Pte)if(r.message.startsWith(e))return!0;return!1}function VM(r,e=Gi){let t=[r.compressedSize,r.uncompressedSize];for(let n of t)if(!Number.isFinite(n)||n<0||n>e)return!1;return!0}function Mte(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function Fte(r,e){e==="Index/Document.iwa"&&(r.hasDocumentEntry=!0),e.startsWith("Index/MasterSlide")&&(r.hasMasterSlideEntry=!0),e.startsWith("Index/Tables/")&&(r.hasTablesEntry=!0),e==="Index/CalculationEngine.iwa"&&(r.hasCalculationEngineEntry=!0)}function KM(r){if(r.hasDocumentEntry)return r.hasMasterSlideEntry?{ext:"key",mime:"application/vnd.apple.keynote"}:r.hasTablesEntry?{ext:"numbers",mime:"application/vnd.apple.numbers"}:{ext:"pages",mime:"application/vnd.apple.pages"}}function zM(r){switch(r=r.toLowerCase(),r){case"application/epub+zip":return{ext:"epub",mime:r};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:r};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:r};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:r};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:r};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:r};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:r};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:r};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:r};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:r};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:r};case"application/vnd.ms-excel.sheet.macroenabled":return{ext:"xlsm",mime:"application/vnd.ms-excel.sheet.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":return{ext:"xltx",mime:r};case"application/vnd.ms-excel.template.macroenabled":return{ext:"xltm",mime:"application/vnd.ms-excel.template.macroenabled.12"};case"application/vnd.ms-powerpoint.slideshow.macroenabled":return{ext:"ppsm",mime:"application/vnd.ms-powerpoint.slideshow.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return{ext:"docx",mime:r};case"application/vnd.ms-word.document.macroenabled":return{ext:"docm",mime:"application/vnd.ms-word.document.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.template":return{ext:"dotx",mime:r};case"application/vnd.ms-word.template.macroenabledtemplate":return{ext:"dotm",mime:"application/vnd.ms-word.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.template":return{ext:"potx",mime:r};case"application/vnd.ms-powerpoint.template.macroenabled":return{ext:"potm",mime:"application/vnd.ms-powerpoint.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return{ext:"pptx",mime:r};case"application/vnd.ms-powerpoint.presentation.macroenabled":return{ext:"pptm",mime:"application/vnd.ms-powerpoint.presentation.macroenabled.12"};case"application/vnd.ms-visio.drawing":return{ext:"vsdx",mime:"application/vnd.visio"};case"application/vnd.ms-package.3dmanufacturing-3dmodel+xml":return{ext:"3mf",mime:"model/3mf"};default:}}function Ute(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function $te(r,e){e.startsWith("word/")&&(r.hasWordDirectory=!0),e.startsWith("ppt/")&&(r.hasPresentationDirectory=!0),e.startsWith("xl/")&&(r.hasSpreadsheetDirectory=!0),e.startsWith("3D/")&&e.endsWith(".model")&&(r.hasThreeDimensionalModelEntry=!0)}function WM(r){if(r.hasWordDirectory)return{ext:"docx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};if(r.hasPresentationDirectory)return{ext:"pptx",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};if(r.hasSpreadsheetDirectory)return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};if(r.hasThreeDimensionalModelEntry)return{ext:"3mf",mime:"model/3mf"}}function GM(r){if(!(!r.hasContentTypesEntry||r.hasUnparseableContentTypes||r.isParsingContentTypes||r.hasParsedContentTypesEntry))return WM(r)}function Hte(r){let e=r.indexOf('.main+xml"');if(e===-1){let o="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";return r.includes(`ContentType="${o}"`)?o:void 0}let t=r.slice(0,e),n=t.lastIndexOf('"');return t.slice(n+1)}var jM=134695760,N4=16,qte=N4-1;function Vte(r,e){if(r.length<N4)return-1;let t=r.length-N4;for(let n=0;n<=t;n++)if(et.get(r,n)===jM&&et.get(r,n+8)===e+n)return n;return-1}async function Kte(r,{shouldBuffer:e,maximumLength:t=Gi}={}){let{syncBuffer:n}=r,{length:o}=n,i=[],s=0;for(;;){let a=await r.tokenizer.peekBuffer(n,{mayBeLess:!0}),c=Vte(n.subarray(0,a),s),l=c>=0?0:a===o?Math.min(qte,a-1):0,u=c>=0?c:a-l;if(u===0)break;if(s+=u,s>t)throw new Error(`ZIP entry compressed data exceeds ${t} bytes`);if(e){let d=new Uint8Array(u);await r.tokenizer.readBuffer(d),i.push(d)}else await r.tokenizer.ignore(u);if(c>=0)break}if(St(r.tokenizer)||(r.knownSizeDescriptorScannedBytes+=s),!!e)return Nte(i,s)}function zte(r,e){return St(r.tokenizer)?Math.max(0,16777216-(r.tokenizer.position-e)):Math.max(0,Gi-r.knownSizeDescriptorScannedBytes)}async function Gte(r,e,{shouldBuffer:t,maximumDescriptorLength:n=Gi}={}){if(e.dataDescriptor&&e.compressedSize===0)return Kte(r,{shouldBuffer:t,maximumLength:n});if(!t){await Rn(r.tokenizer,e.compressedSize,{maximumLength:St(r.tokenizer)?Gi:r.tokenizer.fileInfo.size,reason:"ZIP entry compressed data"});return}let o=Ote(r.tokenizer);if(!Number.isFinite(e.compressedSize)||e.compressedSize<0||e.compressedSize>o)throw new Error(`ZIP entry compressed data exceeds ${o} bytes`);let i=new Uint8Array(e.compressedSize);return await r.tokenizer.readBuffer(i),i}Fc.prototype.inflate=async function(r,e,t){if(r.compressedMethod===0)return t(e);if(r.compressedMethod!==8)throw new Error(`Unsupported ZIP compression method: ${r.compressedMethod}`);let n=await Lte(e,{maximumLength:Gi});return t(n)};Fc.prototype.unzip=async function(r){let e=!1,t=0,n=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(zi(this.tokenizer,n,16777216))throw new kn(`ZIP stream probing exceeds ${16777216} bytes`);let o=await this.readLocalFileHeader();if(!o)break;if(t++,t>HM)throw new Error(`ZIP entry count exceeds ${HM}`);let i=r(o);e=!!i.stop,await this.tokenizer.ignore(o.extraFieldLength);let s=await Gte(this,o,{shouldBuffer:!!i.handler,maximumDescriptorLength:Math.min(Gi,zte(this,n))});if(i.handler&&await this.inflate(o,s,i.handler),o.dataDescriptor){let a=new Uint8Array(N4);if(await this.tokenizer.readBuffer(a),et.get(a,0)!==jM)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-a.length}`)}if(zi(this.tokenizer,n,16777216))throw new kn(`ZIP stream probing exceeds ${16777216} bytes`)}while(!e)};async function YM(r){let e,t=Ute(),n=Mte();try{await new Fc(r).unzip(i=>{if($te(t,i.filename),Fte(n,i.filename),n.hasDocumentEntry&&(n.hasMasterSlideEntry||n.hasTablesEntry))return e=KM(n),{stop:!0};let s=i.filename==="[Content_Types].xml",a=GM(t);if(!s&&a)return e=a,{stop:!0};switch(i.filename){case"META-INF/mozilla.rsa":return e={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return e={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return VM(i,qM)?{async handler(c){let l=new TextDecoder("utf-8").decode(c).trim();e=zM(l)},stop:!0}:{};case"[Content_Types].xml":return t.hasContentTypesEntry=!0,VM(i,qM)?(t.isParsingContentTypes=!0,{async handler(c){let l=new TextDecoder("utf-8").decode(c),u=Hte(l);u&&(e=zM(u)),t.hasParsedContentTypesEntry=!0,t.isParsingContentTypes=!1},stop:!0}):(t.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/v.test(i.filename)?(e={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}})}catch(i){if(!Bte(i))throw i;t.isParsingContentTypes&&(t.isParsingContentTypes=!1,t.hasUnparseableContentTypes=!0),!e&&i instanceof Se&&!t.hasContentTypesEntry&&(e=WM(t))}let o=St(r)&&n.hasDocumentEntry&&!n.hasMasterSlideEntry&&!n.hasTablesEntry&&!n.hasCalculationEngineEntry?void 0:KM(n);return e??GM(t)??o??{ext:"zip",mime:"application/zip"}}var XM=64,QM=1024*1024,Wte=256;async function ZM(r){async function e(){let a=await r.peekNumber(bM),c=128,l=0;for(;(a&c)===0&&c!==0;)++l,c>>=1;let u=new Uint8Array(l+1);return await xp(r,u,void 0,{maximumLength:u.length,reason:"EBML field"}),u}async function t(){let a=await e(),c=await e();c[0]^=128>>c.length-1;let l=Math.min(6,c.length),u=new DataView(a.buffer),d=new DataView(c.buffer,c.length-l,l);return{id:Nx(u),len:Nx(d)}}async function n(a){let c=0;for(;a>0;){if(c++,c>Wte||zi(r,i,16777216))return;let l=r.position,u=await t();if(u.id===17026){if(u.len>XM)return;let d=L4(u.len,XM,"EBML DocType");return(await r.readToken(new Ar(d))).replaceAll(/\0.*$/gv,"")}if(St(r)&&(!Number.isFinite(u.len)||u.len<0||u.len>QM)||(await Rn(r,u.len,{maximumLength:St(r)?QM:r.fileInfo.size,reason:"EBML payload"}),--a,r.position<=l))return}}let o=await t(),i=r.position;switch(await n(o.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/matroska"};default:}}var jte=512,Yte=16*1024*1024,JM=1024*1024;function Xte(r){return(r.codePointAt(0)&32)!==0}async function eF(r){let e={ext:"png",mime:"image/png"},t={ext:"apng",mime:"image/apng"};await r.ignore(8);async function n(){return{length:await r.readToken(xM),type:await r.readToken(new Ar(4,"latin1"))}}let o=St(r),i=r.position,s=0,a=!1;do{if(s++,s>jte||zi(r,i,Yte))break;let c=r.position,l=await n();if(l.length<0)return;if(l.type==="IHDR"){if(l.length!==13)return;a=!0}switch(l.type){case"IDAT":return e;case"acTL":return t;default:if(!a&&l.type!=="CgBI")return;if(o&&l.length>JM)return a&&Xte(l.type)?e:void 0;try{await Rn(r,l.length+4,{maximumLength:o?JM+4:r.fileInfo.size,reason:"PNG chunk payload"})}catch(u){if(!o&&(u instanceof kn||u instanceof Se))return e;throw u}}if(r.position<=c)break}while(r.position+8<r.fileInfo.size);return e}var Qte=512,tF=1024*1024;async function rF(r){let e=!1;try{async function t(){let s=new Uint8Array(16);return await xp(r,s,void 0,{maximumLength:s.length,reason:"ASF header GUID"}),{id:s,size:Number(await r.readToken(EM))}}await Rn(r,30,{maximumLength:30,reason:"ASF header prelude"});let n=St(r),o=r.position,i=0;for(;r.position+24<r.fileInfo.size&&(i++,!(i>Qte||zi(r,o,16777216)));){let s=r.position,a=await t(),c=a.size-24;if(!Number.isFinite(c)||c<0){e=!0;break}if(Yn(a.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let l=new Uint8Array(16);if(c-=await xp(r,l,void 0,{maximumLength:l.length,reason:"ASF stream type GUID"}),Yn(l,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(Yn(l,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}if(n&&c>tF){e=!0;break}if(await Rn(r,c,{maximumLength:n?tF:r.fileInfo.size,reason:"ASF header payload"}),r.position<=s){e=!0;break}}}catch(t){if(t instanceof Se||t instanceof kn)St(r)&&(e=!0);else throw t}if(!e)return{ext:"asf",mime:"application/vnd.ms-asf"}}var Ep=4100,Zte=Ep-2,Jte=16777216,ere=1,nF=100,Ox=16777216,tre=512,oF=256,rre=1024*1024,iF=16777216;function nre(r){return Number.isFinite(r)?Math.max(1,Math.trunc(r)):Ep}function ore(r){return Number.isFinite(r)?Math.max(0,Math.min(Zte,Math.trunc(r))):0}function ire(r){return Number.isFinite(r)?Math.max(0,r):Number.MAX_SAFE_INTEGER}function sF(r){return import(r)}function sre(r){return r.pipeThrough(new TransformStream)}function aF(r,e){return e===void 0?r.read():(e.throwIfAborted(),Promise.race([r.read(),new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason),r.cancel(e.reason).catch(()=>{})},{once:!0})})]))}function are(r,e){let t=r.getReader(),n=0,o=!1,i=!1,s=async a=>{o||i||(i=!0,await t.cancel(a))};return new ReadableStream({async pull(a){if(n>=e){a.close(),await s();return}let{done:c,value:l}=await t.read();if(c||!l){o=!0,a.close();return}let u=e-n;if(l.length>u){a.enqueue(l.subarray(0,u)),n+=u,a.close(),await s();return}a.enqueue(l),n+=l.length},async cancel(a){await s(a)}})}async function cF(r,e){return new Bx(e).fromBuffer(r)}var Bx=class r{constructor(e){let t=ore(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return vM(sre(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let n=e.position;for(let o of this.detectors){let i;try{i=await o.detect(e)}catch(s){if(s instanceof Se||s instanceof kn)return;throw s}if(i)return i;if(n!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(SM(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=AM(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:n}]=await Promise.all([sF("node:fs/promises"),sF("strtok3")]),o=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),i=await o.stat();if(!i.isFile()){await o.close();return}let s=new n(o,{...this.getTokenizerOptions(),fileInfo:{path:e,size:i.size}});return this.fromTokenizer(s)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let n=nre(t?.sampleSize??Ep),o,i=!1,s=e.getReader(),a=[],c=0;try{for(;c<n;){let{value:d,done:f}=await aF(s,this.options.signal);if(f||!d){i=!0;break}a.push(d),c+=d.length}if(!i&&c===n){let{value:d,done:f}=await aF(s,this.options.signal);f||!d?i=!0:(a.push(d),c+=d.length)}}finally{s.releaseLock()}if(c>0){let d=a.length===1?a[0]:OM(a);try{o=await this.fromBuffer(d.subarray(0,n))}catch(f){if(!(f instanceof Se))throw f;o=void 0}!i&&o?.ext==="pages"&&(o={ext:"zip",mime:"application/zip"})}let l=new TransformStream({start(d){for(let f of a)d.enqueue(f)},transform(d,f){f.enqueue(d)}}),u=e.pipeThrough(l);return u.fileType=o,u}async detectGzip(e){if(this.gzipProbeDepth>=ere)return{ext:"gz",mime:"application/gzip"};let t=new bp(e),n=are(t.inflate(),Jte),o=St(e),i,s,a,c;if(o){let l=new AbortController;i=setTimeout(()=>{l.abort(new DOMException(`Operation timed out after ${nF} ms`,"TimeoutError"))},nF),s=this.options.signal===void 0?l.signal:AbortSignal.any([this.options.signal,l.signal]),a=new r({...this.options,signal:s}),a.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{c=await(a??this).fromStream(n)}catch(l){if(l?.name==="AbortError"&&s?.reason?.name!=="TimeoutError")throw l}finally{clearTimeout(i),o||this.gzipProbeDepth--}return c?.ext==="tar"?{ext:"tar.gz",mime:"application/gzip"}:{ext:"gz",mime:"application/gzip"}}check(e,t){return Yn(this.buffer,e,t)}checkString(e,t){return this.check(BM(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(Ep),e.fileInfo.size===void 0&&(e.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=e,St(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.detectionReentryCount>=oF?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await Rn(e,6,{maximumLength:6,reason:"ID3 header prefix"});let t=await e.readToken(FM),n=St(e);if(!Number.isFinite(t)||t<0||n&&(t>Ox||e.position+t>Ox))return;if(e.position+t>e.fileInfo.size)return n?void 0:{ext:"mp3",mime:"audio/mpeg"};try{await Rn(e,t,{maximumLength:n?Ox:e.fileInfo.size,reason:"ID3 payload"})}catch(o){if(o instanceof Se)return;throw o}return this.detectionReentryCount>=oF?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4]))return YM(e);if(this.checkString("OggS")){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),Yn(t,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:Yn(t,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Yn(t,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Yn(t,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Yn(t,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Yn(t,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:"zip",mime:"application/zip"};if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF"))return{ext:"pdf",mime:"application/pdf"};if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){let t=await this.readTiffHeader(!1);if(t)return t}if(this.check([77,77])){let t=await this.readTiffHeader(!0);if(t)return t}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163]))return ZM(e);if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1")||this.checkString("PARE"))return{ext:"parquet",mime:"application/vnd.apache.parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([4,34,77,24]))return{ext:"lz4",mime:"application/x-lz4"};if(this.checkString("regf"))return{ext:"dat",mime:"application/x-ft-windows-registry-hive"};if(this.checkString("$FL2")||this.checkString("$FL3"))return{ext:"sav",mime:"application/x-spss-sav"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString(String.raw`{\rtf`))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190])){let t=Rx.get(this.buffer,4),n=Lc.get(this.buffer,6);if(t>0&&t<=30)return{ext:"macho",mime:"application/x-mach-binary"};if(n>30)return{ext:"class",mime:"application/java-vm"}}if(this.checkString(".RMF"))return{ext:"rm",mime:"application/vnd.rn-realmedia"};if(this.checkString("DRACO"))return{ext:"drc",mime:"application/x-ft-draco"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){let t=new Ar(4,"latin1").get(this.buffer,2);if(/^\d+$/v.test(t)&&t>=1e3&&t<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>"))return await e.ignore(8),await e.readToken(new Ar(13,"ascii"))==="debian-binary"?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"};if(this.checkString("WEBVTT")&&[`
111
111
  `,"\r"," "," ","\0"].some(t=>this.checkString(t,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10]))return eF(e);if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/vnd.apache.arrow.file"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.checkString("ftyp",{offset:4})&&(this.buffer[8]&96)!==0){let t=new Ar(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(t){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return t.startsWith("3g")?t.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.checkString(`REGEDIT4\r
112
112
  `))return{ext:"reg",mime:"application/x-ms-regedit"};if(this.check([82,73,70,70])){if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217]))return rF(e);if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new Ar(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.checkString("<?xml ",{offset:2,encoding:"utf-16be"})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("**ACE",{offset:7})&&this.checkString("**",{offset:12}))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){let t=new DataView(this.buffer.buffer).getUint32(12,!0);if(t>12&&this.buffer.length>=t+16)try{let n=new TextDecoder().decode(this.buffer.subarray(16,t+16));if(JSON.parse(n).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(this.checkString("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(this.check([71])&&this.check([71],{offset:188}))return{ext:"mts",mime:"video/mp2t"};if(this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:"mts",mime:"video/mp2t"};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(this.check([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x-ms-shortcut"};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x-ft-apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x-ft-fbx"};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(this.check([255,255,0,0,7,0,0,0,4,0,0,0,1,0,1,0])||this.check([0,0,255,255,0,0,0,7,0,0,0,4,0,1,0,1]))return{ext:"jmp",mime:"application/x-jmp-data"};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString("ustar",{offset:257})&&(this.checkString("\0",{offset:262})||this.checkString(" ",{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&MM(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254])){let t="utf-16le";return this.checkString("<?xml ",{offset:2,encoding:t})?{ext:"xml",mime:"application/xml"}:this.check([255,14],{offset:2})&&this.checkString("SketchUp Model",{offset:4,encoding:t})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:this.checkString(`Windows Registry Editor Version 5.00\r
113
- `,{offset:2,encoding:t})?{ext:"reg",mime:"application/x-ms-regedit"}:void 0}if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"}};detectImprecise=async e=>{this.buffer=new Uint8Array(Ep);let t=ire(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let n=0;n<=this.options.mpegOffsetTolerance;++n){let o=this.scanMpeg(n);if(o)return o}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?Lc:ht);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?Lc:ht);if(!(t>tre)&&!(St(this.tokenizer)&&2+t*12>iF))for(let n=0;n<t;++n){let o=await this.readTiffTag(e);if(o)return o}}async readTiffHeader(e){let t={ext:"tif",mime:"image/tiff"},n=(e?Lc:ht).get(this.buffer,2),o=(e?Rx:et).get(this.buffer,4);if(n===42){if(o>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(o>=8){let a=(e?Lc:ht).get(this.buffer,8),c=(e?Lc:ht).get(this.buffer,10);if(a===28&&c===254||a===31&&c===11)return{ext:"nef",mime:"image/x-nikon-nef"}}}if(St(this.tokenizer)&&o>rre)return t;let i=St(this.tokenizer)?iF:this.tokenizer.fileInfo.size;try{await Rn(this.tokenizer,o,{maximumLength:i,reason:"TIFF IFD offset"})}catch(a){if(a instanceof Se)return;throw a}let s;try{s=await this.readTiffIFD(e)}catch(a){if(a instanceof Se)return;throw a}return s??t}if(n===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}},aYe=new Set(UM),cYe=new Set($M);var lF="application/octet-stream";function cre(r){return/^(<\?xml[^>]+>)?[^<^\w]+<svg/ig.test(r)}async function lre(r){try{return JSON.parse(r),!0}catch{return!1}}function ure(r){let e=new TextDecoder("utf-8",{fatal:!0});try{return e.decode(r)}catch{return null}}async function dre(r){return/^\s*<(?:!doctype\s+html|html|head|body)\b/i.test(r)}async function uF(r,e){let t=(await cF(r))?.mime;if(t!=null)return t==="application/xml"&&e?.toLowerCase().endsWith(".svg")?"image/svg+xml":t;if(e==null||e.includes(".")===!1){let n=ure(r);return n!=null?cre(n)?"image/svg+xml":await lre(n)?"application/json":await dre(n)?"text/html; charset=utf-8":"text/plain; charset=utf-8":lF}switch(e.split(".").pop()){case"css":return"text/css";case"html":return"text/html; charset=utf-8";case"js":case"mjs":case"cjs":return"text/javascript";case"json":return"application/json";case"txt":return"text/plain";case"woff2":return"font/woff2";case"svg":return"image/svg+xml";case"csv":return"text/csv";case"doc":return"application/msword";case"xls":return"application/vnd.ms-excel";case"ppt":return"application/vnd.ms-powerpoint";case"msi":return"application/x-msdownload";default:return lF}}function dF(r,e,t){if(t?.signal?.throwIfAborted(),["AbortError"].includes(e.name))throw e;return["InvalidParametersError"].includes(e.name)?Yr(r,e):e.code==="ECONNREFUSED"||e.code==="ECANCELLED"||e.name==="DNSQueryFailedError"?Wy(r,e):["NotUnixFSError"].includes(e.name)?Rc(r,e):e.code==="ETIMEOUT"||e.name==="TimeoutError"?Wy(r,e):["ERR_BAD_PATH","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(e.code)?$9(r):["DoesNotExistError"].includes(e.name)?$9(r):["BlockNotFoundWhileOfflineError"].includes(e.name)?jL(r):["RecordNotFoundError","LoadBlockFailedError"].includes(e.name)?Wy(r,e):F9(r,e)}function fF({cid:r,contentType:e,ranges:t,contentPrefix:n}){let o=e.immutable?"":"W/",i=e.etag;if(t?.length!=null&&t?.length>0){let s=t.filter(a=>a.start!=null||a.end!=null);s.length>0&&(i+="."+s.map(a=>`${a.start??0}-${a.end??"N"}`).join(","))}return`${o}"${n??""}${r.toString()}${i}"`}function Mx(r,e){let t=(e?.get("if-none-match")??"").split(",").map(n=>(n=n.trim(),n.startsWith("W/")&&(n=n.substring(2)),n));return r.startsWith("W/")&&(r=r.substring(2)),t.includes("*")||t.includes(r)}function Fx(r){if(r==null||r==="")return;let e=Number(r);if(isNaN(e))throw new Fr(`Invalid range specification: could not parse "${e}" as number`);return e}function fre(r){if(r==null||r==="")return[];if(!r.startsWith("bytes="))throw new Fr("Invalid range request");let t=r.substring(6).split(",").map(o=>o.trim()),n=[];for(let o of t){let i=o.match(/^(?<start>\d+)?-(?<end>\d+)?$/);if(i?.groups==null)throw new Fr(`Invalid range specification: ${o}`);if(o.startsWith("-"))n.push({end:Fx(o)});else{let{start:s,end:a}=i.groups;n.push({start:Fx(s),end:Fx(a)})}}return n}function hF(r,e){let t=e.get("range");if(t!=null)try{let n=fre(t);return n.length===0?void 0:{multipartBoundary:`multipart_byteranges_${Math.floor(Math.random()*1e9)}`,ranges:n}}catch(n){return n.name==="InvalidRangeError"?jy(r):Yr(r,n)}}function hre(r){if(!r.startsWith("/ipfs/")&&!r.startsWith("/ipns/"))throw new E(`Path ${r} did not start with /ipfs/ or /ipns/`);let e=new URL(`not-http://example.com${r}`),[,t,n,...o]=e.pathname.split("/");return`${t}://${n}${o.length>0?`/${o.join("/")}`:""}${e.search}${e.hash}`}function pF(r){if((r.startsWith("/ipfs/")||r.startsWith("/ipns/"))&&(r=hre(r)),r.startsWith("ipfs://")||r.startsWith("ipns://")||r.startsWith("dnslink://")){let e=new URL(r);if(e.protocol==="ipns:")try{F.parse(e.hostname)}catch{try{Ee(e.hostname)}catch{e.protocol="dnslink"}}return e}throw new E(`URL did not start with ipfs:// or ipns:// - ${r}`)}function pre(r){if(r!=null)return{...r,signal:r?.signal==null?void 0:r?.signal}}function mre(r){let e=r.get("accept")?.split(",")??[];return e.length!==1?!1:e[0].split(";")[0]===_c}function O4(r){return`${r}`.substring(0,10)}var B4=class{helia;ipnsResolver;dnsLink;log;contentTypeParser;withServerTiming;plugins=[];urlResolver;constructor(e,t={}){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipnsResolver=t.ipnsResolver??OD(e),this.dnsLink=t.dnsLink??kD(e),this.contentTypeParser=t.contentTypeParser??uF,this.withServerTiming=t?.withServerTiming??!1,this.urlResolver=new S4({ipnsResolver:this.ipnsResolver,dnsLink:this.dnsLink,helia:this.helia},t);let n={...t,logger:e.logger.forComponent("verified-fetch"),helia:e,contentTypeParser:this.contentTypeParser,ipnsResolver:this.ipnsResolver},o=[new o4(n),new Xy(n),new Yy(n),new n4(n),new Qy(n),new Zy(n)],i=t.plugins?.map(s=>s(n))??[];if(i.length>0){let s=new Map(o.map(c=>[c.id,c])),a=new Map(i.map(c=>[c.id,c]));this.plugins=o.map(c=>a.get(c.id)??c),this.plugins.unshift(...i.filter(c=>!s.has(c.id)))}else this.plugins=o}async fetch(e,t){this.log("fetch %s %s",t?.method??"GET",e);let n=new zu,o=!!t?.withServerTiming||!!this.withServerTiming;try{if(t?.signal?.throwIfAborted(),t?.method==="OPTIONS")return this.handleFinalResponse(new Response(null,{status:200}),o,{serverTiming:n});let i=pre(t),s=new Headers(i?.headers);i!=null&&(i.offline??=s.get("cache-control")==="only-if-cached"),i?.onProgress?.(new k("verified-fetch:request:start",{resource:e}));let a=hF(e,s);if(a instanceof Response)return this.handleFinalResponse(a,o,{serverTiming:n});let c=this.parseResource(e);if(c.protocol==="ipfs:"&&c.pathname===""&&Mx(`"${c.hostname}"`,s))return this.handleFinalResponse(H9(e,new Headers({etag:`"${c.hostname}"`,"cache-control":"public, max-age=29030400, immutable"})),o,{serverTiming:n});let l=gre(c,s.get("accept"));if(mre(s)){if(c.protocol!=="ipns:")return ea(c,l,[Ic]);let m=this.plugins.find(b=>b.id==="ipns-record-plugin");return m==null?ea(e,l,[]):this.handleFinalResponse(await m.handle({...i,range:a,url:c,resource:e,redirected:!1}),o,{serverTiming:n})}let u=await this.urlResolver.resolve(c,n,i);if(u instanceof Response)return this.handleFinalResponse(u,o,{serverTiming:n});i?.onProgress?.(new k("verified-fetch:request:resolve",{cid:u.terminalElement.cid,path:u.url.pathname}));let d=this.getAcceptHeader(u.url,l,u.terminalElement.cid);if(d instanceof Response)return this.log("allowed media types for requested CID did not contain anything the client can understand"),this.handleFinalResponse(d,o,{serverTiming:n});let f={},h={},p={},y={...i,...u,resource:e,accept:d,range:a,serverTiming:n,headers:s,requestedMimeTypes:l,onProgress:m=>{if(i?.onProgress?.(m),m.type==="helia:routing:find-providers:start")f[m.detail.routing]={start:performance.now(),found:0};else if(m.type==="helia:routing:find-providers:provider"){if(f[m.detail.routing]==null)return;f[m.detail.routing].found++,n.add(In("found-provider"),`${In(m.detail.routing)},${O4(m.detail.provider.id)}`,performance.now()-f[m.detail.routing].start)}else if(m.type==="helia:routing:find-providers:end"){let b=f[m.detail.routing];if(b==null)return;n.add(In("find-providers"),`${In(m.detail.routing)},${b.found}`,performance.now()-b.start)}else if(m.type==="helia:block-broker:connect")h[`connect-${m.detail.broker}-${m.detail.provider}`]={start:performance.now(),transport:""};else if(m.type==="helia:block-broker:connected"){let b=h[`connect-${m.detail.broker}-${m.detail.provider}`];if(b==null)return;n.add(In("connect"),`${In(m.detail.broker)},${O4(m.detail.provider)},${nN(m.detail.address)}`,performance.now()-b.start)}else if(m.type==="helia:block-broker:request-block")p[`block-${m.detail.broker}-${m.detail.cid}-${m.detail.provider}`]=performance.now();else if(m.type==="helia:block-broker:receive-block"){let b=p[`block-${m.detail.broker}-${m.detail.cid}-${m.detail.provider}`];if(b==null)return;n.add(In("block"),`${In(m.detail.broker)},${O4(m.detail.provider)},${O4(m.detail.cid)}`,performance.now()-b)}}};this.log.trace('finding handler for cid code "0x%s" and response content types %s',u.terminalElement.cid.code.toString(16),d.map(m=>m.contentType.mediaType).join(", "));let g=await this.runPluginPipeline(y);return i?.onProgress?.(new k("verified-fetch:request:end",{cid:u.terminalElement.cid,path:u.url.pathname})),g==null&&this.log.error("no plugin could handle request for %s",e),this.handleFinalResponse(g,o,y)}catch(i){i?.name==="AbortError"&&(i.serverTiming=n.getHeader()),this.log.error("error fetching resource %s - %e",e,i);try{return this.handleFinalResponse(dF(e,i,t),o,{serverTiming:n})}catch(s){let a=n.getHeader();throw a!==""&&(s.serverTiming=a),s}}}getAcceptHeader(e,t,n){let o=$L(e.protocol,n),i=[];for(let s of t){let[a,c]=s.mediaType.split("/");for(let l of o){let[u,d]=l.mediaType.split("/");s.mediaType.includes(l.mediaType)&&i.push({contentType:l,options:s.options}),s.mediaType==="*/*"&&i.push({contentType:l,options:s.options}),s.mediaType.startsWith("*/")&&d===c&&i.push({contentType:l,options:s.options}),s.mediaType.endsWith("/*")&&u===a&&i.push({contentType:l,options:s.options})}}return i.length===0?(this.log("requested %o",t.map(({mediaType:s})=>s)),this.log("supported %o",o.map(({mediaType:s})=>s)),ea(e,t,o)):i}parseResource(e){return(pt(e)||Pp(e))&&(e=`/ipns/${e}`),(F.asCID(e)===e||e instanceof F)&&(e=`/ipfs/${e}`),new URL(pF(e.toString()))}handleFinalResponse(e,t,n){let o=UL(e.headers.get("content-type"))??Gy;if(t===!0&&n?.serverTiming!=null){let i=n?.serverTiming.getHeader();i!==""&&e.headers.set("server-timing",i)}if(n?.url?.protocol!=null&&n.ttl!=null&&KL({response:e,ttl:n.ttl,protocol:n.url.protocol}),n?.terminalElement?.cid!=null&&n?.url!=null){let i=n.url.pathname.split("/").map(a=>decodeURIComponent(a)).join("/").trim(),s=de(K(i,"ascii"),"ascii");e.headers.set("x-ipfs-path",`/${n.url.protocol==="ipfs:"?"ipfs":"ipns"}/${n?.url.hostname}${s==="/"?"":s}`)}if(e.headers.set("access-control-allow-origin","*"),e.headers.set("access-control-allow-methods","GET, HEAD, OPTIONS"),e.headers.set("access-control-allow-headers","Content-Type, Range, User-Agent, X-Requested-With"),e.headers.set("access-control-expose-headers","Content-Range, Content-Length, X-Ipfs-Path, X-Ipfs-Roots, X-Chunked-Output, X-Stream-Output"),n?.terminalElement?.cid!=null&&e.headers.get("etag")==null){let i=fF({cid:n.terminalElement.cid,contentType:o,ranges:n?.range?.ranges});if(e.headers.set("etag",i),Mx(i,n?.headers))return H9(e.url,e.headers)}return n?.method==="HEAD"?new Response(null,{status:200,headers:e.headers}):(e.status>399&&e.headers.delete("content-disposition"),e)}async runPluginPipeline(e){let t,n=new Set;this.log.trace("checking which plugins can handle %c%s with accept %s",e.terminalElement.cid,e.url.pathname,e.accept.map(a=>a.contentType.mediaType).join(", "));let o=this.plugins.filter(a=>!n.has(a.id)).filter(a=>a.canHandle(e));if(o.length===0)return this.log.trace("no plugins found that can handle request; exiting pipeline"),U9(e.resource);this.log.trace("plugins ready to handle request: %s",o.map(a=>a.id).join(", "));let i=!1,s=!1;for(let a of o){this.log("invoking plugin: %s",a.id),n.add(a.id);let c=await a.handle(e);if(this.log("plugin response %s %o",a.id,c),c!=null){t=c,s=!0;break}if(t!=null){this.log.trace("plugin %s produced final response",a.id);break}if(s&&t!=null)break;if(!i){this.log.trace("no context changes and no final response; exiting pipeline.");break}}return t??U9(e.resource,JSON.stringify({error:kc(new Error("No verified fetch plugin could handle the request"))}),{headers:{"content-type":"application/json"}})}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};function gre(r,e){return(e==null||e==="")&&(e="*/*"),e.split(",").map(t=>{let n=t.trim().split(";"),o={q:"1"};for(let i=1;i<n.length;i++){let[s,a]=n[i].split("=").map(c=>c.trim());o[s]=a}return{mediaType:`${n[0]}`.trim(),options:o}}).sort((t,n)=>t.options.q===n.options.q?0:t.options.q>n.options.q?-1:1)}var vp,M4=async function(e,t){return vp==null&&(vp=await Ux()),vp(e,t)};M4.start=async function(){await vp?.start()};M4.stop=async function(){await vp?.stop()};async function Ux(r,e){let t;if(!yre(r)){let n=wre(r?.dnsResolvers),o=_D();o.dns=n;let i=r?.routers??["https://delegated-ipfs.dev"];for(let c=0;c<i.length;c++)o.services[`delegatedRouting${c}`]=O0({url:i[c]});r?.libp2pConfig!=null&&Object.assign(o,r.libp2pConfig),t=await C2(o);let s=[Cf()],a=[Df(t)];(r?.gateways==null||r.gateways.length>0)&&(s.push(If({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})),a.push(Pf({gateways:r?.gateways??["https://trustless-gateway.link"]}))),r=await TD({libp2p:t,blockBrokers:s,dns:n,routers:a,hashers:r?.hashers}),r.logger.forComponent("helia:verified-fetch").trace("created verified-fetch with libp2p config: %j",o)}return mF(r,e)}async function mF(r,e){let t=new B4(r,e);async function n(o,i){return t.fetch(o,i)}return n.start=t.start.bind(t),n.stop=t.stop.bind(t),n}function yre(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function wre(r){if(r!=null)return Array.isArray(r)?Za({resolvers:{".":r}}):Za({resolvers:r})}return EF(bre);})();
113
+ `,{offset:2,encoding:t})?{ext:"reg",mime:"application/x-ms-regedit"}:void 0}if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"}};detectImprecise=async e=>{this.buffer=new Uint8Array(Ep);let t=ire(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let n=0;n<=this.options.mpegOffsetTolerance;++n){let o=this.scanMpeg(n);if(o)return o}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?Lc:ht);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?Lc:ht);if(!(t>tre)&&!(St(this.tokenizer)&&2+t*12>iF))for(let n=0;n<t;++n){let o=await this.readTiffTag(e);if(o)return o}}async readTiffHeader(e){let t={ext:"tif",mime:"image/tiff"},n=(e?Lc:ht).get(this.buffer,2),o=(e?Rx:et).get(this.buffer,4);if(n===42){if(o>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(o>=8){let a=(e?Lc:ht).get(this.buffer,8),c=(e?Lc:ht).get(this.buffer,10);if(a===28&&c===254||a===31&&c===11)return{ext:"nef",mime:"image/x-nikon-nef"}}}if(St(this.tokenizer)&&o>rre)return t;let i=St(this.tokenizer)?iF:this.tokenizer.fileInfo.size;try{await Rn(this.tokenizer,o,{maximumLength:i,reason:"TIFF IFD offset"})}catch(a){if(a instanceof Se)return;throw a}let s;try{s=await this.readTiffIFD(e)}catch(a){if(a instanceof Se)return;throw a}return s??t}if(n===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}},aYe=new Set(UM),cYe=new Set($M);var lF="application/octet-stream";function cre(r){return/^(<\?xml[^>]+>)?[^<^\w]+<svg/ig.test(r)}async function lre(r){try{return JSON.parse(r),!0}catch{return!1}}function ure(r){let e=new TextDecoder("utf-8",{fatal:!0});try{return e.decode(r)}catch{return null}}async function dre(r){return/^\s*<(?:!doctype\s+html|html|head|body)\b/i.test(r)}async function uF(r,e){let t=(await cF(r))?.mime;if(t!=null)return t==="application/xml"&&e?.toLowerCase().endsWith(".svg")?"image/svg+xml":t;if(e==null||e.includes(".")===!1){let n=ure(r);return n!=null?cre(n)?"image/svg+xml":await lre(n)?"application/json":await dre(n)?"text/html; charset=utf-8":"text/plain; charset=utf-8":lF}switch(e.split(".").pop()){case"css":return"text/css";case"html":return"text/html; charset=utf-8";case"js":case"mjs":case"cjs":return"text/javascript";case"json":return"application/json";case"txt":return"text/plain";case"woff2":return"font/woff2";case"svg":return"image/svg+xml";case"csv":return"text/csv";case"doc":return"application/msword";case"xls":return"application/vnd.ms-excel";case"ppt":return"application/vnd.ms-powerpoint";case"msi":return"application/x-msdownload";default:return lF}}function dF(r,e,t){if(t?.signal?.throwIfAborted(),["AbortError"].includes(e.name))throw e;return["InvalidParametersError"].includes(e.name)?Yr(r,e):e.code==="ECONNREFUSED"||e.code==="ECANCELLED"||e.name==="DNSQueryFailedError"?Wy(r,e):["NotUnixFSError"].includes(e.name)?Rc(r,e):e.code==="ETIMEOUT"||e.name==="TimeoutError"?Wy(r,e):["ERR_BAD_PATH","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(e.code)?$9(r):["DoesNotExistError"].includes(e.name)?$9(r):["BlockNotFoundWhileOfflineError"].includes(e.name)?jL(r):["RecordNotFoundError","LoadBlockFailedError"].includes(e.name)?Wy(r,e):F9(r,e)}function fF({cid:r,contentType:e,ranges:t,contentPrefix:n}){let o=e.immutable?"":"W/",i=e.etag;if(t?.length!=null&&t?.length>0){let s=t.filter(a=>a.start!=null||a.end!=null);s.length>0&&(i+="."+s.map(a=>`${a.start??0}-${a.end??"N"}`).join(","))}return`${o}"${n??""}${r.toString()}${i}"`}function Mx(r,e){let t=(e?.get("if-none-match")??"").split(",").map(n=>(n=n.trim(),n.startsWith("W/")&&(n=n.substring(2)),n));return r.startsWith("W/")&&(r=r.substring(2)),t.includes("*")||t.includes(r)}function Fx(r){if(r==null||r==="")return;let e=Number(r);if(isNaN(e))throw new Fr(`Invalid range specification: could not parse "${e}" as number`);return e}function fre(r){if(r==null||r==="")return[];if(!r.startsWith("bytes="))throw new Fr("Invalid range request");let t=r.substring(6).split(",").map(o=>o.trim()),n=[];for(let o of t){let i=o.match(/^(?<start>\d+)?-(?<end>\d+)?$/);if(i?.groups==null)throw new Fr(`Invalid range specification: ${o}`);if(o.startsWith("-"))n.push({end:Fx(o)});else{let{start:s,end:a}=i.groups;n.push({start:Fx(s),end:Fx(a)})}}return n}function hF(r,e){let t=e.get("range");if(t!=null)try{let n=fre(t);return n.length===0?void 0:{multipartBoundary:`multipart_byteranges_${Math.floor(Math.random()*1e9)}`,ranges:n}}catch(n){return n.name==="InvalidRangeError"?jy(r):Yr(r,n)}}function hre(r){if(!r.startsWith("/ipfs/")&&!r.startsWith("/ipns/"))throw new E(`Path ${r} did not start with /ipfs/ or /ipns/`);let e=new URL(`not-http://example.com${r}`),[,t,n,...o]=e.pathname.split("/");return`${t}://${n}${o.length>0?`/${o.join("/")}`:""}${e.search}${e.hash}`}function pF(r){if((r.startsWith("/ipfs/")||r.startsWith("/ipns/"))&&(r=hre(r)),r.startsWith("ipfs://")||r.startsWith("ipns://")||r.startsWith("dnslink://")){let e=new URL(r);if(e.protocol==="ipns:")try{F.parse(e.hostname)}catch{try{Ee(e.hostname)}catch{e.protocol="dnslink"}}return e}throw new E(`URL did not start with ipfs:// or ipns:// - ${r}`)}function pre(r){if(r!=null)return{...r,signal:r?.signal==null?void 0:r?.signal}}function mre(r){let e=r.get("accept")?.split(",")??[];return e.length!==1?!1:e[0].split(";")[0]===_c}function O4(r){return`${r}`.substring(0,10)}var B4=class{helia;ipnsResolver;dnsLink;log;contentTypeParser;withServerTiming;plugins=[];urlResolver;constructor(e,t={}){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipnsResolver=t.ipnsResolver??OD(e),this.dnsLink=t.dnsLink??kD(e),this.contentTypeParser=t.contentTypeParser??uF,this.withServerTiming=t?.withServerTiming??!1,this.urlResolver=new S4({ipnsResolver:this.ipnsResolver,dnsLink:this.dnsLink,helia:this.helia},t);let n={...t,logger:e.logger.forComponent("verified-fetch"),helia:e,contentTypeParser:this.contentTypeParser,ipnsResolver:this.ipnsResolver},o=[new o4(n),new Xy(n),new Yy(n),new n4(n),new Qy(n),new Zy(n)],i=t.plugins?.map(s=>s(n))??[];if(i.length>0){let s=new Map(o.map(c=>[c.id,c])),a=new Map(i.map(c=>[c.id,c]));this.plugins=o.map(c=>a.get(c.id)??c),this.plugins.unshift(...i.filter(c=>!s.has(c.id)))}else this.plugins=o}async fetch(e,t){this.log("fetch %s %s",t?.method??"GET",e);let n=new zu,o=!!t?.withServerTiming||!!this.withServerTiming;try{if(t?.signal?.throwIfAborted(),t?.method==="OPTIONS")return this.handleFinalResponse(new Response(null,{status:200}),o,{serverTiming:n});let i=pre(t),s=new Headers(i?.headers);i!=null&&(i.offline??=s.get("cache-control")==="only-if-cached"),i?.onProgress?.(new k("verified-fetch:request:start",{resource:e}));let a=hF(e,s);if(a instanceof Response)return this.handleFinalResponse(a,o,{serverTiming:n});let c=this.parseResource(e);if(c.protocol==="ipfs:"&&c.pathname===""&&Mx(`"${c.hostname}"`,s))return this.handleFinalResponse(H9(e,new Headers({etag:`"${c.hostname}"`,"cache-control":"public, max-age=29030400, immutable"})),o,{serverTiming:n});let l=gre(c,s.get("accept"));if(mre(s)){if(c.protocol!=="ipns:")return ea(c,l,[Ic]);let m=this.plugins.find(T=>T.id==="ipns-record-plugin");if(m==null)return ea(e,l,[]);let b={...i,range:a,url:c,resource:e,redirected:!1,serverTiming:n};return this.handleFinalResponse(await m.handle(b),o,b)}let u=await this.urlResolver.resolve(c,n,i);if(u instanceof Response)return this.handleFinalResponse(u,o,{serverTiming:n});i?.onProgress?.(new k("verified-fetch:request:resolve",{cid:u.terminalElement.cid,path:u.url.pathname}));let d=this.getAcceptHeader(u.url,l,u.terminalElement.cid);if(d instanceof Response)return this.log("allowed media types for requested CID did not contain anything the client can understand"),this.handleFinalResponse(d,o,{serverTiming:n});let f={},h={},p={},y={...i,...u,resource:e,accept:d,range:a,serverTiming:n,headers:s,requestedMimeTypes:l,onProgress:m=>{if(i?.onProgress?.(m),m.type==="helia:routing:find-providers:start")f[m.detail.routing]={start:performance.now(),found:0};else if(m.type==="helia:routing:find-providers:provider"){if(f[m.detail.routing]==null)return;f[m.detail.routing].found++,n.add(In("found-provider"),`${In(m.detail.routing)},${O4(m.detail.provider.id)}`,performance.now()-f[m.detail.routing].start)}else if(m.type==="helia:routing:find-providers:end"){let b=f[m.detail.routing];if(b==null)return;n.add(In("find-providers"),`${In(m.detail.routing)},${b.found}`,performance.now()-b.start)}else if(m.type==="helia:block-broker:connect")h[`connect-${m.detail.broker}-${m.detail.provider}`]={start:performance.now(),transport:""};else if(m.type==="helia:block-broker:connected"){let b=h[`connect-${m.detail.broker}-${m.detail.provider}`];if(b==null)return;n.add(In("connect"),`${In(m.detail.broker)},${O4(m.detail.provider)},${nN(m.detail.address)}`,performance.now()-b.start)}else if(m.type==="helia:block-broker:request-block")p[`block-${m.detail.broker}-${m.detail.cid}-${m.detail.provider}`]=performance.now();else if(m.type==="helia:block-broker:receive-block"){let b=p[`block-${m.detail.broker}-${m.detail.cid}-${m.detail.provider}`];if(b==null)return;n.add(In("block"),`${In(m.detail.broker)},${O4(m.detail.provider)},${O4(m.detail.cid)}`,performance.now()-b)}}};this.log.trace('finding handler for cid code "0x%s" and response content types %s',u.terminalElement.cid.code.toString(16),d.map(m=>m.contentType.mediaType).join(", "));let g=await this.runPluginPipeline(y);return i?.onProgress?.(new k("verified-fetch:request:end",{cid:u.terminalElement.cid,path:u.url.pathname})),g==null&&this.log.error("no plugin could handle request for %s",e),this.handleFinalResponse(g,o,y)}catch(i){i?.name==="AbortError"&&(i.serverTiming=n.getHeader()),this.log.error("error fetching resource %s - %e",e,i);try{return this.handleFinalResponse(dF(e,i,t),o,{serverTiming:n})}catch(s){let a=n.getHeader();throw a!==""&&(s.serverTiming=a),s}}}getAcceptHeader(e,t,n){let o=$L(e.protocol,n),i=[];for(let s of t){let[a,c]=s.mediaType.split("/");for(let l of o){let[u,d]=l.mediaType.split("/");s.mediaType.includes(l.mediaType)&&i.push({contentType:l,options:s.options}),s.mediaType==="*/*"&&i.push({contentType:l,options:s.options}),s.mediaType.startsWith("*/")&&d===c&&i.push({contentType:l,options:s.options}),s.mediaType.endsWith("/*")&&u===a&&i.push({contentType:l,options:s.options})}}return i.length===0?(this.log("requested %o",t.map(({mediaType:s})=>s)),this.log("supported %o",o.map(({mediaType:s})=>s)),ea(e,t,o)):i}parseResource(e){return(pt(e)||Pp(e))&&(e=`/ipns/${e}`),(F.asCID(e)===e||e instanceof F)&&(e=`/ipfs/${e}`),new URL(pF(e.toString()))}handleFinalResponse(e,t,n){let o=UL(e.headers.get("content-type"))??Gy;if(t===!0&&n?.serverTiming!=null){let i=n?.serverTiming.getHeader();i!==""&&e.headers.set("server-timing",i)}if(n?.url?.protocol!=null&&n.ttl!=null&&KL({response:e,ttl:n.ttl,expires:n.expires,protocol:n.url.protocol}),n?.terminalElement?.cid!=null&&n?.url!=null){let i=n.url.pathname.split("/").map(a=>decodeURIComponent(a)).join("/").trim(),s=de(K(i,"ascii"),"ascii");e.headers.set("x-ipfs-path",`/${n.url.protocol==="ipfs:"?"ipfs":"ipns"}/${n?.url.hostname}${s==="/"?"":s}`)}if(e.headers.set("access-control-allow-origin","*"),e.headers.set("access-control-allow-methods","GET, HEAD, OPTIONS"),e.headers.set("access-control-allow-headers","Content-Type, Range, User-Agent, X-Requested-With"),e.headers.set("access-control-expose-headers","Content-Range, Content-Length, X-Ipfs-Path, X-Ipfs-Roots, X-Chunked-Output, X-Stream-Output"),n?.terminalElement?.cid!=null&&e.headers.get("etag")==null){let i=fF({cid:n.terminalElement.cid,contentType:o,ranges:n?.range?.ranges});if(e.headers.set("etag",i),Mx(i,n?.headers))return H9(e.url,e.headers)}return n?.method==="HEAD"?new Response(null,{status:200,headers:e.headers}):(e.status>399&&e.headers.delete("content-disposition"),e)}async runPluginPipeline(e){let t,n=new Set;this.log.trace("checking which plugins can handle %c%s with accept %s",e.terminalElement.cid,e.url.pathname,e.accept.map(a=>a.contentType.mediaType).join(", "));let o=this.plugins.filter(a=>!n.has(a.id)).filter(a=>a.canHandle(e));if(o.length===0)return this.log.trace("no plugins found that can handle request; exiting pipeline"),U9(e.resource);this.log.trace("plugins ready to handle request: %s",o.map(a=>a.id).join(", "));let i=!1,s=!1;for(let a of o){this.log("invoking plugin: %s",a.id),n.add(a.id);let c=await a.handle(e);if(this.log("plugin response %s %o",a.id,c),c!=null){t=c,s=!0;break}if(t!=null){this.log.trace("plugin %s produced final response",a.id);break}if(s&&t!=null)break;if(!i){this.log.trace("no context changes and no final response; exiting pipeline.");break}}return t??U9(e.resource,JSON.stringify({error:kc(new Error("No verified fetch plugin could handle the request"))}),{headers:{"content-type":"application/json"}})}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};function gre(r,e){return(e==null||e==="")&&(e="*/*"),e.split(",").map(t=>{let n=t.trim().split(";"),o={q:"1"};for(let i=1;i<n.length;i++){let[s,a]=n[i].split("=").map(c=>c.trim());o[s]=a}return{mediaType:`${n[0]}`.trim(),options:o}}).sort((t,n)=>t.options.q===n.options.q?0:t.options.q>n.options.q?-1:1)}var vp,M4=async function(e,t){return vp==null&&(vp=await Ux()),vp(e,t)};M4.start=async function(){await vp?.start()};M4.stop=async function(){await vp?.stop()};async function Ux(r,e){let t;if(!yre(r)){let n=wre(r?.dnsResolvers),o=_D();o.dns=n;let i=r?.routers??["https://delegated-ipfs.dev"];for(let c=0;c<i.length;c++)o.services[`delegatedRouting${c}`]=O0({url:i[c]});r?.libp2pConfig!=null&&Object.assign(o,r.libp2pConfig),t=await C2(o);let s=[Cf()],a=[Df(t)];(r?.gateways==null||r.gateways.length>0)&&(s.push(If({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})),a.push(Pf({gateways:r?.gateways??["https://trustless-gateway.link"]}))),r=await TD({libp2p:t,blockBrokers:s,dns:n,routers:a,hashers:r?.hashers}),r.logger.forComponent("helia:verified-fetch").trace("created verified-fetch with libp2p config: %j",o)}return mF(r,e)}async function mF(r,e){let t=new B4(r,e);async function n(o,i){return t.fetch(o,i)}return n.start=t.start.bind(t),n.stop=t.stop.bind(t),n}function yre(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function wre(r){if(r!=null)return Array.isArray(r)?Za({resolvers:{".":r}}):Za({resolvers:r})}return EF(bre);})();
114
114
  /*! Bundled license information:
115
115
 
116
116
  pvtsutils/build/index.js: