helia 4.2.1-e6b976a → 4.2.1-f46700f
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 +6 -6
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +5 -5
- package/src/version.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Helia = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Helia=(()=>{var Bb=Object.create;var Bc=Object.defineProperty;var Mb=Object.getOwnPropertyDescriptor;var Ub=Object.getOwnPropertyNames;var Fb=Object.getPrototypeOf,Vb=Object.prototype.hasOwnProperty;var ke=(r,e)=>()=>(r&&(e=r(r=0)),e);var Re=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),pe=(r,e)=>{for(var t in e)Bc(r,t,{get:e[t],enumerable:!0})},x4=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ub(e))!Vb.call(r,o)&&o!==t&&Bc(r,o,{get:()=>e[o],enumerable:!(n=Mb(e,o))||n.enumerable});return r};var Qe=(r,e,t)=>(t=r!=null?Bb(Fb(r)):{},x4(e||!r||!r.__esModule?Bc(t,"default",{value:r,enumerable:!0}):t,r)),Mc=r=>x4(Bc({},"__esModule",{value:!0}),r);var Yo=Re((ML,I4)=>{"use strict";function A4(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function jb(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return A4(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),A4(new o,t)}}I4.exports=jb});var jm=Re(si=>{"use strict";var GR="[object ArrayBuffer]",Pn=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===GR}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},r0="string",WR=/^[0-9a-f]+$/i,zR=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,YR=/^[a-zA-Z0-9-_]+$/,El=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=Pn.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},Sr=class{static toString(e,t=!1){let n=Pn.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},bl=class r{static isHex(e){return typeof e===r0&&WR.test(e)}static isBase64(e){return typeof e===r0&&zR.test(e)}static isBase64Url(e){return typeof e===r0&&YR.test(e)}static ToString(e,t="utf8"){let n=Pn.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 Sr.toString(n,!0);case"utf16":case"utf16be":return Sr.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 Sr.fromString(e,!0);case"utf16":case"utf16be":return Sr.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Pn.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 El.fromString(e);case"utf16":case"utf16be":return Sr.fromString(e);case"utf16le":case"usc2":return Sr.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 El.toString(e);case"utf16":case"utf16be":return Sr.toString(e);case"utf16le":case"usc2":return Sr.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=Pn.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Pn.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return Sr.toString(e,t)}static FromUtf16String(e,t=!1){return Sr.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,"")||""}};bl.DEFAULT_UTF8_ENCODING="utf8";function XR(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function QR(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function jR(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}si.BufferSourceConverter=Pn;si.Convert=bl;si.assign=XR;si.combine=QR;si.isEqual=jR});var n6=Re((Ua,lu)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(f){if(!Array.isArray(f)&&!ArrayBuffer.isView(f))return!1;for(var p=0;p<f.length;p++)if(!Number.isInteger(f[p])||f[p]<0||f[p]>255)return!1;return!0}function o(f,p){return(f&65535)*p+(((f>>>16)*p&65535)<<16)}function s(f,p){return f<<p|f>>>32-p}function i(f){return f^=f>>>16,f=o(f,2246822507),f^=f>>>13,f=o(f,3266489909),f^=f>>>16,f}function a(f,p){f=[f[0]>>>16,f[0]&65535,f[1]>>>16,f[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=f[3]+p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=f[2]+p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=f[1]+p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=f[0]+p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(f,p){f=[f[0]>>>16,f[0]&65535,f[1]>>>16,f[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=f[3]*p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=f[2]*p[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=f[3]*p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=f[1]*p[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=f[2]*p[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=f[3]*p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=f[0]*p[3]+f[1]*p[2]+f[2]*p[1]+f[3]*p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function l(f,p){return p%=64,p===32?[f[1],f[0]]:p<32?[f[0]<<p|f[1]>>>32-p,f[1]<<p|f[0]>>>32-p]:(p-=32,[f[1]<<p|f[0]>>>32-p,f[0]<<p|f[1]>>>32-p])}function d(f,p){return p%=64,p===0?f:p<32?[f[0]<<p|f[1]>>>32-p,f[1]<<p]:[f[1]<<p-32,0]}function u(f,p){return[f[0]^p[0],f[1]^p[1]]}function h(f){return f=u(f,[0,f[0]>>>1]),f=c(f,[4283543511,3981806797]),f=u(f,[0,f[0]>>>1]),f=c(f,[3301882366,444984403]),f=u(f,[0,f[0]>>>1]),f}t.x86.hash32=function(f,p){if(t.inputValidation&&!n(f))return e;p=p||0;for(var m=f.length%4,y=f.length-m,w=p,b=0,E=3432918353,x=461845907,v=0;v<y;v=v+4)b=f[v]|f[v+1]<<8|f[v+2]<<16|f[v+3]<<24,b=o(b,E),b=s(b,15),b=o(b,x),w^=b,w=s(w,13),w=o(w,5)+3864292196;switch(b=0,m){case 3:b^=f[v+2]<<16;case 2:b^=f[v+1]<<8;case 1:b^=f[v],b=o(b,E),b=s(b,15),b=o(b,x),w^=b}return w^=f.length,w=i(w),w>>>0},t.x86.hash128=function(f,p){if(t.inputValidation&&!n(f))return e;p=p||0;for(var m=f.length%16,y=f.length-m,w=p,b=p,E=p,x=p,v=0,I=0,S=0,R=0,T=597399067,P=2869860233,N=951274213,B=2716044179,k=0;k<y;k=k+16)v=f[k]|f[k+1]<<8|f[k+2]<<16|f[k+3]<<24,I=f[k+4]|f[k+5]<<8|f[k+6]<<16|f[k+7]<<24,S=f[k+8]|f[k+9]<<8|f[k+10]<<16|f[k+11]<<24,R=f[k+12]|f[k+13]<<8|f[k+14]<<16|f[k+15]<<24,v=o(v,T),v=s(v,15),v=o(v,P),w^=v,w=s(w,19),w+=b,w=o(w,5)+1444728091,I=o(I,P),I=s(I,16),I=o(I,N),b^=I,b=s(b,17),b+=E,b=o(b,5)+197830471,S=o(S,N),S=s(S,17),S=o(S,B),E^=S,E=s(E,15),E+=x,E=o(E,5)+2530024501,R=o(R,B),R=s(R,18),R=o(R,T),x^=R,x=s(x,13),x+=w,x=o(x,5)+850148119;switch(v=0,I=0,S=0,R=0,m){case 15:R^=f[k+14]<<16;case 14:R^=f[k+13]<<8;case 13:R^=f[k+12],R=o(R,B),R=s(R,18),R=o(R,T),x^=R;case 12:S^=f[k+11]<<24;case 11:S^=f[k+10]<<16;case 10:S^=f[k+9]<<8;case 9:S^=f[k+8],S=o(S,N),S=s(S,17),S=o(S,B),E^=S;case 8:I^=f[k+7]<<24;case 7:I^=f[k+6]<<16;case 6:I^=f[k+5]<<8;case 5:I^=f[k+4],I=o(I,P),I=s(I,16),I=o(I,N),b^=I;case 4:v^=f[k+3]<<24;case 3:v^=f[k+2]<<16;case 2:v^=f[k+1]<<8;case 1:v^=f[k],v=o(v,T),v=s(v,15),v=o(v,P),w^=v}return w^=f.length,b^=f.length,E^=f.length,x^=f.length,w+=b,w+=E,w+=x,b+=w,E+=w,x+=w,w=i(w),b=i(b),E=i(E),x=i(x),w+=b,w+=E,w+=x,b+=w,E+=w,x+=w,("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(E>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)},t.x64.hash128=function(f,p){if(t.inputValidation&&!n(f))return e;p=p||0;for(var m=f.length%16,y=f.length-m,w=[0,p],b=[0,p],E=[0,0],x=[0,0],v=[2277735313,289559509],I=[1291169091,658871167],S=0;S<y;S=S+16)E=[f[S+4]|f[S+5]<<8|f[S+6]<<16|f[S+7]<<24,f[S]|f[S+1]<<8|f[S+2]<<16|f[S+3]<<24],x=[f[S+12]|f[S+13]<<8|f[S+14]<<16|f[S+15]<<24,f[S+8]|f[S+9]<<8|f[S+10]<<16|f[S+11]<<24],E=c(E,v),E=l(E,31),E=c(E,I),w=u(w,E),w=l(w,27),w=a(w,b),w=a(c(w,[0,5]),[0,1390208809]),x=c(x,I),x=l(x,33),x=c(x,v),b=u(b,x),b=l(b,31),b=a(b,w),b=a(c(b,[0,5]),[0,944331445]);switch(E=[0,0],x=[0,0],m){case 15:x=u(x,d([0,f[S+14]],48));case 14:x=u(x,d([0,f[S+13]],40));case 13:x=u(x,d([0,f[S+12]],32));case 12:x=u(x,d([0,f[S+11]],24));case 11:x=u(x,d([0,f[S+10]],16));case 10:x=u(x,d([0,f[S+9]],8));case 9:x=u(x,[0,f[S+8]]),x=c(x,I),x=l(x,33),x=c(x,v),b=u(b,x);case 8:E=u(E,d([0,f[S+7]],56));case 7:E=u(E,d([0,f[S+6]],48));case 6:E=u(E,d([0,f[S+5]],40));case 5:E=u(E,d([0,f[S+4]],32));case 4:E=u(E,d([0,f[S+3]],24));case 3:E=u(E,d([0,f[S+2]],16));case 2:E=u(E,d([0,f[S+1]],8));case 1:E=u(E,[0,f[S]]),E=c(E,v),E=l(E,31),E=c(E,I),w=u(w,E)}return w=u(w,[0,f.length]),b=u(b,[0,f.length]),w=a(w,b),b=a(b,w),w=h(w),b=h(b),w=a(w,b),b=a(b,w),("00000000"+(w[0]>>>0).toString(16)).slice(-8)+("00000000"+(w[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof Ua<"u"?(typeof lu<"u"&&lu.exports&&(Ua=lu.exports=t),Ua.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(Ua)});var s6=Re((sF,o6)=>{o6.exports=n6()});var c6=Re((CF,a6)=>{var ui=1e3,di=ui*60,fi=di*60,ms=fi*24,CS=ms*7,NS=ms*365.25;a6.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return LS(r);if(t==="number"&&isFinite(r))return e.long?OS(r):PS(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function LS(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*NS;case"weeks":case"week":case"w":return t*CS;case"days":case"day":case"d":return t*ms;case"hours":case"hour":case"hrs":case"hr":case"h":return t*fi;case"minutes":case"minute":case"mins":case"min":case"m":return t*di;case"seconds":case"second":case"secs":case"sec":case"s":return t*ui;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function PS(r){var e=Math.abs(r);return e>=ms?Math.round(r/ms)+"d":e>=fi?Math.round(r/fi)+"h":e>=di?Math.round(r/di)+"m":e>=ui?Math.round(r/ui)+"s":r+"ms"}function OS(r){var e=Math.abs(r);return e>=ms?fu(r,e,ms,"day"):e>=fi?fu(r,e,fi,"hour"):e>=di?fu(r,e,di,"minute"):e>=ui?fu(r,e,ui,"second"):r+" ms"}function fu(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var u6=Re((NF,l6)=>{function BS(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=c6(),t.destroy=l,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let u=0;for(let h=0;h<d.length;h++)u=(u<<5)-u+d.charCodeAt(h),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(d){let u,h=null,f,p;function m(...y){if(!m.enabled)return;let w=m,b=Number(new Date),E=b-(u||b);w.diff=E,w.prev=u,w.curr=b,u=b,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let x=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(I,S)=>{if(I==="%%")return"%";x++;let R=t.formatters[S];if(typeof R=="function"){let T=y[x];I=R.call(w,T),y.splice(x,1),x--}return I}),t.formatArgs.call(w,y),(w.log||t.log).apply(w,y)}return m.namespace=d,m.useColors=t.useColors(),m.color=t.selectColor(d),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(f!==t.namespaces&&(f=t.namespaces,p=t.enabled(d)),p),set:y=>{h=y}}),typeof t.init=="function"&&t.init(m),m}function n(d,u){let h=t(this.namespace+(typeof u>"u"?":":u)+d);return h.log=this.log,h}function o(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let u,h=(typeof d=="string"?d:"").split(/[\s,]+/),f=h.length;for(u=0;u<f;u++)h[u]&&(d=h[u].replace(/\*/g,".*?"),d[0]==="-"?t.skips.push(new RegExp("^"+d.slice(1)+"$")):t.names.push(new RegExp("^"+d+"$")))}function s(){let d=[...t.names.map(a),...t.skips.map(a).map(u=>"-"+u)].join(",");return t.enable(""),d}function i(d){if(d[d.length-1]==="*")return!0;let u,h;for(u=0,h=t.skips.length;u<h;u++)if(t.skips[u].test(d))return!1;for(u=0,h=t.names.length;u<h;u++)if(t.names[u].test(d))return!0;return!1}function a(d){return d.toString().substring(2,d.toString().length-2).replace(/\.\*\?$/,"*")}function c(d){return d instanceof Error?d.stack||d.message:d}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}l6.exports=BS});var d6=Re((or,hu)=>{or.formatArgs=US;or.save=FS;or.load=VS;or.useColors=MS;or.storage=KS();or.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`."))}})();or.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 MS(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1: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&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function US(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+hu.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)}or.log=console.debug||console.log||(()=>{});function FS(r){try{r?or.storage.setItem("debug",r):or.storage.removeItem("debug")}catch{}}function VS(){let r;try{r=or.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function KS(){try{return localStorage}catch{}}hu.exports=u6()(or);var{formatters:$S}=hu.exports;$S.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var h6=Re((MF,S0)=>{"use strict";var qS=Object.prototype.hasOwnProperty,Ft="~";function Va(){}Object.create&&(Va.prototype=Object.create(null),new Va().__proto__||(Ft=!1));function GS(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function f6(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new GS(t,n||r,o),i=Ft?Ft+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function pu(r,e){--r._eventsCount===0?r._events=new Va:delete r._events[e]}function Pt(){this._events=new Va,this._eventsCount=0}Pt.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)qS.call(t,n)&&e.push(Ft?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Pt.prototype.listeners=function(e){var t=Ft?Ft+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Pt.prototype.listenerCount=function(e){var t=Ft?Ft+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Pt.prototype.emit=function(e,t,n,o,s,i){var a=Ft?Ft+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,d,u;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(u=1,d=new Array(l-1);u<l;u++)d[u-1]=arguments[u];c.fn.apply(c.context,d)}else{var h=c.length,f;for(u=0;u<h;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,o);break;default:if(!d)for(f=1,d=new Array(l-1);f<l;f++)d[f-1]=arguments[f];c[u].fn.apply(c[u].context,d)}}return!0};Pt.prototype.on=function(e,t,n){return f6(this,e,t,n,!1)};Pt.prototype.once=function(e,t,n){return f6(this,e,t,n,!0)};Pt.prototype.removeListener=function(e,t,n,o){var s=Ft?Ft+e:e;if(!this._events[s])return this;if(!t)return pu(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&pu(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:pu(this,s)}return this};Pt.prototype.removeAllListeners=function(e){var t;return e?(t=Ft?Ft+e:e,this._events[t]&&pu(this,t)):(this._events=new Va,this._eventsCount=0),this};Pt.prototype.off=Pt.prototype.removeListener;Pt.prototype.addListener=Pt.prototype.on;Pt.prefixed=Ft;Pt.EventEmitter=Pt;typeof S0<"u"&&(S0.exports=Pt)});var k0=Re((iV,y6)=>{y6.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var ig=Re(Za=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var l,d,u,h;return l=(c&255<<24)>>>24,d=(c&255<<16)>>>16,u=(c&65280)>>>8,h=c&255,[l,d,u,h].join(".")},i=function(c){var l,d,u,h,f,p;for(l=[],u=h=0;h<=3&&c.length!==0;u=++h){if(u>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),f=p[0],d=p[1],c=c.substring(d),l.push(f)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var l,d,u,h,f;for(h=0,l=10,d="9",u=0,c.length>1&&c[u]==="0"&&(c[u+1]==="x"||c[u+1]==="X"?(u+=2,l=16):"0"<=c[u+1]&&c[u+1]<="9"&&(u++,l=8,d="7")),f=u;u<c.length;){if("0"<=c[u]&&c[u]<=d)h=h*l+(t(c[u])-n)>>>0;else if(l===16)if("a"<=c[u]&&c[u]<="f")h=h*l+(10+t(c[u])-s)>>>0;else if("A"<=c[u]&&c[u]<="F")h=h*l+(10+t(c[u])-o)>>>0;else break;else break;if(h>4294967295)throw new Error("too large");u++}if(u===f)throw new Error("empty octet");return[h,u]},r=function(){function c(l,d){var u,h,f,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(d||(p=l.split("/",2),l=p[0],d=p[1]),d||(d=32),typeof d=="string"&&d.indexOf(".")>-1){try{this.maskLong=i(d)}catch(m){throw u=m,new Error("Invalid mask: "+d)}for(h=f=32;f>=0;h=--f)if(this.maskLong===4294967295<<32-h>>>0){this.bitmask=h;break}}else if(d||d===0)this.bitmask=parseInt(d,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(m){throw u=m,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+d);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var d,u,h;for(h=i(this.first),u=i(this.last),d=0;h<=u;)l(a(h),h,d),d++,h++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Za.ip2long=i,Za.long2ip=a,Za.Netmask=r}).call(Za)});var p1=Re((BW,R2)=>{var OW=function(){typeof R2<"u"&&(R2.exports=m);var r=86400,e=3200,t=146097*e/400,n=r*t,o=1e3*n,s=864e13,i=4294967296,a=1e6,c="000000000",l=Math.trunc||function(R){var T=R-R%1;return T==0&&(R<0||R===0&&1/R!=1/0)?-0:T},d=m.prototype,u=(m.fromDate=function(R){return new m(+R)},m.fromInt64BE=x(0,1,2,3,0,4),m.fromInt64LE=x(3,2,1,0,4,0),m.fromString=function(N){var T,P=new m,N=(N+="").replace(/^\s*[+\-]?\d+/,function(k){var k=+k,X=1970+(k-1970)%400;return P.year=k-X,X}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function(B,k,X){return k<0&&(X*=-1),T=6e4*(60*+k+ +X),""}).replace(/\.\d+$/,function(B){return P.nano=+(B+c).substr(1,9),""}).split(/\D+/);if(1<N.length?N[1]--:N[1]=0,P.time=T=Date.UTC.apply(Date,N)-(T||0),isNaN(T))throw new TypeError("Invalid Date");return y(P)},m.fromTimeT=function(R){return b(R,0)},d.year=0,d.time=0,d.nano=0,d.addNano=function(R){return this.nano+=+R||0,this},d.getNano=function(){var R=y(this);return(R.time%1e3*a+ +R.nano+1e9)%1e9},d.getTimeT=function(){var T=y(this),R=Math.floor(T.time/1e3),T=T.year;return T&&(R+=T*t*r/e),R},d.getYear=function(){return this.toDate().getUTCFullYear()+this.year},d.toDate=function(){return w(y(this).time)},d.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},d.toString=function(R){var T=this,P=T.toDate(),N={H:function(){return I(P.getUTCHours())},L:function(){return S(P.getUTCMilliseconds(),3)},M:function(){return I(P.getUTCMinutes())},N:function(){return S(T.getNano(),9)},S:function(){return I(P.getUTCSeconds())},Y:function(){var B=T.getYear();return 999999<B?"+"+B:9999<B?"+"+S(B,6):0<=B?S(B,4):-999999<=B?"-"+S(-B,6):B},a:function(){return f[P.getUTCDay()]},b:function(){return h[P.getUTCMonth()]},d:function(){return I(P.getUTCDate())},e:function(){return function(B){return(9<B?"":" ")+(0|B)}(P.getUTCDate())},m:function(){return I(P.getUTCMonth()+1)}};return function B(k){return k.replace(/%./g,function(X){var L=X[1],D=p[L],L=N[L];return D?B(D):L?L():X})}(R||u)},d.writeInt64BE=E(0,1,2,3,0,4),d.writeInt64LE=E(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),h=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],f=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],p={"%":"%",F:"%Y-%m-%d",n:`
|
|
2
|
+
"use strict";var Helia=(()=>{var Bb=Object.create;var Bc=Object.defineProperty;var Mb=Object.getOwnPropertyDescriptor;var Ub=Object.getOwnPropertyNames;var Fb=Object.getPrototypeOf,Vb=Object.prototype.hasOwnProperty;var ke=(r,e)=>()=>(r&&(e=r(r=0)),e);var Re=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),pe=(r,e)=>{for(var t in e)Bc(r,t,{get:e[t],enumerable:!0})},x4=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ub(e))!Vb.call(r,o)&&o!==t&&Bc(r,o,{get:()=>e[o],enumerable:!(n=Mb(e,o))||n.enumerable});return r};var Qe=(r,e,t)=>(t=r!=null?Bb(Fb(r)):{},x4(e||!r||!r.__esModule?Bc(t,"default",{value:r,enumerable:!0}):t,r)),Mc=r=>x4(Bc({},"__esModule",{value:!0}),r);var Yo=Re((ML,I4)=>{"use strict";function A4(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function jb(r,e,t){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");t||(t={}),typeof e=="object"&&(t=e,e=""),e&&(t.code=e);try{return A4(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),A4(new o,t)}}I4.exports=jb});var j8=Re(si=>{"use strict";var GR="[object ArrayBuffer]",Pn=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===GR}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},r0="string",WR=/^[0-9a-f]+$/i,zR=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,YR=/^[a-zA-Z0-9-_]+$/,El=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=Pn.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},Sr=class{static toString(e,t=!1){let n=Pn.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},bl=class r{static isHex(e){return typeof e===r0&&WR.test(e)}static isBase64(e){return typeof e===r0&&zR.test(e)}static isBase64Url(e){return typeof e===r0&&YR.test(e)}static ToString(e,t="utf8"){let n=Pn.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 Sr.toString(n,!0);case"utf16":case"utf16be":return Sr.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 Sr.fromString(e,!0);case"utf16":case"utf16be":return Sr.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=Pn.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 El.fromString(e);case"utf16":case"utf16be":return Sr.fromString(e);case"utf16le":case"usc2":return Sr.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 El.toString(e);case"utf16":case"utf16be":return Sr.toString(e);case"utf16le":case"usc2":return Sr.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=Pn.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=Pn.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return Sr.toString(e,t)}static FromUtf16String(e,t=!1){return Sr.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,"")||""}};bl.DEFAULT_UTF8_ENCODING="utf8";function XR(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function QR(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function jR(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}si.BufferSourceConverter=Pn;si.Convert=bl;si.assign=XR;si.combine=QR;si.isEqual=jR});var n6=Re((Ua,lu)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(f){if(!Array.isArray(f)&&!ArrayBuffer.isView(f))return!1;for(var p=0;p<f.length;p++)if(!Number.isInteger(f[p])||f[p]<0||f[p]>255)return!1;return!0}function o(f,p){return(f&65535)*p+(((f>>>16)*p&65535)<<16)}function s(f,p){return f<<p|f>>>32-p}function i(f){return f^=f>>>16,f=o(f,2246822507),f^=f>>>13,f=o(f,3266489909),f^=f>>>16,f}function a(f,p){f=[f[0]>>>16,f[0]&65535,f[1]>>>16,f[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=f[3]+p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=f[2]+p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=f[1]+p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=f[0]+p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function c(f,p){f=[f[0]>>>16,f[0]&65535,f[1]>>>16,f[1]&65535],p=[p[0]>>>16,p[0]&65535,p[1]>>>16,p[1]&65535];var m=[0,0,0,0];return m[3]+=f[3]*p[3],m[2]+=m[3]>>>16,m[3]&=65535,m[2]+=f[2]*p[3],m[1]+=m[2]>>>16,m[2]&=65535,m[2]+=f[3]*p[2],m[1]+=m[2]>>>16,m[2]&=65535,m[1]+=f[1]*p[3],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=f[2]*p[2],m[0]+=m[1]>>>16,m[1]&=65535,m[1]+=f[3]*p[1],m[0]+=m[1]>>>16,m[1]&=65535,m[0]+=f[0]*p[3]+f[1]*p[2]+f[2]*p[1]+f[3]*p[0],m[0]&=65535,[m[0]<<16|m[1],m[2]<<16|m[3]]}function l(f,p){return p%=64,p===32?[f[1],f[0]]:p<32?[f[0]<<p|f[1]>>>32-p,f[1]<<p|f[0]>>>32-p]:(p-=32,[f[1]<<p|f[0]>>>32-p,f[0]<<p|f[1]>>>32-p])}function d(f,p){return p%=64,p===0?f:p<32?[f[0]<<p|f[1]>>>32-p,f[1]<<p]:[f[1]<<p-32,0]}function u(f,p){return[f[0]^p[0],f[1]^p[1]]}function h(f){return f=u(f,[0,f[0]>>>1]),f=c(f,[4283543511,3981806797]),f=u(f,[0,f[0]>>>1]),f=c(f,[3301882366,444984403]),f=u(f,[0,f[0]>>>1]),f}t.x86.hash32=function(f,p){if(t.inputValidation&&!n(f))return e;p=p||0;for(var m=f.length%4,y=f.length-m,w=p,b=0,E=3432918353,x=461845907,v=0;v<y;v=v+4)b=f[v]|f[v+1]<<8|f[v+2]<<16|f[v+3]<<24,b=o(b,E),b=s(b,15),b=o(b,x),w^=b,w=s(w,13),w=o(w,5)+3864292196;switch(b=0,m){case 3:b^=f[v+2]<<16;case 2:b^=f[v+1]<<8;case 1:b^=f[v],b=o(b,E),b=s(b,15),b=o(b,x),w^=b}return w^=f.length,w=i(w),w>>>0},t.x86.hash128=function(f,p){if(t.inputValidation&&!n(f))return e;p=p||0;for(var m=f.length%16,y=f.length-m,w=p,b=p,E=p,x=p,v=0,I=0,S=0,R=0,T=597399067,P=2869860233,N=951274213,B=2716044179,k=0;k<y;k=k+16)v=f[k]|f[k+1]<<8|f[k+2]<<16|f[k+3]<<24,I=f[k+4]|f[k+5]<<8|f[k+6]<<16|f[k+7]<<24,S=f[k+8]|f[k+9]<<8|f[k+10]<<16|f[k+11]<<24,R=f[k+12]|f[k+13]<<8|f[k+14]<<16|f[k+15]<<24,v=o(v,T),v=s(v,15),v=o(v,P),w^=v,w=s(w,19),w+=b,w=o(w,5)+1444728091,I=o(I,P),I=s(I,16),I=o(I,N),b^=I,b=s(b,17),b+=E,b=o(b,5)+197830471,S=o(S,N),S=s(S,17),S=o(S,B),E^=S,E=s(E,15),E+=x,E=o(E,5)+2530024501,R=o(R,B),R=s(R,18),R=o(R,T),x^=R,x=s(x,13),x+=w,x=o(x,5)+850148119;switch(v=0,I=0,S=0,R=0,m){case 15:R^=f[k+14]<<16;case 14:R^=f[k+13]<<8;case 13:R^=f[k+12],R=o(R,B),R=s(R,18),R=o(R,T),x^=R;case 12:S^=f[k+11]<<24;case 11:S^=f[k+10]<<16;case 10:S^=f[k+9]<<8;case 9:S^=f[k+8],S=o(S,N),S=s(S,17),S=o(S,B),E^=S;case 8:I^=f[k+7]<<24;case 7:I^=f[k+6]<<16;case 6:I^=f[k+5]<<8;case 5:I^=f[k+4],I=o(I,P),I=s(I,16),I=o(I,N),b^=I;case 4:v^=f[k+3]<<24;case 3:v^=f[k+2]<<16;case 2:v^=f[k+1]<<8;case 1:v^=f[k],v=o(v,T),v=s(v,15),v=o(v,P),w^=v}return w^=f.length,b^=f.length,E^=f.length,x^=f.length,w+=b,w+=E,w+=x,b+=w,E+=w,x+=w,w=i(w),b=i(b),E=i(E),x=i(x),w+=b,w+=E,w+=x,b+=w,E+=w,x+=w,("00000000"+(w>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(E>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)},t.x64.hash128=function(f,p){if(t.inputValidation&&!n(f))return e;p=p||0;for(var m=f.length%16,y=f.length-m,w=[0,p],b=[0,p],E=[0,0],x=[0,0],v=[2277735313,289559509],I=[1291169091,658871167],S=0;S<y;S=S+16)E=[f[S+4]|f[S+5]<<8|f[S+6]<<16|f[S+7]<<24,f[S]|f[S+1]<<8|f[S+2]<<16|f[S+3]<<24],x=[f[S+12]|f[S+13]<<8|f[S+14]<<16|f[S+15]<<24,f[S+8]|f[S+9]<<8|f[S+10]<<16|f[S+11]<<24],E=c(E,v),E=l(E,31),E=c(E,I),w=u(w,E),w=l(w,27),w=a(w,b),w=a(c(w,[0,5]),[0,1390208809]),x=c(x,I),x=l(x,33),x=c(x,v),b=u(b,x),b=l(b,31),b=a(b,w),b=a(c(b,[0,5]),[0,944331445]);switch(E=[0,0],x=[0,0],m){case 15:x=u(x,d([0,f[S+14]],48));case 14:x=u(x,d([0,f[S+13]],40));case 13:x=u(x,d([0,f[S+12]],32));case 12:x=u(x,d([0,f[S+11]],24));case 11:x=u(x,d([0,f[S+10]],16));case 10:x=u(x,d([0,f[S+9]],8));case 9:x=u(x,[0,f[S+8]]),x=c(x,I),x=l(x,33),x=c(x,v),b=u(b,x);case 8:E=u(E,d([0,f[S+7]],56));case 7:E=u(E,d([0,f[S+6]],48));case 6:E=u(E,d([0,f[S+5]],40));case 5:E=u(E,d([0,f[S+4]],32));case 4:E=u(E,d([0,f[S+3]],24));case 3:E=u(E,d([0,f[S+2]],16));case 2:E=u(E,d([0,f[S+1]],8));case 1:E=u(E,[0,f[S]]),E=c(E,v),E=l(E,31),E=c(E,I),w=u(w,E)}return w=u(w,[0,f.length]),b=u(b,[0,f.length]),w=a(w,b),b=a(b,w),w=h(w),b=h(b),w=a(w,b),b=a(b,w),("00000000"+(w[0]>>>0).toString(16)).slice(-8)+("00000000"+(w[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof Ua<"u"?(typeof lu<"u"&&lu.exports&&(Ua=lu.exports=t),Ua.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(Ua)});var s6=Re((sF,o6)=>{o6.exports=n6()});var c6=Re((CF,a6)=>{var ui=1e3,di=ui*60,fi=di*60,ms=fi*24,CS=ms*7,NS=ms*365.25;a6.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return LS(r);if(t==="number"&&isFinite(r))return e.long?OS(r):PS(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function LS(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*NS;case"weeks":case"week":case"w":return t*CS;case"days":case"day":case"d":return t*ms;case"hours":case"hour":case"hrs":case"hr":case"h":return t*fi;case"minutes":case"minute":case"mins":case"min":case"m":return t*di;case"seconds":case"second":case"secs":case"sec":case"s":return t*ui;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function PS(r){var e=Math.abs(r);return e>=ms?Math.round(r/ms)+"d":e>=fi?Math.round(r/fi)+"h":e>=di?Math.round(r/di)+"m":e>=ui?Math.round(r/ui)+"s":r+"ms"}function OS(r){var e=Math.abs(r);return e>=ms?fu(r,e,ms,"day"):e>=fi?fu(r,e,fi,"hour"):e>=di?fu(r,e,di,"minute"):e>=ui?fu(r,e,ui,"second"):r+" ms"}function fu(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var u6=Re((NF,l6)=>{function BS(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=c6(),t.destroy=l,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let u=0;for(let h=0;h<d.length;h++)u=(u<<5)-u+d.charCodeAt(h),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(d){let u,h=null,f,p;function m(...y){if(!m.enabled)return;let w=m,b=Number(new Date),E=b-(u||b);w.diff=E,w.prev=u,w.curr=b,u=b,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let x=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(I,S)=>{if(I==="%%")return"%";x++;let R=t.formatters[S];if(typeof R=="function"){let T=y[x];I=R.call(w,T),y.splice(x,1),x--}return I}),t.formatArgs.call(w,y),(w.log||t.log).apply(w,y)}return m.namespace=d,m.useColors=t.useColors(),m.color=t.selectColor(d),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(f!==t.namespaces&&(f=t.namespaces,p=t.enabled(d)),p),set:y=>{h=y}}),typeof t.init=="function"&&t.init(m),m}function n(d,u){let h=t(this.namespace+(typeof u>"u"?":":u)+d);return h.log=this.log,h}function o(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let u,h=(typeof d=="string"?d:"").split(/[\s,]+/),f=h.length;for(u=0;u<f;u++)h[u]&&(d=h[u].replace(/\*/g,".*?"),d[0]==="-"?t.skips.push(new RegExp("^"+d.slice(1)+"$")):t.names.push(new RegExp("^"+d+"$")))}function s(){let d=[...t.names.map(a),...t.skips.map(a).map(u=>"-"+u)].join(",");return t.enable(""),d}function i(d){if(d[d.length-1]==="*")return!0;let u,h;for(u=0,h=t.skips.length;u<h;u++)if(t.skips[u].test(d))return!1;for(u=0,h=t.names.length;u<h;u++)if(t.names[u].test(d))return!0;return!1}function a(d){return d.toString().substring(2,d.toString().length-2).replace(/\.\*\?$/,"*")}function c(d){return d instanceof Error?d.stack||d.message:d}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}l6.exports=BS});var d6=Re((or,hu)=>{or.formatArgs=US;or.save=FS;or.load=VS;or.useColors=MS;or.storage=KS();or.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`."))}})();or.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 MS(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1: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&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function US(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+hu.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)}or.log=console.debug||console.log||(()=>{});function FS(r){try{r?or.storage.setItem("debug",r):or.storage.removeItem("debug")}catch{}}function VS(){let r;try{r=or.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function KS(){try{return localStorage}catch{}}hu.exports=u6()(or);var{formatters:$S}=hu.exports;$S.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var h6=Re((MF,S0)=>{"use strict";var qS=Object.prototype.hasOwnProperty,Ft="~";function Va(){}Object.create&&(Va.prototype=Object.create(null),new Va().__proto__||(Ft=!1));function GS(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function f6(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new GS(t,n||r,o),i=Ft?Ft+e:e;return r._events[i]?r._events[i].fn?r._events[i]=[r._events[i],s]:r._events[i].push(s):(r._events[i]=s,r._eventsCount++),r}function pu(r,e){--r._eventsCount===0?r._events=new Va:delete r._events[e]}function Pt(){this._events=new Va,this._eventsCount=0}Pt.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)qS.call(t,n)&&e.push(Ft?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Pt.prototype.listeners=function(e){var t=Ft?Ft+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,s=n.length,i=new Array(s);o<s;o++)i[o]=n[o].fn;return i};Pt.prototype.listenerCount=function(e){var t=Ft?Ft+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Pt.prototype.emit=function(e,t,n,o,s,i){var a=Ft?Ft+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,d,u;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,o),!0;case 5:return c.fn.call(c.context,t,n,o,s),!0;case 6:return c.fn.call(c.context,t,n,o,s,i),!0}for(u=1,d=new Array(l-1);u<l;u++)d[u-1]=arguments[u];c.fn.apply(c.context,d)}else{var h=c.length,f;for(u=0;u<h;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,o);break;default:if(!d)for(f=1,d=new Array(l-1);f<l;f++)d[f-1]=arguments[f];c[u].fn.apply(c[u].context,d)}}return!0};Pt.prototype.on=function(e,t,n){return f6(this,e,t,n,!1)};Pt.prototype.once=function(e,t,n){return f6(this,e,t,n,!0)};Pt.prototype.removeListener=function(e,t,n,o){var s=Ft?Ft+e:e;if(!this._events[s])return this;if(!t)return pu(this,s),this;var i=this._events[s];if(i.fn)i.fn===t&&(!o||i.once)&&(!n||i.context===n)&&pu(this,s);else{for(var a=0,c=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||n&&i[a].context!==n)&&c.push(i[a]);c.length?this._events[s]=c.length===1?c[0]:c:pu(this,s)}return this};Pt.prototype.removeAllListeners=function(e){var t;return e?(t=Ft?Ft+e:e,this._events[t]&&pu(this,t)):(this._events=new Va,this._eventsCount=0),this};Pt.prototype.off=Pt.prototype.removeListener;Pt.prototype.addListener=Pt.prototype.on;Pt.prefixed=Ft;Pt.EventEmitter=Pt;typeof S0<"u"&&(S0.exports=Pt)});var k0=Re((iV,y6)=>{y6.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(s,i){t[s]=i,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(s){return t[s]!==void 0||n[s]!==void 0},remove:function(s){t[s]!==void 0&&(t[s]=void 0),n[s]!==void 0&&(n[s]=void 0)},get:function(s){var i=t[s];if(i!==void 0)return i;if((i=n[s])!==void 0)return o(s,i),i},set:function(s,i){t[s]!==void 0?t[s]=i:o(s,i)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var ig=Re(Za=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var l,d,u,h;return l=(c&255<<24)>>>24,d=(c&255<<16)>>>16,u=(c&65280)>>>8,h=c&255,[l,d,u,h].join(".")},i=function(c){var l,d,u,h,f,p;for(l=[],u=h=0;h<=3&&c.length!==0;u=++h){if(u>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}p=e(c),f=p[0],d=p[1],c=c.substring(d),l.push(f)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),s=t("a"),o=t("A"),e=function(c){var l,d,u,h,f;for(h=0,l=10,d="9",u=0,c.length>1&&c[u]==="0"&&(c[u+1]==="x"||c[u+1]==="X"?(u+=2,l=16):"0"<=c[u+1]&&c[u+1]<="9"&&(u++,l=8,d="7")),f=u;u<c.length;){if("0"<=c[u]&&c[u]<=d)h=h*l+(t(c[u])-n)>>>0;else if(l===16)if("a"<=c[u]&&c[u]<="f")h=h*l+(10+t(c[u])-s)>>>0;else if("A"<=c[u]&&c[u]<="F")h=h*l+(10+t(c[u])-o)>>>0;else break;else break;if(h>4294967295)throw new Error("too large");u++}if(u===f)throw new Error("empty octet");return[h,u]},r=function(){function c(l,d){var u,h,f,p;if(typeof l!="string")throw new Error("Missing `net' parameter");if(d||(p=l.split("/",2),l=p[0],d=p[1]),d||(d=32),typeof d=="string"&&d.indexOf(".")>-1){try{this.maskLong=i(d)}catch(m){throw u=m,new Error("Invalid mask: "+d)}for(h=f=32;f>=0;h=--f)if(this.maskLong===4294967295<<32-h>>>0){this.bitmask=h;break}}else if(d||d===0)this.bitmask=parseInt(d,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(i(l)&this.maskLong)>>>0}catch(m){throw u=m,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+d);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(i(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var d,u,h;for(h=i(this.first),u=i(this.last),d=0;h<=u;)l(a(h),h,d),d++,h++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Za.ip2long=i,Za.long2ip=a,Za.Netmask=r}).call(Za)});var p1=Re((BW,R2)=>{var OW=function(){typeof R2<"u"&&(R2.exports=m);var r=86400,e=3200,t=146097*e/400,n=r*t,o=1e3*n,s=864e13,i=4294967296,a=1e6,c="000000000",l=Math.trunc||function(R){var T=R-R%1;return T==0&&(R<0||R===0&&1/R!=1/0)?-0:T},d=m.prototype,u=(m.fromDate=function(R){return new m(+R)},m.fromInt64BE=x(0,1,2,3,0,4),m.fromInt64LE=x(3,2,1,0,4,0),m.fromString=function(N){var T,P=new m,N=(N+="").replace(/^\s*[+\-]?\d+/,function(k){var k=+k,X=1970+(k-1970)%400;return P.year=k-X,X}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function(B,k,X){return k<0&&(X*=-1),T=6e4*(60*+k+ +X),""}).replace(/\.\d+$/,function(B){return P.nano=+(B+c).substr(1,9),""}).split(/\D+/);if(1<N.length?N[1]--:N[1]=0,P.time=T=Date.UTC.apply(Date,N)-(T||0),isNaN(T))throw new TypeError("Invalid Date");return y(P)},m.fromTimeT=function(R){return b(R,0)},d.year=0,d.time=0,d.nano=0,d.addNano=function(R){return this.nano+=+R||0,this},d.getNano=function(){var R=y(this);return(R.time%1e3*a+ +R.nano+1e9)%1e9},d.getTimeT=function(){var T=y(this),R=Math.floor(T.time/1e3),T=T.year;return T&&(R+=T*t*r/e),R},d.getYear=function(){return this.toDate().getUTCFullYear()+this.year},d.toDate=function(){return w(y(this).time)},d.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},d.toString=function(R){var T=this,P=T.toDate(),N={H:function(){return I(P.getUTCHours())},L:function(){return S(P.getUTCMilliseconds(),3)},M:function(){return I(P.getUTCMinutes())},N:function(){return S(T.getNano(),9)},S:function(){return I(P.getUTCSeconds())},Y:function(){var B=T.getYear();return 999999<B?"+"+B:9999<B?"+"+S(B,6):0<=B?S(B,4):-999999<=B?"-"+S(-B,6):B},a:function(){return f[P.getUTCDay()]},b:function(){return h[P.getUTCMonth()]},d:function(){return I(P.getUTCDate())},e:function(){return function(B){return(9<B?"":" ")+(0|B)}(P.getUTCDate())},m:function(){return I(P.getUTCMonth()+1)}};return function B(k){return k.replace(/%./g,function(X){var L=X[1],D=p[L],L=N[L];return D?B(D):L?L():X})}(R||u)},d.writeInt64BE=E(0,1,2,3,0,4),d.writeInt64LE=E(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),h=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],f=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],p={"%":"%",F:"%Y-%m-%d",n:`
|
|
3
3
|
`,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return m;function m(R,T,P){var N=this;if(!(N instanceof m))return new m(R,T,P);N.time=+R||0,N.nano=+T||0,N.year=+P||0,y(N)}function y(R){var T,P,N,B=R.year,k=R.time,X=R.nano,D=((X<0||a<=X)&&(X-=(P=Math.floor(X/a))*a,k+=P,P=1),B%e);return(k<-s||s<k||D)&&((T=l(k/o))&&(B+=T*e,k-=T*o),(N=w(k)).setUTCFullYear(D+N.getUTCFullYear()),N=(k=+N)+(T=l((B-=D)/e))*o,T&&-s<=N&&N<=s&&(B-=T*e,k=N),P=1),P&&(R.year=B,R.time=k,R.nano=X),R}function w(R){var T=new Date(0);return T.setTime(R),T}function b(B,N){B=+B||0;var P=l((N=(N|0)*i)/n)+l(B/n),N=N%n+B%n,B=l(N/n);return B&&(P+=B,N-=B*n),new m(1e3*N,0,P*e)}function E(R,T,P,N,B,k){return function(D,L){var C=y(this);D=D||new Array(8),v(D,L|=0);var A=Math.floor(C.time/1e3),C=C.year*(t*r/e),$=l(C/i)+l(A/i),C=C%i+A%i,A=Math.floor(C/i);return A&&($+=A,C-=A*i),X(D,L+B,$),X(D,L+k,C),D};function X(D,L,$){D[L+R]=$>>24&255,D[L+T]=$>>16&255,D[L+P]=$>>8&255,D[L+N]=255&$}}function x(R,T,P,N,B,k){return function(D,L){v(D,L|=0);var $=X(D,L+B);return b(X(D,L+k),$)};function X(D,L){return 16777216*D[L+R]+(D[L+T]<<16|D[L+P]<<8|D[L+N])}}function v(R,T){if(R=R&&R.length,R==null)throw new TypeError("Invalid Buffer");if(R<T+8)throw new RangeError("Out of range")}function I(R){return(9<R?"":"0")+(0|R)}function S(R,T){return(c+(0|R)).substr(-T)}}()});var O9=Re((_ee,P9)=>{function pD(){return!!(typeof window<"u"&&typeof window.process=="object"&&window.process.type==="renderer"||typeof process<"u"&&typeof process.versions=="object"&&process.versions.electron||typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Electron")>=0)}P9.exports=pD});var gy=Re((zoe,my)=>{"use strict";my.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var vy=Re((by,xy)=>{"use strict";var Td=gy(),{hasOwnProperty:wy}=Object.prototype,{propertyIsEnumerable:YD}=Object,zi=(r,e,t)=>Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}),XD=by,yy={concatArrays:!1,ignoreUndefined:!1},kd=r=>{let e=[];for(let t in r)wy.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)YD.call(r,n)&&e.push(n)}return e};function Yi(r){return Array.isArray(r)?QD(r):Td(r)?jD(r):r}function QD(r){let e=r.slice(0,0);return kd(r).forEach(t=>{zi(e,t,Yi(r[t]))}),e}function jD(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return kd(r).forEach(t=>{zi(e,t,Yi(r[t]))}),e}var Ey=(r,e,t,n)=>(t.forEach(o=>{typeof e[o]>"u"&&n.ignoreUndefined||(o in r&&r[o]!==Object.getPrototypeOf(r)?zi(r,o,$p(r[o],e[o],n)):zi(r,o,Yi(e[o])))}),r),ZD=(r,e,t)=>{let n=r.slice(0,0),o=0;return[r,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)wy.call(s,a)&&(i.push(String(a)),s===r?zi(n,o++,s[a]):zi(n,o++,Yi(s[a])));n=Ey(n,s,kd(s).filter(a=>!i.includes(a)),t)}),n};function $p(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?ZD(r,e,t):!Td(e)||!Td(r)?Yi(e):Ey(r,e,kd(e),t)}xy.exports=function(...r){let e=$p(Yi(yy),this!==XD&&this||{},yy),t={_:{}};for(let n of r)if(n!==void 0){if(!Td(n))throw new TypeError("`"+n+"` is not an Option Object");t=$p(t,{_:n},e)}return t._}});var _y=Re((Xoe,Sy)=>{"use strict";function JD(r){return r>=55296&&r<=56319}function eT(r){return r>=56320&&r<=57343}Sy.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var o=t.length,s=0,i,a,c=0;c<o;c+=1){if(i=t.charCodeAt(c),a=t[c],JD(i)&&eT(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),s+=e(a),s===n)return t.slice(0,c+1);if(s>n)return t.slice(0,c-a.length+1)}return t}});var Iy=Re((Qoe,Ay)=>{"use strict";function tT(r){return r>=55296&&r<=56319}function rT(r){return r>=56320&&r<=57343}Ay.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,o=null,s=null,i=0;i<t;i++)o=e.charCodeAt(i),rT(o)?s!=null&&tT(s)?n+=1:n+=3:o<=127?n+=1:o>=128&&o<=2047?n+=2:o>=2048&&o<=65535&&(n+=3),s=o;return n}});var Ty=Re((joe,Dy)=>{"use strict";var nT=_y(),oT=Iy();Dy.exports=nT.bind(null,oT)});var Ny=Re((Zoe,Cy)=>{"use strict";var sT=Ty(),iT=/[\/\?<>\\:\*\|"]/g,aT=/[\x00-\x1f\x80-\x9f]/g,cT=/^\.+$/,lT=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,uT=/[\. ]+$/;function ky(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(iT,e).replace(aT,e).replace(cT,e).replace(lT,e).replace(uT,e);return sT(t,255)}Cy.exports=function(r,e){var t=e&&e.replacement||"",n=ky(r,t);return t===""?n:ky(n,"")}});var aw=Re((cae,iw)=>{"use strict";function XT(r){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),t=0;t<e.length;t++)e[t]=255;for(var n=0;n<r.length;n++){var o=r.charAt(n),s=o.charCodeAt(0);if(e[s]!==255)throw new TypeError(o+" is ambiguous");e[s]=n}var i=r.length,a=r.charAt(0),c=Math.log(i)/Math.log(256),l=Math.log(256)/Math.log(i);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var p=0,m=0,y=0,w=f.length;y!==w&&f[y]===0;)y++,p++;for(var b=(w-y)*l+1>>>0,E=new Uint8Array(b);y!==w;){for(var x=f[y],v=0,I=b-1;(x!==0||v<m)&&I!==-1;I--,v++)x+=256*E[I]>>>0,E[I]=x%i>>>0,x=x/i>>>0;if(x!==0)throw new Error("Non-zero carry");m=v,y++}for(var S=b-m;S!==b&&E[S]===0;)S++;for(var R=a.repeat(p);S<b;++S)R+=r.charAt(E[S]);return R}function u(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var p=0;if(f[p]!==" "){for(var m=0,y=0;f[p]===a;)m++,p++;for(var w=(f.length-p)*c+1>>>0,b=new Uint8Array(w);f[p];){var E=e[f.charCodeAt(p)];if(E===255)return;for(var x=0,v=w-1;(E!==0||x<y)&&v!==-1;v--,x++)E+=i*b[v]>>>0,b[v]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");y=x,p++}if(f[p]!==" "){for(var I=w-y;I!==w&&b[I]===0;)I++;for(var S=new Uint8Array(m+(w-I)),R=m;I!==w;)S[R++]=b[I++];return S}}}function h(f){var p=u(f);if(p)return p;throw new Error("Non-base"+i+" character")}return{encode:d,decodeUnsafe:u,decode:h}}iw.exports=XT});var qd=Re((lae,cw)=>{"use strict";var QT=new TextDecoder,jT=r=>QT.decode(r),ZT=new TextEncoder,JT=r=>ZT.encode(r);function ek(r,e){let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}cw.exports={decodeText:jT,encodeText:JT,concat:ek}});var uw=Re((uae,lw)=>{"use strict";var{encodeText:tk}=qd(),c3=class{constructor(e,t,n,o){this.name=e,this.code=t,this.codeBuf=tk(this.code),this.alphabet=o,this.codec=n(o)}encode(e){return this.codec.encode(e)}decode(e){for(let t of e)if(this.alphabet&&this.alphabet.indexOf(t)<0)throw new Error(`invalid character '${t}' in '${e}'`);return this.codec.decode(e)}};lw.exports=c3});var fw=Re((dae,dw)=>{"use strict";var rk=(r,e,t)=>{let n={};for(let l=0;l<e.length;++l)n[e[l]]=l;let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let d=n[r[l]];if(d===void 0)throw new SyntaxError("Invalid character "+r[l]);a=a<<t|d,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||255&a<<8-i)throw new SyntaxError("Unexpected end of data");return s},nk=(r,e,t)=>{let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i&&(s+=e[o&a<<t-i]),n)for(;s.length*t&7;)s+="=";return s},ok=r=>e=>({encode(t){return nk(t,e,r)},decode(t){return rk(t,e,r)}});dw.exports={rfc4648:ok}});var gw=Re((fae,mw)=>{"use strict";var _c=aw(),sk=uw(),{rfc4648:At}=fw(),{decodeText:ik,encodeText:ak}=qd(),ck=()=>({encode:ik,decode:ak}),hw=[["identity","\0",ck,""],["base2","0",At(1),"01"],["base8","7",At(3),"01234567"],["base10","9",_c,"0123456789"],["base16","f",At(4),"0123456789abcdef"],["base16upper","F",At(4),"0123456789ABCDEF"],["base32hex","v",At(5),"0123456789abcdefghijklmnopqrstuv"],["base32hexupper","V",At(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV"],["base32hexpad","t",At(5),"0123456789abcdefghijklmnopqrstuv="],["base32hexpadupper","T",At(5),"0123456789ABCDEFGHIJKLMNOPQRSTUV="],["base32","b",At(5),"abcdefghijklmnopqrstuvwxyz234567"],["base32upper","B",At(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"],["base32pad","c",At(5),"abcdefghijklmnopqrstuvwxyz234567="],["base32padupper","C",At(5),"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="],["base32z","h",At(5),"ybndrfg8ejkmcpqxot1uwisza345h769"],["base36","k",_c,"0123456789abcdefghijklmnopqrstuvwxyz"],["base36upper","K",_c,"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"],["base58btc","z",_c,"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"],["base58flickr","Z",_c,"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"],["base64","m",At(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"],["base64pad","M",At(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="],["base64url","u",At(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"],["base64urlpad","U",At(6),"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="]],pw=hw.reduce((r,e)=>(r[e[0]]=new sk(e[0],e[1],e[2],e[3]),r),{}),lk=hw.reduce((r,e)=>(r[e[1]]=pw[e[0]],r),{});mw.exports={names:pw,codes:lk}});var Ew=Re((jn,ww)=>{"use strict";var Ji=gw(),{encodeText:uk,decodeText:Gd,concat:yw}=qd();function dk(r,e){if(!e)throw new Error("requires an encoded Uint8Array");let{name:t,codeBuf:n}=Ns(r);return mk(t,e),yw([n,e],n.length+e.length)}function fk(r,e){let t=Ns(r),n=uk(t.encode(e));return yw([t.codeBuf,n],t.codeBuf.length+n.length)}function hk(r){r instanceof Uint8Array&&(r=Gd(r));let e=r[0];return["f","F","v","V","t","T","b","B","c","C","h","k","K"].includes(e)&&(r=r.toLowerCase()),Ns(r[0]).decode(r.substring(1))}function pk(r){if(r instanceof Uint8Array&&(r=Gd(r)),Object.prototype.toString.call(r)!=="[object String]")return!1;try{return Ns(r[0]).name}catch{return!1}}function mk(r,e){Ns(r).decode(Gd(e))}function Ns(r){if(Object.prototype.hasOwnProperty.call(Ji.names,r))return Ji.names[r];if(Object.prototype.hasOwnProperty.call(Ji.codes,r))return Ji.codes[r];throw new Error(`Unsupported encoding: ${r}`)}function gk(r){return r instanceof Uint8Array&&(r=Gd(r)),Ns(r[0])}jn=ww.exports=dk;jn.encode=fk;jn.decode=hk;jn.isEncoded=pk;jn.encoding=Ns;jn.encodingFromData=gk;var yk=Object.freeze(Ji.names),wk=Object.freeze(Ji.codes);jn.names=yk;jn.codes=wk});var Rw=Re((hae,vw)=>{vw.exports=xw;var bw=128,Ek=127,bk=~Ek,xk=Math.pow(2,31);function xw(r,e,t){e=e||[],t=t||0;for(var n=t;r>=xk;)e[t++]=r&255|bw,r/=128;for(;r&bk;)e[t++]=r&255|bw,r>>>=7;return e[t]=r|0,xw.bytes=t-n+1,e}});var Aw=Re((pae,_w)=>{_w.exports=l3;var vk=128,Sw=127;function l3(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw l3.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Sw)<<o:(i&Sw)*Math.pow(2,o),o+=7}while(i>=vk);return l3.bytes=s-n,t}});var Dw=Re((mae,Iw)=>{var Rk=Math.pow(2,7),Sk=Math.pow(2,14),_k=Math.pow(2,21),Ak=Math.pow(2,28),Ik=Math.pow(2,35),Dk=Math.pow(2,42),Tk=Math.pow(2,49),kk=Math.pow(2,56),Ck=Math.pow(2,63);Iw.exports=function(r){return r<Rk?1:r<Sk?2:r<_k?3:r<Ak?4:r<Ik?5:r<Dk?6:r<Tk?7:r<kk?8:r<Ck?9:10}});var kw=Re((gae,Tw)=>{Tw.exports={encode:Rw(),decode:Aw(),encodingLength:Dw()}});var Nw=Re((yae,Cw)=>{"use strict";var Nk=Object.freeze({identity:0,sha1:17,"sha2-256":18,"sha2-512":19,"sha3-512":20,"sha3-384":21,"sha3-256":22,"sha3-224":23,"shake-128":24,"shake-256":25,"keccak-224":26,"keccak-256":27,"keccak-384":28,"keccak-512":29,blake3:30,"murmur3-128":34,"murmur3-32":35,"dbl-sha2-256":86,md4:212,md5:213,bmt:214,"sha2-256-trunc254-padded":4114,"ripemd-128":4178,"ripemd-160":4179,"ripemd-256":4180,"ripemd-320":4181,x11:4352,kangarootwelve:7425,"sm3-256":21325,"blake2b-8":45569,"blake2b-16":45570,"blake2b-24":45571,"blake2b-32":45572,"blake2b-40":45573,"blake2b-48":45574,"blake2b-56":45575,"blake2b-64":45576,"blake2b-72":45577,"blake2b-80":45578,"blake2b-88":45579,"blake2b-96":45580,"blake2b-104":45581,"blake2b-112":45582,"blake2b-120":45583,"blake2b-128":45584,"blake2b-136":45585,"blake2b-144":45586,"blake2b-152":45587,"blake2b-160":45588,"blake2b-168":45589,"blake2b-176":45590,"blake2b-184":45591,"blake2b-192":45592,"blake2b-200":45593,"blake2b-208":45594,"blake2b-216":45595,"blake2b-224":45596,"blake2b-232":45597,"blake2b-240":45598,"blake2b-248":45599,"blake2b-256":45600,"blake2b-264":45601,"blake2b-272":45602,"blake2b-280":45603,"blake2b-288":45604,"blake2b-296":45605,"blake2b-304":45606,"blake2b-312":45607,"blake2b-320":45608,"blake2b-328":45609,"blake2b-336":45610,"blake2b-344":45611,"blake2b-352":45612,"blake2b-360":45613,"blake2b-368":45614,"blake2b-376":45615,"blake2b-384":45616,"blake2b-392":45617,"blake2b-400":45618,"blake2b-408":45619,"blake2b-416":45620,"blake2b-424":45621,"blake2b-432":45622,"blake2b-440":45623,"blake2b-448":45624,"blake2b-456":45625,"blake2b-464":45626,"blake2b-472":45627,"blake2b-480":45628,"blake2b-488":45629,"blake2b-496":45630,"blake2b-504":45631,"blake2b-512":45632,"blake2s-8":45633,"blake2s-16":45634,"blake2s-24":45635,"blake2s-32":45636,"blake2s-40":45637,"blake2s-48":45638,"blake2s-56":45639,"blake2s-64":45640,"blake2s-72":45641,"blake2s-80":45642,"blake2s-88":45643,"blake2s-96":45644,"blake2s-104":45645,"blake2s-112":45646,"blake2s-120":45647,"blake2s-128":45648,"blake2s-136":45649,"blake2s-144":45650,"blake2s-152":45651,"blake2s-160":45652,"blake2s-168":45653,"blake2s-176":45654,"blake2s-184":45655,"blake2s-192":45656,"blake2s-200":45657,"blake2s-208":45658,"blake2s-216":45659,"blake2s-224":45660,"blake2s-232":45661,"blake2s-240":45662,"blake2s-248":45663,"blake2s-256":45664,"skein256-8":45825,"skein256-16":45826,"skein256-24":45827,"skein256-32":45828,"skein256-40":45829,"skein256-48":45830,"skein256-56":45831,"skein256-64":45832,"skein256-72":45833,"skein256-80":45834,"skein256-88":45835,"skein256-96":45836,"skein256-104":45837,"skein256-112":45838,"skein256-120":45839,"skein256-128":45840,"skein256-136":45841,"skein256-144":45842,"skein256-152":45843,"skein256-160":45844,"skein256-168":45845,"skein256-176":45846,"skein256-184":45847,"skein256-192":45848,"skein256-200":45849,"skein256-208":45850,"skein256-216":45851,"skein256-224":45852,"skein256-232":45853,"skein256-240":45854,"skein256-248":45855,"skein256-256":45856,"skein512-8":45857,"skein512-16":45858,"skein512-24":45859,"skein512-32":45860,"skein512-40":45861,"skein512-48":45862,"skein512-56":45863,"skein512-64":45864,"skein512-72":45865,"skein512-80":45866,"skein512-88":45867,"skein512-96":45868,"skein512-104":45869,"skein512-112":45870,"skein512-120":45871,"skein512-128":45872,"skein512-136":45873,"skein512-144":45874,"skein512-152":45875,"skein512-160":45876,"skein512-168":45877,"skein512-176":45878,"skein512-184":45879,"skein512-192":45880,"skein512-200":45881,"skein512-208":45882,"skein512-216":45883,"skein512-224":45884,"skein512-232":45885,"skein512-240":45886,"skein512-248":45887,"skein512-256":45888,"skein512-264":45889,"skein512-272":45890,"skein512-280":45891,"skein512-288":45892,"skein512-296":45893,"skein512-304":45894,"skein512-312":45895,"skein512-320":45896,"skein512-328":45897,"skein512-336":45898,"skein512-344":45899,"skein512-352":45900,"skein512-360":45901,"skein512-368":45902,"skein512-376":45903,"skein512-384":45904,"skein512-392":45905,"skein512-400":45906,"skein512-408":45907,"skein512-416":45908,"skein512-424":45909,"skein512-432":45910,"skein512-440":45911,"skein512-448":45912,"skein512-456":45913,"skein512-464":45914,"skein512-472":45915,"skein512-480":45916,"skein512-488":45917,"skein512-496":45918,"skein512-504":45919,"skein512-512":45920,"skein1024-8":45921,"skein1024-16":45922,"skein1024-24":45923,"skein1024-32":45924,"skein1024-40":45925,"skein1024-48":45926,"skein1024-56":45927,"skein1024-64":45928,"skein1024-72":45929,"skein1024-80":45930,"skein1024-88":45931,"skein1024-96":45932,"skein1024-104":45933,"skein1024-112":45934,"skein1024-120":45935,"skein1024-128":45936,"skein1024-136":45937,"skein1024-144":45938,"skein1024-152":45939,"skein1024-160":45940,"skein1024-168":45941,"skein1024-176":45942,"skein1024-184":45943,"skein1024-192":45944,"skein1024-200":45945,"skein1024-208":45946,"skein1024-216":45947,"skein1024-224":45948,"skein1024-232":45949,"skein1024-240":45950,"skein1024-248":45951,"skein1024-256":45952,"skein1024-264":45953,"skein1024-272":45954,"skein1024-280":45955,"skein1024-288":45956,"skein1024-296":45957,"skein1024-304":45958,"skein1024-312":45959,"skein1024-320":45960,"skein1024-328":45961,"skein1024-336":45962,"skein1024-344":45963,"skein1024-352":45964,"skein1024-360":45965,"skein1024-368":45966,"skein1024-376":45967,"skein1024-384":45968,"skein1024-392":45969,"skein1024-400":45970,"skein1024-408":45971,"skein1024-416":45972,"skein1024-424":45973,"skein1024-432":45974,"skein1024-440":45975,"skein1024-448":45976,"skein1024-456":45977,"skein1024-464":45978,"skein1024-472":45979,"skein1024-480":45980,"skein1024-488":45981,"skein1024-496":45982,"skein1024-504":45983,"skein1024-512":45984,"skein1024-520":45985,"skein1024-528":45986,"skein1024-536":45987,"skein1024-544":45988,"skein1024-552":45989,"skein1024-560":45990,"skein1024-568":45991,"skein1024-576":45992,"skein1024-584":45993,"skein1024-592":45994,"skein1024-600":45995,"skein1024-608":45996,"skein1024-616":45997,"skein1024-624":45998,"skein1024-632":45999,"skein1024-640":46e3,"skein1024-648":46001,"skein1024-656":46002,"skein1024-664":46003,"skein1024-672":46004,"skein1024-680":46005,"skein1024-688":46006,"skein1024-696":46007,"skein1024-704":46008,"skein1024-712":46009,"skein1024-720":46010,"skein1024-728":46011,"skein1024-736":46012,"skein1024-744":46013,"skein1024-752":46014,"skein1024-760":46015,"skein1024-768":46016,"skein1024-776":46017,"skein1024-784":46018,"skein1024-792":46019,"skein1024-800":46020,"skein1024-808":46021,"skein1024-816":46022,"skein1024-824":46023,"skein1024-832":46024,"skein1024-840":46025,"skein1024-848":46026,"skein1024-856":46027,"skein1024-864":46028,"skein1024-872":46029,"skein1024-880":46030,"skein1024-888":46031,"skein1024-896":46032,"skein1024-904":46033,"skein1024-912":46034,"skein1024-920":46035,"skein1024-928":46036,"skein1024-936":46037,"skein1024-944":46038,"skein1024-952":46039,"skein1024-960":46040,"skein1024-968":46041,"skein1024-976":46042,"skein1024-984":46043,"skein1024-992":46044,"skein1024-1000":46045,"skein1024-1008":46046,"skein1024-1016":46047,"skein1024-1024":46048,"poseidon-bls12_381-a2-fc1":46081,"poseidon-bls12_381-a2-fc1-sc":46082});Cw.exports={names:Nk}});function Lk(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,y=0,w=0,b=p.length;w!==b&&p[w]===0;)w++,m++;for(var E=(b-w)*d+1>>>0,x=new Uint8Array(E);w!==b;){for(var v=p[w],I=0,S=E-1;(v!==0||I<y)&&S!==-1;S--,I++)v+=256*x[S]>>>0,x[S]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");y=I,w++}for(var R=E-y;R!==E&&x[R]===0;)R++;for(var T=c.repeat(m);R<E;++R)T+=r.charAt(x[R]);return T}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var y=0,w=0;p[m]===c;)y++,m++;for(var b=(p.length-m)*l+1>>>0,E=new Uint8Array(b);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var v=0,I=b-1;(x!==0||v<w)&&I!==-1;I--,v++)x+=a*E[I]>>>0,E[I]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");w=v,m++}if(p[m]!==" "){for(var S=b-w;S!==b&&E[S]===0;)S++;for(var R=new Uint8Array(y+(b-S)),T=y;S!==b;)R[T++]=E[S++];return R}}}function f(p){var m=h(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:h,decode:f}}var Pk,Ok,Lw,Pw=ke(()=>{Pk=Lk,Ok=Pk,Lw=Ok});var Eae,Ow,Zn,Bw,Mw,$o=ke(()=>{Eae=new Uint8Array(0),Ow=(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},Zn=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")},Bw=r=>new TextEncoder().encode(r),Mw=r=>new TextDecoder().decode(r)});var u3,d3,f3,Fw,h3,ea,Ho,Bk,Mk,tt,nn=ke(()=>{Pw();$o();u3=class{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")}},d3=class{constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),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 Fw(this,e)}},f3=class{constructor(e){this.decoders=e}or(e){return Fw(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Fw=(r,e)=>new f3({...r.decoders||{[r.prefix]:r},...e.decoders||{[e.prefix]:e}}),h3=class{constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new u3(e,t,n),this.decoder=new d3(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},ea=({name:r,prefix:e,encode:t,decode:n})=>new h3(r,e,t,n),Ho=({prefix:r,name:e,alphabet:t})=>{let{encode:n,decode:o}=Lw(t,e);return ea({prefix:r,name:e,encode:n,decode:s=>Zn(o(s))})},Bk=(r,e,t,n)=>{let o={};for(let d=0;d<e.length;++d)o[e[d]]=d;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,l=0;for(let d=0;d<s;++d){let u=o[r[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,a+=t,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i},Mk=(r,e,t)=>{let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i&&(s+=e[o&a<<t-i]),n)for(;s.length*t&7;)s+="=";return s},tt=({name:r,prefix:e,bitsPerChar:t,alphabet:n})=>ea({prefix:e,name:r,encode(o){return Mk(o,n,t)},decode(o){return Bk(o,n,t,r)}})});var p3={};pe(p3,{identity:()=>Uk});var Uk,Vw=ke(()=>{nn();$o();Uk=ea({prefix:"\0",name:"identity",encode:r=>Mw(r),decode:r=>Bw(r)})});var m3={};pe(m3,{base2:()=>Fk});var Fk,Kw=ke(()=>{nn();Fk=tt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var g3={};pe(g3,{base8:()=>Vk});var Vk,$w=ke(()=>{nn();Vk=tt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var y3={};pe(y3,{base10:()=>Kk});var Kk,Hw=ke(()=>{nn();Kk=Ho({prefix:"9",name:"base10",alphabet:"0123456789"})});var w3={};pe(w3,{base16:()=>$k,base16upper:()=>Hk});var $k,Hk,qw=ke(()=>{nn();$k=tt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Hk=tt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var E3={};pe(E3,{base32:()=>ta,base32hex:()=>zk,base32hexpad:()=>Xk,base32hexpadupper:()=>Qk,base32hexupper:()=>Yk,base32pad:()=>Gk,base32padupper:()=>Wk,base32upper:()=>qk,base32z:()=>jk});var ta,qk,Gk,Wk,zk,Yk,Xk,Qk,jk,b3=ke(()=>{nn();ta=tt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),qk=tt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Gk=tt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Wk=tt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),zk=tt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Yk=tt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Xk=tt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Qk=tt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),jk=tt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var x3={};pe(x3,{base36:()=>Zk,base36upper:()=>Jk});var Zk,Jk,Gw=ke(()=>{nn();Zk=Ho({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Jk=Ho({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var v3={};pe(v3,{base58btc:()=>bn,base58flickr:()=>eC});var bn,eC,R3=ke(()=>{nn();bn=Ho({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),eC=Ho({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var S3={};pe(S3,{base64:()=>tC,base64pad:()=>rC,base64url:()=>nC,base64urlpad:()=>oC});var tC,rC,nC,oC,Ww=ke(()=>{nn();tC=tt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rC=tt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),nC=tt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),oC=tt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var _3={};pe(_3,{base256emoji:()=>lC});function aC(r){return r.reduce((e,t)=>(e+=sC[t],e),"")}function cC(r){let e=[];for(let t of r){let n=iC[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var zw,sC,iC,lC,Yw=ke(()=>{nn();zw=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}"),sC=zw.reduce((r,e,t)=>(r[t]=e,r),[]),iC=zw.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);lC=ea({prefix:"\u{1F680}",name:"base256emoji",encode:aC,decode:cC})});function jw(r,e,t){e=e||[],t=t||0;for(var n=t;r>=hC;)e[t++]=r&255|Xw,r/=128;for(;r&fC;)e[t++]=r&255|Xw,r>>>=7;return e[t]=r|0,jw.bytes=t-n+1,e}function A3(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw A3.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Qw)<<o:(i&Qw)*Math.pow(2,o),o+=7}while(i>=mC);return A3.bytes=s-n,t}var uC,Xw,dC,fC,hC,pC,mC,Qw,gC,yC,wC,EC,bC,xC,vC,RC,SC,_C,AC,IC,Ac,Zw=ke(()=>{uC=jw,Xw=128,dC=127,fC=~dC,hC=Math.pow(2,31);pC=A3,mC=128,Qw=127;gC=Math.pow(2,7),yC=Math.pow(2,14),wC=Math.pow(2,21),EC=Math.pow(2,28),bC=Math.pow(2,35),xC=Math.pow(2,42),vC=Math.pow(2,49),RC=Math.pow(2,56),SC=Math.pow(2,63),_C=function(r){return r<gC?1:r<yC?2:r<wC?3:r<EC?4:r<bC?5:r<xC?6:r<vC?7:r<RC?8:r<SC?9:10},AC={encode:uC,decode:pC,encodingLength:_C},IC=AC,Ac=IC});var Ic,ra,na,zd=ke(()=>{Zw();Ic=(r,e=0)=>[Ac.decode(r,e),Ac.decode.bytes],ra=(r,e,t=0)=>(Ac.encode(r,e,t),e),na=r=>Ac.encodingLength(r)});var Ls,Jw,eE,oa,Tc=ke(()=>{$o();zd();Ls=(r,e)=>{let t=e.byteLength,n=na(r),o=n+na(t),s=new Uint8Array(o+t);return ra(r,s,0),ra(t,s,n),s.set(e,o),new oa(r,t,e,s)},Jw=r=>{let e=Zn(r),[t,n]=Ic(e),[o,s]=Ic(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new oa(t,o,i,e)},eE=(r,e)=>r===e?!0:r.code===e.code&&r.size===e.size&&Ow(r.bytes,e.bytes),oa=class{constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}}});var D3,I3,T3=ke(()=>{Tc();D3=({name:r,code:e,encode:t})=>new I3(r,e,t),I3=class{constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Ls(this.code,t):t.then(n=>Ls(this.code,n))}else throw Error("Unknown type, must be binary type")}}});var k3={};pe(k3,{sha256:()=>DC,sha512:()=>TC});var rE,DC,TC,nE=ke(()=>{T3();rE=r=>async e=>new Uint8Array(await crypto.subtle.digest(r,e)),DC=D3({name:"sha2-256",code:18,encode:rE("SHA-256")}),TC=D3({name:"sha2-512",code:19,encode:rE("SHA-512")})});var C3={};pe(C3,{identity:()=>NC});var oE,kC,sE,CC,NC,iE=ke(()=>{$o();Tc();oE=0,kC="identity",sE=Zn,CC=r=>Ls(oE,sE(r)),NC={code:oE,name:kC,encode:sE,digest:CC}});var aE=ke(()=>{$o()});var Vae,Kae,cE=ke(()=>{Vae=new TextEncoder,Kae=new TextDecoder});var Qd,OC,BC,MC,kc,UC,lE,uE,Yd,Xd,FC,VC,KC,dE=ke(()=>{zd();Tc();R3();b3();$o();Qd=class r{constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this.byteOffset=o.byteOffset,this.byteLength=o.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:Xd,byteLength:Xd,code:Yd,version:Yd,multihash:Yd,bytes:Yd,_baseCache:Xd,asCID:Xd})}toV0(){switch(this.version){case 0:return this;default:{let{code:e,multihash:t}=this;if(e!==kc)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==UC)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Ls(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&eE(this.multihash,e.multihash)}toString(e){let{bytes:t,version:n,_baseCache:o}=this;switch(n){case 0:return BC(t,o,e||bn.encoder);default:return MC(t,o,e||ta.encoder)}}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return VC(/^0\.0/,KC),!!(e&&(e[uE]||e.asCID===e))}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof r)return e;if(e!=null&&e.asCID===e){let{version:t,code:n,multihash:o,bytes:s}=e;return new r(t,n,o,s||lE(t,n,o.bytes))}else if(e!=null&&e[uE]===!0){let{version:t,multihash:n,code:o}=e,s=Jw(n);return r.create(t,o,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");switch(e){case 0:{if(t!==kc)throw new Error(`Version 0 CID must use dag-pb (code: ${kc}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=lE(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,kc,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=Zn(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new oa(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,h]=Ic(e.subarray(t));return t+=h,u},o=n(),s=kc;if(o===18?(o=0,t=0):o===1&&(s=n()),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,d=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(e,t){let[n,o]=OC(e,t),s=r.decode(o);return s._baseCache.set(n,e),s}},OC=(r,e)=>{switch(r[0]){case"Q":{let t=e||bn;return[bn.prefix,t.decode(`${bn.prefix}${r}`)]}case bn.prefix:{let t=e||bn;return[bn.prefix,t.decode(r)]}case ta.prefix:{let t=e||ta;return[ta.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}},BC=(r,e,t)=>{let{prefix:n}=t;if(n!==bn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o},MC=(r,e,t)=>{let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o},kc=112,UC=18,lE=(r,e,t)=>{let n=na(r),o=n+na(e),s=new Uint8Array(o+t.byteLength);return ra(r,s,0),ra(e,s,n),s.set(t,o),s},uE=Symbol.for("@ipld/js-cid/CID"),Yd={writable:!1,configurable:!1,enumerable:!0},Xd={writable:!1,enumerable:!1,configurable:!1},FC="0.0.0-dev",VC=(r,e)=>{if(r.test(FC))console.warn(e);else throw new Error(e)},KC=`CID.isCID(v) is deprecated and will be removed in the next major release.
|
|
4
4
|
Following code pattern:
|
|
5
5
|
|
|
@@ -14,12 +14,12 @@ if (cid) {
|
|
|
14
14
|
// Make sure to use cid instead of value
|
|
15
15
|
doSomethingWithCID(cid)
|
|
16
16
|
}
|
|
17
|
-
`});var fE=ke(()=>{dE();zd();$o();T3();Tc()});var N3,Xae,hE=ke(()=>{Vw();Kw();$w();Hw();qw();b3();Gw();R3();Ww();Yw();nE();iE();aE();cE();fE();N3={...p3,...m3,...g3,...y3,...w3,...E3,...x3,...v3,...S3,..._3},Xae={...k3,...C3}});function sa(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}var jd=ke(()=>{});function Zd(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?sa(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}var L3=ke(()=>{jd()});function mE(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var pE,P3,$C,Jd,O3=ke(()=>{hE();L3();pE=mE("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),P3=mE("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=Zd(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),$C={utf8:pE,"utf-8":pE,hex:N3.base16,latin1:P3,ascii:P3,binary:P3,...N3},Jd=$C});var gE={};pe(gE,{toString:()=>HC});function HC(r,e="utf8"){let t=Jd[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var yE=ke(()=>{O3()});var wE={};pe(wE,{fromString:()=>qC});function qC(r,e="utf8"){let t=Jd[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?sa(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var EE=ke(()=>{O3();jd()});var bE={};pe(bE,{concat:()=>GC});function GC(r,e){e||(e=r.reduce((o,s)=>o+s.length,0));let t=Zd(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return sa(t)}var xE=ke(()=>{L3();jd()});var M3=Re((cce,IE)=>{"use strict";var vE=Ew(),ia=kw(),{names:Cc}=Nw(),{toString:ef}=(yE(),Mc(gE)),{fromString:WC}=(EE(),Mc(wE)),{concat:zC}=(xE(),Mc(bE)),aa={};for(let r in Cc){let e=r;aa[Cc[e]]=e}Object.freeze(aa);function YC(r){if(!(r instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return ef(r,"base16")}function XC(r){return WC(r,"base16")}function QC(r){if(!(r instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return ef(vE.encode("base58btc",r)).slice(1)}function jC(r){let e=r instanceof Uint8Array?ef(r):r;return vE.decode("z"+e)}function RE(r){if(!(r instanceof Uint8Array))throw new Error("multihash must be a Uint8Array");if(r.length<2)throw new Error("multihash too short. must be > 2 bytes.");let e=ia.decode(r);if(!_E(e))throw new Error(`multihash unknown function code: 0x${e.toString(16)}`);r=r.slice(ia.decode.bytes);let t=ia.decode(r);if(t<0)throw new Error(`multihash invalid length: ${t}`);if(r=r.slice(ia.decode.bytes),r.length!==t)throw new Error(`multihash length inconsistent: 0x${ef(r,"base16")}`);return{code:e,name:aa[e],length:t,digest:r}}function ZC(r,e,t){if(!r||e===void 0)throw new Error("multihash encode requires at least two args: digest, code");let n=SE(e);if(!(r instanceof Uint8Array))throw new Error("digest should be a Uint8Array");if(t==null&&(t=r.length),t&&r.length!==t)throw new Error("digest length should be equal to specified length.");let o=ia.encode(n),s=ia.encode(t);return zC([o,s,r],o.length+s.length+r.length)}function SE(r){let e=r;if(typeof r=="string"){if(Cc[r]===void 0)throw new Error(`Unrecognized hash function named: ${r}`);e=Cc[r]}if(typeof e!="number")throw new Error(`Hash function code should be a number. Got: ${e}`);if(aa[e]===void 0&&!B3(e))throw new Error(`Unrecognized function code: ${e}`);return e}function B3(r){return r>0&&r<16}function _E(r){return!!(B3(r)||aa[r])}function AE(r){RE(r)}function JC(r){return AE(r),r.subarray(0,2)}IE.exports={names:Cc,codes:aa,toHexString:YC,fromHexString:XC,toB58String:QC,fromB58String:jC,decode:RE,encode:ZC,coerceCode:SE,isAppCode:B3,validate:AE,prefix:JC,isValidCode:_E}});var VE=Re(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var K3=class{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;let t={value:e,done:!1};if(this.pullQueue.length){let n=this.pullQueue.shift();n&&n.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),this.highWaterMark!==void 0&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(let e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(let t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{let t=Promise.reject(e);t.catch(()=>{}),this.pushQueue.push(t)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{let t=this.pushQueue.shift();return t?(this.lowWaterMark!==void 0&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((n,o)=>{this.pullQueue.push({resolve:n,reject:o})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}},nf=class{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){let o=new K3;o.highWaterMark=t,o.lowWaterMark=n,o.removeCallback=e({push:s=>o.push(s),stop:()=>o.stop(),fail:s=>o.fail(s),on:(s,i)=>{o.eventHandlers[s]=i}})||(()=>{}),this[Symbol.asyncIterator]=()=>o[Symbol.asyncIterator](),Object.freeze(this)}};of.EventIterator=nf;of.default=nf});var KE=Re(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var $3=VE();Nc.EventIterator=$3.EventIterator;function aN(r,e,t){return new $3.EventIterator(({push:n})=>(this.addEventListener(r,n,e),()=>this.removeEventListener(r,n,e)),t)}Nc.subscribe=aN;Nc.default=$3.EventIterator});var UN={};pe(UN,{DEFAULT_SESSION_MAX_PROVIDERS:()=>tg,DEFAULT_SESSION_MIN_PROVIDERS:()=>eg,createHelia:()=>BN,libp2pDefaults:()=>lf});var v4=Symbol.for("@libp2p/connection");var on=Symbol.for("@libp2p/content-routing");var Wo=Symbol.for("@libp2p/peer-discovery");var ha=Symbol.for("@libp2p/peer-id");function Ms(r){return r!=null&&!!r[ha]}var sn=Symbol.for("@libp2p/peer-routing");var R4="keep-alive";var an=Symbol.for("@libp2p/transport");var to;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(to||(to={}));var Kt=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},g=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}},Uc=class extends AggregateError{code;props;constructor(e,t,n,o){super(e,t),this.code=n,this.name=o?.name??"AggregateCodeError",this.props=o??{}}};var vn="ERR_TIMEOUT";var zo="ERR_INVALID_MESSAGE";var H=(r,...e)=>{try{[...e]}catch{}};var ye=class extends EventTarget{#e=new Map;constructor(){super(),H(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new Ot(e,t))}},Bf=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Ot=globalThis.CustomEvent??Bf;function Fc(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function cn(...r){let e=[];for(let t of r)Fc(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 ln(...r){let e=[];for(let t of r)Fc(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()}))}function Ae(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}function J(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Vc=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)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}},Us=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Vc(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Vc(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Mf=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function kt(r={}){return Kb(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 Kb(r,e){e=e??{};let t=e.onEnd,n=new Us,o,s,i,a=J(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,w)=>{s=b=>{s=null,n.push(b);try{y(r(n))}catch(E){w(E)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=J()})}},l=y=>s!=null?s(y):(n.push(y),o),d=y=>(n=new Us,s!=null?s({error:y}):(n.push({error:y}),o)),u=y=>{if(i)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},h=y=>i?o:(i=!0,y!=null?d(y):l({done:!0})),f=()=>(n=new Us,h(),{done:!0}),p=y=>(h(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:f,throw:p,push:u,end:h,get readableLength(){return n.size},onEmpty:async y=>{let w=y?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let b,E;w!=null&&(b=new Promise((x,v)=>{E=()=>{v(new Mf)},w.addEventListener("abort",E)}));try{await Promise.race([a.promise,b])}finally{E!=null&&w!=null&&w?.removeEventListener("abort",E)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(y){return m.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},o}var Uf=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function er(r,e,t,n){let o=new Uf(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",d),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=u=>{try{if(n?.filter?.(u)===!1)return}catch(h){a(),i(h);return}a(),s(u)},l=u=>{a(),i(u.detail)},d=()=>{a(),i(o)};t?.addEventListener("abort",d),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var Kc=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Ue(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Kc(t?.errorMessage,t?.errorCode));let n,o=new Kc(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var $c=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=J(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Kt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function $b(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Hc=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=$b(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,H(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Kt),this.cleanup())}async join(e={}){let t=new $c(new Error("where").stack,e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ue(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var tr=class extends ye{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!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){t?.signal?.throwIfAborted();let n=new Hc(e,t),o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Kt)}),this.clear()}async onEmpty(e){this.size!==0&&await er(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await er(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await er(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=kt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new g("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var wr=class extends tr{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function Hb(r){return r[Symbol.asyncIterator]!=null}function qb(r){if(Hb(r))return(async()=>{for await(let e of r);})();for(let e of r);}var $t=qb;function Ie(r=0){return new Uint8Array(r)}function ze(r=0){return new Uint8Array(r)}var Gb=Math.pow(2,7),Wb=Math.pow(2,14),zb=Math.pow(2,21),Ff=Math.pow(2,28),Vf=Math.pow(2,35),Kf=Math.pow(2,42),$f=Math.pow(2,49),Ce=128,Ct=127;function Se(r){if(r<Gb)return 1;if(r<Wb)return 2;if(r<zb)return 3;if(r<Ff)return 4;if(r<Vf)return 5;if(r<Kf)return 6;if(r<$f)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Hf(r,e,t=0){switch(Se(r)){case 8:e[t++]=r&255|Ce,r/=128;case 7:e[t++]=r&255|Ce,r/=128;case 6:e[t++]=r&255|Ce,r/=128;case 5:e[t++]=r&255|Ce,r/=128;case 4:e[t++]=r&255|Ce,r>>>=7;case 3:e[t++]=r&255|Ce,r>>>=7;case 2:e[t++]=r&255|Ce,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Yb(r,e,t=0){switch(Se(r)){case 8:e.set(t++,r&255|Ce),r/=128;case 7:e.set(t++,r&255|Ce),r/=128;case 6:e.set(t++,r&255|Ce),r/=128;case 5:e.set(t++,r&255|Ce),r/=128;case 4:e.set(t++,r&255|Ce),r>>>=7;case 3:e.set(t++,r&255|Ce),r>>>=7;case 2:e.set(t++,r&255|Ce),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function qf(r,e){let t=r[e],n=0;if(n+=t&Ct,t<Ce||(t=r[e+1],n+=(t&Ct)<<7,t<Ce)||(t=r[e+2],n+=(t&Ct)<<14,t<Ce)||(t=r[e+3],n+=(t&Ct)<<21,t<Ce)||(t=r[e+4],n+=(t&Ct)*Ff,t<Ce)||(t=r[e+5],n+=(t&Ct)*Vf,t<Ce)||(t=r[e+6],n+=(t&Ct)*Kf,t<Ce)||(t=r[e+7],n+=(t&Ct)*$f,t<Ce))return n;throw new RangeError("Could not decode varint")}function Xb(r,e){let t=r.get(e),n=0;if(n+=t&Ct,t<Ce||(t=r.get(e+1),n+=(t&Ct)<<7,t<Ce)||(t=r.get(e+2),n+=(t&Ct)<<14,t<Ce)||(t=r.get(e+3),n+=(t&Ct)<<21,t<Ce)||(t=r.get(e+4),n+=(t&Ct)*Ff,t<Ce)||(t=r.get(e+5),n+=(t&Ct)*Vf,t<Ce)||(t=r.get(e+6),n+=(t&Ct)*Kf,t<Ce)||(t=r.get(e+7),n+=(t&Ct)*$f,t<Ce))return n;throw new RangeError("Could not decode varint")}function $e(r,e,t=0){return e==null&&(e=ze(Se(r))),e instanceof Uint8Array?Hf(r,e,t):Yb(r,e,t)}function Bt(r,e=0){return r instanceof Uint8Array?qf(r,e):Xb(r,e)}function ve(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=ze(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function Z(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var _4=Symbol.for("@achingbrain/uint8arraylist");function S4(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 qc(r){return!!r?.[_4]}var ce=class r{bufs;length;[_4]=!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(qc(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(qc(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=S4(this.bufs,e);return t.buf[t.index]}set(e,t){let n=S4(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(qc(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 ve(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:ve(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,d=t>a&&t<=c;if(l&&d){if(e===a&&t===c){n.push(i);break}let u=e-a;n.push(i.subarray(u,u+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(d){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!qc(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,d;for(let u=t;u<=c;u+=d){d=0;for(let h=l;h>=0;h--){let f=this.get(u+h);if(n[h]!==f){d=Math.max(1,h-a[f]);break}}if(d===0)return u}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ze(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=Ie(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=Ie(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=Ie(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=ze(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=Ie(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=Ie(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=Ie(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=Ie(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=Ie(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Z(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function Gc(r){return r[Symbol.asyncIterator]!=null}var Wc=r=>{let e=Se(r),t=ze(e);return $e(r,t),Wc.bytes=e,t};Wc.bytes=0;function Ht(r,e){e=e??{};let t=e.lengthEncoder??Wc;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Gc(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Ht.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Wc;return new ce(t(r.byteLength),r)};var Fs=Qe(Yo(),1);var Zb=8,Jb=1024*1024*4,Xo;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Xo||(Xo={}));var Gf=r=>{let e=Bt(r);return Gf.bytes=Se(e),e};Gf.bytes=0;function qt(r,e){let t=new ce,n=Xo.LENGTH,o=-1,s=e?.lengthDecoder??Gf,i=e?.maxLengthLength??Zb,a=e?.maxDataLength??Jb;function*c(){for(;t.byteLength>0;){if(n===Xo.LENGTH)try{if(o=s(t),o<0)throw(0,Fs.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>a)throw(0,Fs.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=Xo.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw(0,Fs.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(n===Xo.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=Xo.LENGTH}}}return Gc(r)?async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw(0,Fs.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw(0,Fs.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}qt.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return qt(n,{...e??{},onLength:s=>{t=s}})};function ex(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Vs=ex;function tx(r){return r[Symbol.asyncIterator]!=null}function rx(r,e){let t=0;if(tx(r))return async function*(){for await(let c of r)yield e(c,t++)}();let n=Vs(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){yield await i;for await(let c of n)yield e(c,t++)}();let a=e;return function*(){yield i;for(let c of n)yield a(c,t++)}()}var Gt=rx;function nx(r){return r[Symbol.asyncIterator]!=null}function ox(...r){let e=[];for(let t of r)nx(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=kt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Mt=ox;function je(r,...e){if(r==null)throw new Error("Empty pipeline");if(Wf(r)){let n=r;r=()=>n.source}else if(T4(r)||D4(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Wf(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++)Wf(t[n])&&(t[n]=ix(t[n]));return sx(...t)}var sx=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},D4=r=>r?.[Symbol.asyncIterator]!=null,T4=r=>r?.[Symbol.iterator]!=null,Wf=r=>r==null?!1:r.sink!=null&&r.source!=null,ix=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=kt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(D4(s))o=async function*(){yield*s,n.end()};else if(T4(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Mt(n,o())}return r.source};function ax(r){return r[Symbol.asyncIterator]!=null}function cx(r,e){return ax(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var ro=cx;var me=class extends Event{constructor(e,t){super(e),this.detail=t}};var pa="/ipfs/bitswap/1.2.0";var zf=new Float32Array([-0]),no=new Uint8Array(zf.buffer);function k4(r,e,t){zf[0]=r,e[t]=no[0],e[t+1]=no[1],e[t+2]=no[2],e[t+3]=no[3]}function C4(r,e){return no[0]=r[e],no[1]=r[e+1],no[2]=r[e+2],no[3]=r[e+3],zf[0]}var Yf=new Float64Array([-0]),Nt=new Uint8Array(Yf.buffer);function N4(r,e,t){Yf[0]=r,e[t]=Nt[0],e[t+1]=Nt[1],e[t+2]=Nt[2],e[t+3]=Nt[3],e[t+4]=Nt[4],e[t+5]=Nt[5],e[t+6]=Nt[6],e[t+7]=Nt[7]}function L4(r,e){return Nt[0]=r[e],Nt[1]=r[e+1],Nt[2]=r[e+2],Nt[3]=r[e+3],Nt[4]=r[e+4],Nt[5]=r[e+5],Nt[6]=r[e+6],Nt[7]=r[e+7],Yf[0]}var lx=BigInt(Number.MAX_SAFE_INTEGER),ux=BigInt(Number.MIN_SAFE_INTEGER),rr=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 Qo;if(e<lx&&e>ux)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>P4&&(o=0n,++n>P4&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Qo;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):Qo}},Qo=new rr(0,0);Qo.toBigInt=function(){return 0n};Qo.zzEncode=Qo.zzDecode=function(){return this};Qo.length=function(){return 1};var P4=4294967296n;function O4(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 B4(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Xf(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Or(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Yc(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Qf=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,Or(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 Or(this,4);return Yc(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Or(this,4);return Yc(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Or(this,4);let e=C4(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Or(this,4);let e=L4(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 Or(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return B4(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Or(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Or(this);while(this.buf[this.pos++]&128);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 rr(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 Or(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 Or(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 Or(this,8);let e=Yc(this.buf,this.pos+=4),t=Yc(this.buf,this.pos+=4);return new rr(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=qf(this.buf,this.pos);return this.pos+=Se(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 jf(r){return new Qf(r instanceof Uint8Array?r:r.subarray())}function te(r,e,t){let n=jf(r);return e.decode(n,void 0,t)}var rh={};pe(rh,{base10:()=>gx});var cP=new Uint8Array(0);function U4(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 Sn(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 F4(r){return new TextEncoder().encode(r)}function V4(r){return new TextDecoder().decode(r)}function dx(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,y=0,w=0,b=p.length;w!==b&&p[w]===0;)w++,m++;for(var E=(b-w)*d+1>>>0,x=new Uint8Array(E);w!==b;){for(var v=p[w],I=0,S=E-1;(v!==0||I<y)&&S!==-1;S--,I++)v+=256*x[S]>>>0,x[S]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");y=I,w++}for(var R=E-y;R!==E&&x[R]===0;)R++;for(var T=c.repeat(m);R<E;++R)T+=r.charAt(x[R]);return T}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var y=0,w=0;p[m]===c;)y++,m++;for(var b=(p.length-m)*l+1>>>0,E=new Uint8Array(b);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var v=0,I=b-1;(x!==0||v<w)&&I!==-1;I--,v++)x+=a*E[I]>>>0,E[I]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");w=v,m++}if(p[m]!==" "){for(var S=b-w;S!==b&&E[S]===0;)S++;for(var R=new Uint8Array(y+(b-S)),T=y;S!==b;)R[T++]=E[S++];return R}}}function f(p){var m=h(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:h,decode:f}}var fx=dx,hx=fx,$4=hx;var Zf=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")}},Jf=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),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 H4(this,e)}},eh=class{decoders;constructor(e){this.decoders=e}or(e){return H4(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 H4(r,e){return new eh({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var th=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 Zf(e,t,n),this.decoder=new Jf(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ks({name:r,prefix:e,encode:t,decode:n}){return new th(r,e,t,n)}function oo({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=$4(t,r);return Ks({prefix:e,name:r,encode:n,decode:s=>Sn(o(s))})}function px(r,e,t,n){let o={};for(let d=0;d<e.length;++d)o[e[d]]=d;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,l=0;for(let d=0;d<s;++d){let u=o[r[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,a+=t,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function mx(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;s.length*t&7;)s+="=";return s}function Ze({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Ks({prefix:e,name:r,encode(o){return mx(o,n,t)},decode(o){return px(o,n,t,r)}})}var gx=oo({prefix:"9",name:"base10",alphabet:"0123456789"});var nh={};pe(nh,{base16:()=>yx,base16upper:()=>wx});var yx=Ze({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),wx=Ze({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var oh={};pe(oh,{base2:()=>Ex});var Ex=Ze({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var sh={};pe(sh,{base256emoji:()=>Sx});var q4=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}"),bx=q4.reduce((r,e,t)=>(r[t]=e,r),[]),xx=q4.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function vx(r){return r.reduce((e,t)=>(e+=bx[t],e),"")}function Rx(r){let e=[];for(let t of r){let n=xx[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Sx=Ks({prefix:"\u{1F680}",name:"base256emoji",encode:vx,decode:Rx});var ih={};pe(ih,{base32:()=>ut,base32hex:()=>Ix,base32hexpad:()=>Tx,base32hexpadupper:()=>kx,base32hexupper:()=>Dx,base32pad:()=>_x,base32padupper:()=>Ax,base32upper:()=>G4,base32z:()=>Cx});var ut=Ze({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),G4=Ze({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_x=Ze({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ax=Ze({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ix=Ze({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Dx=Ze({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Tx=Ze({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),kx=Ze({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Cx=Ze({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ah={};pe(ah,{base36:()=>so,base36upper:()=>Nx});var so=oo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Nx=oo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ch={};pe(ch,{base58btc:()=>Ye,base58flickr:()=>Lx});var Ye=oo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Lx=oo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var uh={};pe(uh,{base64:()=>st,base64pad:()=>Px,base64url:()=>lh,base64urlpad:()=>Ox});var st=Ze({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Px=Ze({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),lh=Ze({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ox=Ze({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var dh={};pe(dh,{base8:()=>Bx});var Bx=Ze({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var fh={};pe(fh,{identity:()=>Mx});var Mx=Ks({prefix:"\0",name:"identity",encode:r=>V4(r),decode:r=>F4(r)});var SP=new TextEncoder,_P=new TextDecoder;var W4=512;var Xc=85;var gh={};pe(gh,{identity:()=>Wt});var Er={};pe(Er,{Digest:()=>jo,create:()=>Br,decode:()=>Mr,equals:()=>mh});var Ux=Q4,Y4=128,Fx=127,Vx=~Fx,Kx=Math.pow(2,31);function Q4(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Kx;)e[t++]=r&255|Y4,r/=128;for(;r&Vx;)e[t++]=r&255|Y4,r>>>=7;return e[t]=r|0,Q4.bytes=t-n+1,e}var $x=ph,Hx=128,X4=127;function ph(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ph.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&X4)<<o:(i&X4)*Math.pow(2,o),o+=7}while(i>=Hx);return ph.bytes=s-n,t}var qx=Math.pow(2,7),Gx=Math.pow(2,14),Wx=Math.pow(2,21),zx=Math.pow(2,28),Yx=Math.pow(2,35),Xx=Math.pow(2,42),Qx=Math.pow(2,49),jx=Math.pow(2,56),Zx=Math.pow(2,63),Jx=function(r){return r<qx?1:r<Gx?2:r<Wx?3:r<zx?4:r<Yx?5:r<Xx?6:r<Qx?7:r<jx?8:r<Zx?9:10},ev={encode:Ux,decode:$x,encodingLength:Jx},tv=ev,ma=tv;function ga(r,e=0){return[ma.decode(r,e),ma.decode.bytes]}function $s(r,e,t=0){return ma.encode(r,e,t),e}function Hs(r){return ma.encodingLength(r)}function Br(r,e){let t=e.byteLength,n=Hs(r),o=n+Hs(t),s=new Uint8Array(o+t);return $s(r,s,0),$s(t,s,n),s.set(e,o),new jo(r,t,e,s)}function Mr(r){let e=Sn(r),[t,n]=ga(e),[o,s]=ga(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new jo(t,o,i,e)}function mh(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&U4(r.bytes,t.bytes)}}var jo=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var j4=0,rv="identity",Z4=Sn;function nv(r){return Br(j4,Z4(r))}var Wt={code:j4,name:rv,encode:Z4,digest:nv};var bh={};pe(bh,{sha256:()=>Ne,sha512:()=>Eh});function wh({name:r,code:e,encode:t}){return new yh(r,e,t)}var yh=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Br(this.code,t):t.then(n=>Br(this.code,n))}else throw Error("Unknown type, must be binary type")}};function em(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Ne=wh({name:"sha2-256",code:18,encode:em("SHA-256")}),Eh=wh({name:"sha2-512",code:19,encode:em("SHA-512")});function tm(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return sv(t,xh(r),e??Ye.encoder);default:return iv(t,xh(r),e??ut.encoder)}}var rm=new WeakMap;function xh(r){let e=rm.get(r);if(e==null){let t=new Map;return rm.set(r,t),t}return e}var le=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!==ya)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==av)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=Br(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&&mh(e.multihash,n.multihash)}toString(e){return tm(this,e)}toJSON(){return{"/":tm(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??nm(n,o,s.bytes))}else if(t[cv]===!0){let{version:n,multihash:o,code:s}=t,i=Mr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ya)throw new Error(`Version 0 CID must use dag-pb (code: ${ya}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=nm(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ya,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=Sn(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new jo(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,h]=ga(e.subarray(t));return t+=h,u},o=n(),s=ya;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,d=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(e,t){let[n,o]=ov(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return xh(s).set(n,e),s}};function ov(r,e){switch(r[0]){case"Q":{let t=e??Ye;return[Ye.prefix,t.decode(`${Ye.prefix}${r}`)]}case Ye.prefix:{let t=e??Ye;return[Ye.prefix,t.decode(r)]}case ut.prefix:{let t=e??ut;return[ut.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function sv(r,e,t){let{prefix:n}=t;if(n!==Ye.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function iv(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var ya=112,av=18;function nm(r,e,t){let n=Hs(r),o=n+Hs(e),s=new Uint8Array(o+t.byteLength);return $s(r,s,0),$s(e,s,n),s.set(t,o),s}var cv=Symbol.for("@ipld/js-cid/CID");var br={...fh,...oh,...dh,...rh,...nh,...ih,...ah,...ch,...uh,...sh},WP={...bh,...gh};function sm(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var om=sm("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),vh=sm("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ze(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),lv={utf8:om,"utf-8":om,hex:br.base16,latin1:vh,ascii:vh,binary:vh,...br},jc=lv;function M(r,e="utf8"){let t=jc[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Rh(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return ze(i);o+i>e&&(n=ze(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var Zo=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Sh(){}var Ah=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},uv=Rh();function dv(r){return globalThis.Buffer!=null?ze(r):uv(r)}var Ea=class{len;head;tail;states;constructor(){this.len=0,this.head=new Zo(Sh,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Zo(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ih((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(Zc,10,rr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=rr.fromBigInt(e);return this._push(Zc,t.length(),t)}uint64Number(e){return this._push(Hf,Se(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=rr.fromBigInt(e).zzEncode();return this._push(Zc,t.length(),t)}sint64Number(e){let t=rr.fromNumber(e).zzEncode();return this._push(Zc,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(_h,1,e?1:0)}fixed32(e){return this._push(wa,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=rr.fromBigInt(e);return this._push(wa,4,t.lo)._push(wa,4,t.hi)}fixed64Number(e){let t=rr.fromNumber(e);return this._push(wa,4,t.lo)._push(wa,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(k4,4,e)}double(e){return this._push(N4,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(_h,1,0):this.uint32(t)._push(hv,t,e)}string(e){let t=O4(e);return t!==0?this.uint32(t)._push(Xf,t,e):this._push(_h,1,0)}fork(){return this.states=new Ah(this),this.head=this.tail=new Zo(Sh,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 Zo(Sh,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=dv(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function _h(r,e,t){e[t]=r&255}function fv(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ih=class extends Zo{next;constructor(e,t){super(fv,e,t),this.next=void 0}};function Zc(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 wa(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 hv(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Ea.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(pv,e,r),this},Ea.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(mv,e,r),this});function pv(r,e,t){e.set(r,t)}function mv(r,e,t){r.length<40?Xf(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(M(r),t)}function Dh(){return new Ea}function re(r,e){let t=Dh();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var qs;(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"})(qs||(qs={}));function Jc(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function He(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return Jc("enum",qs.VARINT,t,n)}function ne(r,e){return Jc("message",qs.LENGTH_DELIMITED,r,e)}var _n=class extends Error{code;constructor(e,t,n){super(e,n),this.code=t}};var rt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(rt||(rt={}));var Th;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Th||(Th={}));(function(r){r.codec=()=>He(Th)})(rt||(rt={}));var Gs;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.priority!=null&&t.priority!==0&&(n.uint32(16),n.int32(t.priority)),t.cancel!=null&&(n.uint32(24),n.bool(t.cancel)),t.wantType!=null&&(n.uint32(32),rt.codec().encode(t.wantType,n)),t.sendDontHave!=null&&(n.uint32(40),n.bool(t.sendDontHave)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={cid:Ie(0),priority:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.cid=t.bytes();break}case 2:{s.priority=t.int32();break}case 3:{s.cancel=t.bool();break}case 4:{s.wantType=rt.codec().decode(t);break}case 5:{s.sendDontHave=t.bool();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(Gs||(Gs={}));var el;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.entries!=null)for(let s of t.entries)n.uint32(10),Gs.codec().encode(s,n);t.full!=null&&(n.uint32(16),n.bool(t.full)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={entries:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.entries!=null&&s.entries.length===o.limits.entries)throw new _n('decode error - map field "entries" had too many elements',"ERR_MAX_LENGTH");s.entries.push(Gs.codec().decode(t,t.uint32(),{limits:o.limits?.entries$}));break}case 2:{s.full=t.bool();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(el||(el={}));var Ws;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.prefix!=null&&t.prefix.byteLength>0&&(n.uint32(10),n.bytes(t.prefix)),t.data!=null&&t.data.byteLength>0&&(n.uint32(18),n.bytes(t.data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={prefix:Ie(0),data:Ie(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.prefix=t.bytes();break}case 2:{s.data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(Ws||(Ws={}));var xr;(function(r){r.HaveBlock="HaveBlock",r.DontHaveBlock="DontHaveBlock"})(xr||(xr={}));var tl;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DontHaveBlock=1]="DontHaveBlock"})(tl||(tl={}));(function(r){r.codec=()=>He(tl)})(xr||(xr={}));var zs;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.type!=null&&tl[t.type]!==0&&(n.uint32(16),xr.codec().encode(t.type,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={cid:Ie(0),type:xr.HaveBlock},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.cid=t.bytes();break}case 2:{s.type=xr.codec().decode(t);break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(zs||(zs={}));var Jo;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.wantlist!=null&&(n.uint32(10),el.codec().encode(t.wantlist,n)),t.blocks!=null)for(let s of t.blocks)n.uint32(26),Ws.codec().encode(s,n);if(t.blockPresences!=null)for(let s of t.blockPresences)n.uint32(34),zs.codec().encode(s,n);t.pendingBytes!=null&&t.pendingBytes!==0&&(n.uint32(40),n.int32(t.pendingBytes)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.wantlist=el.codec().decode(t,t.uint32(),{limits:o.limits?.wantlist});break}case 3:{if(o.limits?.blocks!=null&&s.blocks.length===o.limits.blocks)throw new _n('decode error - map field "blocks" had too many elements',"ERR_MAX_LENGTH");s.blocks.push(Ws.codec().decode(t,t.uint32(),{limits:o.limits?.blocks$}));break}case 4:{if(o.limits?.blockPresences!=null&&s.blockPresences.length===o.limits.blockPresences)throw new _n('decode error - map field "blockPresences" had too many elements',"ERR_MAX_LENGTH");s.blockPresences.push(zs.codec().decode(t,t.uint32(),{limits:o.limits?.blockPresences$}));break}case 5:{s.pendingBytes=t.int32();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(Jo||(Jo={}));function im(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var gv=4193648,yv=gv+16;function*am(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},d=Jo.encode(l).byteLength,{added:u,hasMore:h,newSize:f}=kh(o,l.blocks,a,e,d,wv);a+=u,d=f;let p=h;({added:u,hasMore:h,newSize:f}=kh(n,l.blockPresences,i,e,d,Ev)),i+=u,d=f;let m=h;if({added:u,hasMore:h,newSize:f}=kh(t,l.wantlist.entries,s,e,d,bv),s+=u,d=f,c=!p&&!m&&!h,c||(l.wantlist.full=!1),yield Jo.encode(l),c)break}}function kh(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],d=s(l);if(d>yv)throw new g("Cannot send block as after encoding it is over the max message size","ERR_BLOCK_TOO_LARGE");let u=o+d;if(u>n){a=!0;break}e.push(l),i++,o=u}return{hasMore:a,added:i,newSize:o}}function wv(r){return Ch(3,Ws.encode(r))}function Ev(r){return Ch(4,zs.encode(r))}function bv(r){return Ch(1,Gs.encode(r))}function Ch(r,e){let t=Se(r),n=Se(e.byteLength);return t+n+e.byteLength}var rl=class extends ye{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnTransientConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[pa],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??5e3,this.runOnTransientConnections=t.runOnTransientConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new wr({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e){if(!this.running)return;let{stream:t,connection:n}=e;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,n.remotePeer);let o=()=>{t.status==="open"?t.abort(new g(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`,"ERR_TIMEOUT")):this.log("stream aborted with status %s",t.status)},s=AbortSignal.timeout(this.messageReceiveTimeout);H(1/0,s),s.addEventListener("abort",o),await t.closeWrite(),await je(t,i=>qt(i,{maxDataLength:this.maxIncomingMessageSize}),async i=>{for await(let a of i)try{let c=Jo.decode(a);this.log("incoming new bitswap %s message from %p on stream",t.protocol,n.remotePeer,t.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:c}}),s.removeEventListener("abort",o),s=AbortSignal.timeout(this.messageReceiveTimeout),H(1/0,s),s.addEventListener("abort",o)}catch(c){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,t.id,c),t.abort(c);break}})}).catch(o=>{this.log.error("error handling incoming stream from %p",n.remotePeer,o),t.abort(o)})}async*findProviders(e,t){t?.onProgress?.(new me("bitswap:network:find-providers",e));for await(let n of this.routing.findProviders(e,t))await this.libp2p.isDialable(n.multiaddrs,{runOnTransientConnection:this.runOnTransientConnections})&&(yield n)}async findAndConnect(e,t){await $t(Gt(ro(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=im(o.options.message,t),await o.join({signal:n?.signal});return}await this.sendQueue.add(async s=>{let i=s?.message;if(i==null)throw new g("No message to send","ERR_NO_MESSAGE");this.log("sendMessage to %p",e),s?.onProgress?.(new me("bitswap:network:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,pa,s);await a.closeRead();try{await je(am(i,this.maxOutgoingMessageSize),c=>Ht(c),a),await a.close(s)}catch(c){s?.onProgress?.(new me("bitswap:network:send-wantlist:error",{peer:e,error:c})),this.log.error("error sending message to %p",e,c),a.abort(c)}this._updateSentStats(i.blocks)},{peerId:e,signal:n?.signal,message:t})}async connectTo(e,t){if(!this.running)throw new g("Network isn't running","ERR_NOT_STARTED");t?.onProgress?.(new me("bitswap:network:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),er(this.libp2p,"peer:identify",t?.signal,{filter:o=>{if(!o.detail.peerId.equals(e))return!1;if(o.detail.protocols.includes(pa))return!0;throw new g(`${e} did not support ${pa}`,"ERR_BITSWAP_UNSUPPORTED_BY_PEER")}})]);return n}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};var Tv=Symbol.for("nodejs.util.inspect.custom"),cm=Object.values(br).map(r=>r.decoder).reduce((r,e)=>r.or(e),br.identity.decoder),lm=114,Nh=36,Lh=37,ba=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[ha]=!0;toString(){return this.string==null&&(this.string=Ye.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return le.createV1(lm,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Z(this.multihash.bytes,e);if(typeof e=="string")return ge(e).equals(this);if(e?.multihash?.bytes!=null)return Z(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Tv](){return`PeerId(${this.toString()})`}},es=class extends ba{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ts=class extends ba{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},rs=class extends ba{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function um(r){if(r.type==="RSA")return new es(r);if(r.type==="Ed25519")return new ts(r);if(r.type==="secp256k1")return new rs(r);throw new g("Not a PeerId","ERR_INVALID_PARAMETERS")}function ge(r,e){if(e=e??cm,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Mr(Ye.decode(`z${r}`));return r.startsWith("12D")?new ts({multihash:t}):r.startsWith("16U")?new rs({multihash:t}):new es({multihash:t})}return Je(cm.decode(r))}function Je(r){try{let e=Mr(r);if(e.code===Wt.code){if(e.digest.length===Nh)return new ts({multihash:e});if(e.digest.length===Lh)return new rs({multihash:e})}if(e.code===Ne.code)return new es({multihash:e})}catch{return kv(le.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function kv(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==lm)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Ne.code)return new es({multihash:r.multihash});if(e.code===Wt.code){if(e.digest.length===Nh)return new ts({multihash:r.multihash});if(e.digest.length===Lh)return new rs({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function dt(r,e){return r.length===Nh?new ts({multihash:Br(Wt.code,r),privateKey:e}):r.length===Lh?new rs({multihash:Br(Wt.code,r),privateKey:e}):new es({multihash:await Ne.digest(r),publicKey:r,privateKey:e})}function Ys(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var it=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Ys(this.map.entries(),e=>[ge(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,ge(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return Ys(this.map.keys(),e=>ge(e))}values(){return this.map.values()}get size(){return this.map.size}};var ht=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Ys(this.set.entries(),e=>{let t=ge(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ge(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Ys(this.set.values(),e=>ge(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var qe={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("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"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var dm={SHA1:20,SHA256:32,SHA512:64};var Nv={SHA1:"SHA-1",SHA256:"SHA-256",SHA512:"SHA-512"},Lv=async(r,e)=>{let t=await qe.get().subtle.sign({name:"HMAC"},r,e);return new Uint8Array(t,0,t.byteLength)};async function fm(r,e){let t=Nv[r],n=await qe.get().subtle.importKey("raw",e,{name:"HMAC",hash:{name:t}},!1,["sign"]);return{async digest(o){return Lv(n,o)},length:dm[r]}}var cu={};pe(cu,{Ed25519PrivateKey:()=>Ln,Ed25519PublicKey:()=>cs,MAX_RSA_KEY_SIZE:()=>ds,RsaPrivateKey:()=>Eo,RsaPublicKey:()=>us,Secp256k1PrivateKey:()=>ps,Secp256k1PublicKey:()=>hs,generateEphemeralKeyPair:()=>qm,generateKeyPair:()=>Oa,generateKeyPairFromSeed:()=>TS,importKey:()=>li,keyStretcher:()=>zm,keysPBM:()=>ni,marshalPrivateKey:()=>b0,marshalPublicKey:()=>E0,supportedKeys:()=>Kn,unmarshalPrivateKey:()=>Ar,unmarshalPublicKey:()=>zr});var Jh={};pe(Jh,{Ed25519PrivateKey:()=>Ln,Ed25519PublicKey:()=>cs,generateKeyPair:()=>KR,generateKeyPairFromSeed:()=>Zh,unmarshalEd25519PrivateKey:()=>FR,unmarshalEd25519PublicKey:()=>VR});function Ph(r,e){let t=M(r,"base64urlpad");if(e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=ve([new Uint8Array(e-t.length),t])}return t}function vr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function io(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Ov(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Xs(r,...e){if(!Ov(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function ns(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");io(r.outputLen),io(r.blockLen)}function Qs(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 hm(r,e){Xs(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var nl=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var os=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Ur=(r,e)=>r<<32-e|r>>>e,ol=(r,e)=>r<<e|r>>>32-e>>>0,mB=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Bv=async()=>{};async function pm(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let s=Date.now()-n;s>=0&&s<e||(await Bv(),n+=s)}}function Oh(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Fr(r){return typeof r=="string"&&(r=Oh(r)),Xs(r),r}function sl(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Xs(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var js=class{clone(){return this._cloneInto()}},Mv={}.toString;function mm(r,e){if(e!==void 0&&Mv.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Zs(r){let e=n=>r().update(Fr(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function ss(r=32){if(nl&&typeof nl.getRandomValues=="function")return nl.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Uv(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,l=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+l,a,n)}var il=(r,e,t)=>r&e^~r&t,al=(r,e,t)=>r&e^r&t^e&t,ao=class extends js{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=os(this.buffer)}update(e){Qs(this);let{view:t,buffer:n,blockLen:o}=this;e=Fr(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=os(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Qs(this),hm(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)t[u]=0;Uv(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=os(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var cl=BigInt(4294967295),Bh=BigInt(32);function gm(r,e=!1){return e?{h:Number(r&cl),l:Number(r>>Bh&cl)}:{h:Number(r>>Bh&cl)|0,l:Number(r&cl)|0}}function Fv(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=gm(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var Vv=(r,e)=>BigInt(r>>>0)<<Bh|BigInt(e>>>0),Kv=(r,e,t)=>r>>>t,$v=(r,e,t)=>r<<32-t|e>>>t,Hv=(r,e,t)=>r>>>t|e<<32-t,qv=(r,e,t)=>r<<32-t|e>>>t,Gv=(r,e,t)=>r<<64-t|e>>>t-32,Wv=(r,e,t)=>r>>>t-32|e<<64-t,zv=(r,e)=>e,Yv=(r,e)=>r,Xv=(r,e,t)=>r<<t|e>>>32-t,Qv=(r,e,t)=>e<<t|r>>>32-t,jv=(r,e,t)=>e<<t-32|r>>>64-t,Zv=(r,e,t)=>r<<t-32|e>>>64-t;function Jv(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var eR=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),tR=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,rR=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),nR=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,oR=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),sR=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var iR={fromBig:gm,split:Fv,toBig:Vv,shrSH:Kv,shrSL:$v,rotrSH:Hv,rotrSL:qv,rotrBH:Gv,rotrBL:Wv,rotr32H:zv,rotr32L:Yv,rotlSH:Xv,rotlSL:Qv,rotlBH:jv,rotlBL:Zv,add:Jv,add3L:eR,add3H:tR,add4L:rR,add4H:nR,add5H:sR,add5L:oR},fe=iR;var[aR,cR]=fe.split(["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))),co=new Uint32Array(80),lo=new Uint32Array(80),Mh=class extends ao{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:h,Gh:f,Gl:p,Hh:m,Hl:y}=this;return[e,t,n,o,s,i,a,c,l,d,u,h,f,p,m,y]}set(e,t,n,o,s,i,a,c,l,d,u,h,f,p,m,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=h|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=y|0}process(e,t){for(let E=0;E<16;E++,t+=4)co[E]=e.getUint32(t),lo[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let x=co[E-15]|0,v=lo[E-15]|0,I=fe.rotrSH(x,v,1)^fe.rotrSH(x,v,8)^fe.shrSH(x,v,7),S=fe.rotrSL(x,v,1)^fe.rotrSL(x,v,8)^fe.shrSL(x,v,7),R=co[E-2]|0,T=lo[E-2]|0,P=fe.rotrSH(R,T,19)^fe.rotrBH(R,T,61)^fe.shrSH(R,T,6),N=fe.rotrSL(R,T,19)^fe.rotrBL(R,T,61)^fe.shrSL(R,T,6),B=fe.add4L(S,N,lo[E-7],lo[E-16]),k=fe.add4H(B,I,P,co[E-7],co[E-16]);co[E]=k|0,lo[E]=B|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:h,Fh:f,Fl:p,Gh:m,Gl:y,Hh:w,Hl:b}=this;for(let E=0;E<80;E++){let x=fe.rotrSH(u,h,14)^fe.rotrSH(u,h,18)^fe.rotrBH(u,h,41),v=fe.rotrSL(u,h,14)^fe.rotrSL(u,h,18)^fe.rotrBL(u,h,41),I=u&f^~u&m,S=h&p^~h&y,R=fe.add5L(b,v,S,cR[E],lo[E]),T=fe.add5H(R,w,x,I,aR[E],co[E]),P=R|0,N=fe.rotrSH(n,o,28)^fe.rotrBH(n,o,34)^fe.rotrBH(n,o,39),B=fe.rotrSL(n,o,28)^fe.rotrBL(n,o,34)^fe.rotrBL(n,o,39),k=n&s^n&a^s&a,X=o&i^o&c^i&c;w=m|0,b=y|0,m=f|0,y=p|0,f=u|0,p=h|0,{h:u,l:h}=fe.add(l|0,d|0,T|0,P|0),l=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let D=fe.add3L(P,B,X);n=fe.add3H(D,T,N,k),o=D|0}({h:n,l:o}=fe.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=fe.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=fe.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=fe.add(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:h}=fe.add(this.Eh|0,this.El|0,u|0,h|0),{h:f,l:p}=fe.add(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:y}=fe.add(this.Gh|0,this.Gl|0,m|0,y|0),{h:w,l:b}=fe.add(this.Hh|0,this.Hl|0,w|0,b|0),this.set(n,o,s,i,a,c,l,d,u,h,f,p,m,y,w,b)}roundClean(){co.fill(0),lo.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var uo=Zs(()=>new Mh);var ul={};pe(ul,{abytes:()=>Js,bitGet:()=>mR,bitLen:()=>pR,bitMask:()=>xa,bitSet:()=>gR,bytesToHex:()=>In,bytesToNumberBE:()=>Dn,bytesToNumberLE:()=>Vr,concatBytes:()=>kn,createHmacDrbg:()=>Vh,ensureBytes:()=>Fe,equalBytes:()=>fR,hexToBytes:()=>is,hexToNumber:()=>Fh,isBytes:()=>fo,numberToBytesBE:()=>ho,numberToBytesLE:()=>Tn,numberToHexUnpadded:()=>bm,numberToVarBytesBE:()=>dR,utf8ToBytes:()=>hR,validateObject:()=>Rr});var Em=BigInt(0),ll=BigInt(1),lR=BigInt(2);function fo(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Js(r){if(!fo(r))throw new Error("Uint8Array expected")}var uR=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function In(r){Js(r);let e="";for(let t=0;t<r.length;t++)e+=uR[r[t]];return e}function bm(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Fh(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var An={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function ym(r){if(r>=An._0&&r<=An._9)return r-An._0;if(r>=An._A&&r<=An._F)return r-(An._A-10);if(r>=An._a&&r<=An._f)return r-(An._a-10)}function is(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=ym(r.charCodeAt(s)),a=ym(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Dn(r){return Fh(In(r))}function Vr(r){return Js(r),Fh(In(Uint8Array.from(r).reverse()))}function ho(r,e){return is(r.toString(16).padStart(e*2,"0"))}function Tn(r,e){return ho(r,e).reverse()}function dR(r){return is(bm(r))}function Fe(r,e,t){let n;if(typeof e=="string")try{n=is(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(fo(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function kn(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Js(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function fR(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 hR(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function pR(r){let e;for(e=0;r>Em;r>>=ll,e+=1);return e}function mR(r,e){return r>>BigInt(e)&ll}function gR(r,e,t){return r|(t?ll:Em)<<BigInt(e)}var xa=r=>(lR<<BigInt(r-1))-ll,Uh=r=>new Uint8Array(r),wm=r=>Uint8Array.from(r);function Vh(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Uh(r),o=Uh(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...u)=>t(o,n,...u),c=(u=Uh())=>{o=a(wm([0]),u),n=a(),u.length!==0&&(o=a(wm([1]),u),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let u=0,h=[];for(;u<e;){n=a();let f=n.slice();h.push(f),u+=n.length}return kn(...h)};return(u,h)=>{i(),c(u);let f;for(;!(f=h(l()));)c();return i(),f}}var yR={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||fo(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Rr(r,e,t={}){let n=(o,s,i)=>{let a=yR[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var ft=BigInt(0),Ge=BigInt(1),as=BigInt(2),wR=BigInt(3),Kh=BigInt(4),xm=BigInt(5),vm=BigInt(8),ER=BigInt(9),bR=BigInt(16);function De(r,e){let t=r%e;return t>=ft?t:e+t}function $h(r,e,t){if(t<=ft||e<ft)throw new Error("Expected power/modulo > 0");if(t===Ge)return ft;let n=Ge;for(;e>ft;)e&Ge&&(n=n*r%t),r=r*r%t,e>>=Ge;return n}function Ve(r,e,t){let n=r;for(;e-- >ft;)n*=n,n%=t;return n}function dl(r,e){if(r===ft||e<=ft)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=De(r,e),n=e,o=ft,s=Ge,i=Ge,a=ft;for(;t!==ft;){let l=n/t,d=n%t,u=o-i*l,h=s-a*l;n=t,t=d,o=i,s=a,i=u,a=h}if(n!==Ge)throw new Error("invert: does not exist");return De(o,e)}function xR(r){let e=(r-Ge)/as,t,n,o;for(t=r-Ge,n=0;t%as===ft;t/=as,n++);for(o=as;o<r&&$h(o,e,r)!==r-Ge;o++);if(n===1){let i=(r+Ge)/Kh;return function(c,l){let d=c.pow(l,i);if(!c.eql(c.sqr(d),l))throw new Error("Cannot find square root");return d}}let s=(t+Ge)/as;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,d=a.pow(a.mul(a.ONE,o),t),u=a.pow(c,s),h=a.pow(c,t);for(;!a.eql(h,a.ONE);){if(a.eql(h,a.ZERO))return a.ZERO;let f=1;for(let m=a.sqr(h);f<l&&!a.eql(m,a.ONE);f++)m=a.sqr(m);let p=a.pow(d,Ge<<BigInt(l-f-1));d=a.sqr(p),u=a.mul(u,p),h=a.mul(h,d),l=f}return u}}function vR(r){if(r%Kh===wR){let e=(r+Ge)/Kh;return function(n,o){let s=n.pow(o,e);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%vm===xm){let e=(r-xm)/vm;return function(n,o){let s=n.mul(o,as),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,as),i),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%bR,xR(r)}var Rm=(r,e)=>(De(r,e)&Ge)===Ge,RR=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Hh(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=RR.reduce((n,o)=>(n[o]="function",n),e);return Rr(r,t)}function SR(r,e,t){if(t<ft)throw new Error("Expected power > 0");if(t===ft)return r.ONE;if(t===Ge)return e;let n=r.ONE,o=e;for(;t>ft;)t&Ge&&(n=r.mul(n,o)),o=r.sqr(o),t>>=Ge;return n}function _R(r,e){let t=new Array(e.length),n=e.reduce((s,i,a)=>r.is0(i)?s:(t[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return e.reduceRight((s,i,a)=>r.is0(i)?s:(t[a]=r.mul(s,t[a]),r.mul(s,i)),o),t}function qh(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function fl(r,e,t=!1,n={}){if(r<=ft)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=qh(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=vR(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:xa(o),ZERO:ft,ONE:Ge,create:c=>De(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return ft<=c&&c<r},is0:c=>c===ft,isOdd:c=>(c&Ge)===Ge,neg:c=>De(-c,r),eql:(c,l)=>c===l,sqr:c=>De(c*c,r),add:(c,l)=>De(c+l,r),sub:(c,l)=>De(c-l,r),mul:(c,l)=>De(c*l,r),pow:(c,l)=>SR(a,c,l),div:(c,l)=>De(c*dl(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>dl(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>_R(a,c),cmov:(c,l,d)=>d?l:c,toBytes:c=>t?Tn(c,s):ho(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Vr(c):Dn(c)}});return Object.freeze(a)}function Sm(r,e){if(!r.isOdd)throw new Error("Field doesn't have isOdd");let t=r.sqrt(e);return r.isOdd(t)?r.neg(t):t}function _m(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function Gh(r){let e=_m(r);return e+Math.ceil(e/2)}function Am(r,e,t=!1){let n=r.length,o=_m(e),s=Gh(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Dn(r):Vr(r),a=De(i,e-Ge)+Ge;return t?Tn(a,o):ho(a,o)}var IR=BigInt(0),Wh=BigInt(1);function hl(r,e){let t=(o,s)=>{let i=s.negate();return o?i:s},n=o=>{let s=Math.ceil(e/o)+1,i=2**(o-1);return{windows:s,windowSize:i}};return{constTimeNegate:t,unsafeLadder(o,s){let i=r.ZERO,a=o;for(;s>IR;)s&Wh&&(i=i.add(a)),a=a.double(),s>>=Wh;return i},precomputeWindow(o,s){let{windows:i,windowSize:a}=n(s),c=[],l=o,d=l;for(let u=0;u<i;u++){d=l,c.push(d);for(let h=1;h<a;h++)d=d.add(l),c.push(d);l=d.double()}return c},wNAF(o,s,i){let{windows:a,windowSize:c}=n(o),l=r.ZERO,d=r.BASE,u=BigInt(2**o-1),h=2**o,f=BigInt(o);for(let p=0;p<a;p++){let m=p*c,y=Number(i&u);i>>=f,y>c&&(y-=h,i+=Wh);let w=m,b=m+Math.abs(y)-1,E=p%2!==0,x=y<0;y===0?d=d.add(t(E,s[w])):l=l.add(t(x,s[b]))}return{p:l,f:d}},wNAFCached(o,s,i,a){let c=o._WINDOW_SIZE||1,l=s.get(o);return l||(l=this.precomputeWindow(o,c),c!==1&&s.set(o,a(l))),this.wNAF(c,l,i)}}}function va(r){return Hh(r.Fp),Rr(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...qh(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Kr=BigInt(0),nr=BigInt(1),pl=BigInt(2),DR=BigInt(8),TR={zip215:!0};function kR(r){let e=va(r);return Rr(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function ml(r){let e=kR(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,l=pl<<BigInt(a*8)-nr,d=t.create,u=e.uvRatio||((C,A)=>{try{return{isValid:!0,value:t.sqrt(C*t.inv(A))}}catch{return{isValid:!1,value:Kr}}}),h=e.adjustScalarBytes||(C=>C),f=e.domain||((C,A,U)=>{if(A.length||U)throw new Error("Contexts/pre-hash are not supported");return C}),p=C=>typeof C=="bigint"&&Kr<C,m=(C,A)=>p(C)&&p(A)&&C<A,y=C=>C===Kr||m(C,l);function w(C,A){if(m(C,A))return C;throw new Error(`Expected valid scalar < ${A}, got ${typeof C} ${C}`)}function b(C){return C===Kr?C:w(C,n)}let E=new Map;function x(C){if(!(C instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(A,U,V,q){if(this.ex=A,this.ey=U,this.ez=V,this.et=q,!y(A))throw new Error("x required");if(!y(U))throw new Error("y required");if(!y(V))throw new Error("z required");if(!y(q))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(A){if(A instanceof v)throw new Error("extended point not allowed");let{x:U,y:V}=A||{};if(!y(U)||!y(V))throw new Error("invalid affine point");return new v(U,V,nr,d(U*V))}static normalizeZ(A){let U=t.invertBatch(A.map(V=>V.ez));return A.map((V,q)=>V.toAffine(U[q])).map(v.fromAffine)}_setWindowSize(A){this._WINDOW_SIZE=A,E.delete(this)}assertValidity(){let{a:A,d:U}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:V,ey:q,ez:se,et:ie}=this,de=d(V*V),ae=d(q*q),ue=d(se*se),Me=d(ue*ue),Le=d(de*A),yt=d(ue*d(Le+ae)),wt=d(Me+d(U*d(de*ae)));if(yt!==wt)throw new Error("bad point: equation left != right (1)");let lt=d(V*q),Tt=d(se*ie);if(lt!==Tt)throw new Error("bad point: equation left != right (2)")}equals(A){x(A);let{ex:U,ey:V,ez:q}=this,{ex:se,ey:ie,ez:de}=A,ae=d(U*de),ue=d(se*q),Me=d(V*de),Le=d(ie*q);return ae===ue&&Me===Le}is0(){return this.equals(v.ZERO)}negate(){return new v(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:A}=e,{ex:U,ey:V,ez:q}=this,se=d(U*U),ie=d(V*V),de=d(pl*d(q*q)),ae=d(A*se),ue=U+V,Me=d(d(ue*ue)-se-ie),Le=ae+ie,yt=Le-de,wt=ae-ie,lt=d(Me*yt),Tt=d(Le*wt),xn=d(Me*wt),Go=d(yt*Le);return new v(lt,Tt,Go,xn)}add(A){x(A);let{a:U,d:V}=e,{ex:q,ey:se,ez:ie,et:de}=this,{ex:ae,ey:ue,ez:Me,et:Le}=A;if(U===BigInt(-1)){let p4=d((se-q)*(ue+ae)),m4=d((se+q)*(ue-ae)),Of=d(m4-p4);if(Of===Kr)return this.double();let g4=d(ie*pl*Le),y4=d(de*pl*Me),w4=y4+g4,E4=m4+p4,b4=y4-g4,Nb=d(w4*Of),Lb=d(E4*b4),Pb=d(w4*b4),Ob=d(Of*E4);return new v(Nb,Lb,Ob,Pb)}let yt=d(q*ae),wt=d(se*ue),lt=d(de*V*Le),Tt=d(ie*Me),xn=d((q+se)*(ae+ue)-yt-wt),Go=Tt-lt,fa=Tt+lt,h4=d(wt-U*yt),Db=d(xn*Go),Tb=d(fa*h4),kb=d(xn*h4),Cb=d(Go*fa);return new v(Db,Tb,Cb,kb)}subtract(A){return this.add(A.negate())}wNAF(A){return R.wNAFCached(this,E,A,v.normalizeZ)}multiply(A){let{p:U,f:V}=this.wNAF(w(A,n));return v.normalizeZ([U,V])[0]}multiplyUnsafe(A){let U=b(A);return U===Kr?S:this.equals(S)||U===nr?this:this.equals(I)?this.wNAF(U).p:R.unsafeLadder(this,U)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return R.unsafeLadder(this,n).is0()}toAffine(A){let{ex:U,ey:V,ez:q}=this,se=this.is0();A==null&&(A=se?DR:t.inv(q));let ie=d(U*A),de=d(V*A),ae=d(q*A);if(se)return{x:Kr,y:nr};if(ae!==nr)throw new Error("invZ was invalid");return{x:ie,y:de}}clearCofactor(){let{h:A}=e;return A===nr?this:this.multiplyUnsafe(A)}static fromHex(A,U=!1){let{d:V,a:q}=e,se=t.BYTES;A=Fe("pointHex",A,se);let ie=A.slice(),de=A[se-1];ie[se-1]=de&-129;let ae=Vr(ie);ae===Kr||(U?w(ae,l):w(ae,t.ORDER));let ue=d(ae*ae),Me=d(ue-nr),Le=d(V*ue-q),{isValid:yt,value:wt}=u(Me,Le);if(!yt)throw new Error("Point.fromHex: invalid y coordinate");let lt=(wt&nr)===nr,Tt=(de&128)!==0;if(!U&&wt===Kr&&Tt)throw new Error("Point.fromHex: x=0 and x_0=1");return Tt!==lt&&(wt=d(-wt)),v.fromAffine({x:wt,y:ae})}static fromPrivateKey(A){return N(A).point}toRawBytes(){let{x:A,y:U}=this.toAffine(),V=Tn(U,t.BYTES);return V[V.length-1]|=A&nr?128:0,V}toHex(){return In(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,nr,d(e.Gx*e.Gy)),v.ZERO=new v(Kr,nr,nr,Kr);let{BASE:I,ZERO:S}=v,R=hl(v,a*8);function T(C){return De(C,n)}function P(C){return T(Vr(C))}function N(C){let A=a;C=Fe("private key",C,A);let U=Fe("hashed private key",s(C),2*A),V=h(U.slice(0,A)),q=U.slice(A,2*A),se=P(V),ie=I.multiply(se),de=ie.toRawBytes();return{head:V,prefix:q,scalar:se,point:ie,pointBytes:de}}function B(C){return N(C).pointBytes}function k(C=new Uint8Array,...A){let U=kn(...A);return P(s(f(U,Fe("context",C),!!o)))}function X(C,A,U={}){C=Fe("message",C),o&&(C=o(C));let{prefix:V,scalar:q,pointBytes:se}=N(A),ie=k(U.context,V,C),de=I.multiply(ie).toRawBytes(),ae=k(U.context,de,se,C),ue=T(ie+ae*q);b(ue);let Me=kn(de,Tn(ue,t.BYTES));return Fe("result",Me,a*2)}let D=TR;function L(C,A,U,V=D){let{context:q,zip215:se}=V,ie=t.BYTES;C=Fe("signature",C,2*ie),A=Fe("message",A),o&&(A=o(A));let de=Vr(C.slice(ie,2*ie)),ae,ue,Me;try{ae=v.fromHex(U,se),ue=v.fromHex(C.slice(0,ie),se),Me=I.multiplyUnsafe(de)}catch{return!1}if(!se&&ae.isSmallOrder())return!1;let Le=k(q,ue.toRawBytes(),ae.toRawBytes(),A);return ue.add(ae.multiplyUnsafe(Le)).subtract(Me).clearCofactor().equals(v.ZERO)}return I._setWindowSize(8),{CURVE:e,getPublicKey:B,sign:X,verify:L,ExtendedPoint:v,utils:{getExtendedPublicKey:N,randomPrivateKey:()=>i(t.BYTES),precompute(C=8,A=v.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}}}}var Ra=BigInt(0),zh=BigInt(1);function CR(r){return Rr(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function Im(r){let e=CR(r),{P:t}=e,n=E=>De(E,t),o=e.montgomeryBits,s=Math.ceil(o/8),i=e.nByteLength,a=e.adjustScalarBytes||(E=>E),c=e.powPminus2||(E=>$h(E,t-BigInt(2),t));function l(E,x,v){let I=n(E*(x-v));return x=n(x-I),v=n(v+I),[x,v]}function d(E){if(typeof E=="bigint"&&Ra<=E&&E<t)return E;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let u=(e.a-BigInt(2))/BigInt(4);function h(E,x){let v=d(E),I=d(x),S=v,R=zh,T=Ra,P=v,N=zh,B=Ra,k;for(let D=BigInt(o-1);D>=Ra;D--){let L=I>>D&zh;B^=L,k=l(B,R,P),R=k[0],P=k[1],k=l(B,T,N),T=k[0],N=k[1],B=L;let $=R+T,C=n($*$),A=R-T,U=n(A*A),V=C-U,q=P+N,se=P-N,ie=n(se*$),de=n(q*A),ae=ie+de,ue=ie-de;P=n(ae*ae),N=n(S*n(ue*ue)),R=n(C*U),T=n(V*(C+n(u*V)))}k=l(B,R,P),R=k[0],P=k[1],k=l(B,T,N),T=k[0],N=k[1];let X=c(T);return n(R*X)}function f(E){return Tn(n(E),s)}function p(E){let x=Fe("u coordinate",E,s);return i===32&&(x[31]&=127),Vr(x)}function m(E){let x=Fe("scalar",E),v=x.length;if(v!==s&&v!==i)throw new Error(`Expected ${s} or ${i} bytes, got ${v}`);return Vr(a(x))}function y(E,x){let v=p(x),I=m(E),S=h(v,I);if(S===Ra)throw new Error("Invalid private or public key received");return f(S)}let w=f(e.Gu);function b(E){return y(E,w)}return{scalarMult:y,scalarMultBase:b,getSharedSecret:(E,x)=>y(E,x),getPublicKey:E=>b(E),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:w}}var Sa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Dm=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),KB=BigInt(0),NR=BigInt(1),Yh=BigInt(2),LR=BigInt(5),Tm=BigInt(10),PR=BigInt(20),OR=BigInt(40),km=BigInt(80);function Cm(r){let e=Sa,n=r*r%e*r%e,o=Ve(n,Yh,e)*n%e,s=Ve(o,NR,e)*r%e,i=Ve(s,LR,e)*s%e,a=Ve(i,Tm,e)*i%e,c=Ve(a,PR,e)*a%e,l=Ve(c,OR,e)*c%e,d=Ve(l,km,e)*l%e,u=Ve(d,km,e)*l%e,h=Ve(u,Tm,e)*i%e;return{pow_p_5_8:Ve(h,Yh,e)*r%e,b2:n}}function Nm(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function BR(r,e){let t=Sa,n=De(e*e*e,t),o=De(n*n*e,t),s=Cm(r*o).pow_p_5_8,i=De(r*n*s,t),a=De(e*i*i,t),c=i,l=De(i*Dm,t),d=a===r,u=a===De(-r,t),h=a===De(-r*Dm,t);return d&&(i=c),(u||h)&&(i=l),Rm(i,t)&&(i=De(-i,t)),{isValid:d||u,value:i}}var Cn=fl(Sa,void 0,!0),Xh={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Cn,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:uo,randomBytes:ss,adjustScalarBytes:Nm,uvRatio:BR},ei=ml(Xh);function Lm(r,e,t){if(e.length>255)throw new Error("Context is too big");return sl(Oh("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var $B=ml({...Xh,domain:Lm}),HB=ml({...Xh,domain:Lm,prehash:uo}),_a=Im({P:Sa,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let e=Sa,{pow_p_5_8:t,b2:n}=Cm(r);return De(Ve(t,BigInt(3),e)*n,e)},adjustScalarBytes:Nm,randomBytes:ss});var MR=(Cn.ORDER+BigInt(3))/BigInt(8),qB=Cn.pow(Yh,MR),GB=Cn.sqrt(Cn.neg(Cn.ONE)),WB=(Cn.ORDER-BigInt(5))/BigInt(8),zB=BigInt(486662);var YB=Sm(Cn,Cn.neg(BigInt(486664)));var XB=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),QB=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),jB=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),ZB=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var JB=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ti=32,Nn=64,gl=32;function Pm(){let r=ei.utils.randomPrivateKey(),e=ei.getPublicKey(r);return{privateKey:Um(r,e),publicKey:e}}function Om(r){if(r.length!==gl)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=ei.getPublicKey(e);return{privateKey:Um(e,t),publicKey:t}}function Bm(r,e){let t=r.subarray(0,gl);return ei.sign(e instanceof Uint8Array?e:e.subarray(),t)}function Mm(r,e,t){return ei.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Um(r,e){let t=new Uint8Array(Nn);for(let n=0;n<gl;n++)t[n]=r[n],t[gl+n]=e[n];return t}var Qh={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function yl(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=qe.get();t*=8;async function c(u,h){let f=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:p};typeof h=="string"&&(h=M(h));let y;if(h.length===0){y=await a.subtle.importKey("jwk",Qh,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:f,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Qh,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:f,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}let w=await a.subtle.encrypt(m,y,u);return ve([f,m.iv,new Uint8Array(w)])}async function l(u,h){let f=u.subarray(0,s),p=u.subarray(s,s+n),m=u.subarray(s+n),y={name:e,iv:p};typeof h=="string"&&(h=M(h));let w;if(h.length===0)try{let E={name:"PBKDF2",salt:f,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(E,x,{name:e,length:t},!0,["decrypt"])}catch{w=await a.subtle.importKey("jwk",Qh,{name:"AES-GCM"},!0,["decrypt"])}else{let E={name:"PBKDF2",salt:f,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(E,x,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(y,w,m);return new Uint8Array(b)}return{encrypt:c,decrypt:l}}async function ri(r,e){let n=await yl().encrypt(r,e);return st.encode(n)}var ni={};pe(ni,{KeyType:()=>Ke,PrivateKey:()=>Hr,PublicKey:()=>$r});var Ke;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(Ke||(Ke={}));var jh;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(jh||(jh={}));(function(r){r.codec=()=>He(jh)})(Ke||(Ke={}));var $r;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ke.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=Ke.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})($r||($r={}));var Hr;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ke.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=Ke.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Hr||(Hr={}));var cs=class{_key;constructor(e){this._key=oi(e,ti)}verify(e,t){return Mm(this._key,t,e)}marshal(){return this._key}get bytes(){return $r.encode({Type:Ke.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}},Ln=class{_key;_publicKey;constructor(e,t){this._key=oi(e,Nn),this._publicKey=oi(t,ti)}sign(e){return Bm(this._key,e)}get public(){return new cs(this._publicKey)}marshal(){return this._key}get bytes(){return Hr.encode({Type:Ke.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}async hash(){let e=Ne.digest(this.bytes),t;return vr(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=Wt.digest(this.public.bytes);return Ye.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return ri(this.bytes,e);throw new g(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function FR(r){if(r.length>Nn){r=oi(r,Nn+ti);let n=r.subarray(0,Nn),o=r.subarray(Nn,r.length);return new Ln(n,o)}r=oi(r,Nn);let e=r.subarray(0,Nn),t=r.subarray(ti);return new Ln(e,t)}function VR(r){return r=oi(r,ti),new cs(r)}async function KR(){let{privateKey:r,publicKey:e}=Pm();return new Ln(r,e)}async function Zh(r){let{privateKey:e,publicKey:t}=Om(r);return new Ln(e,t)}function oi(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new g(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}function O(r,e="utf8"){let t=jc[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Vm={"P-256":256,"P-384":384,"P-521":521},$R=Object.keys(Vm),e0=$R.join(" / ");async function Km(r){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new g(`Unknown curve: ${r}. Must be ${e0}`,"ERR_INVALID_CURVE");let e=await qe.get().subtle.generateKey({name:"ECDH",namedCurve:r},!0,["deriveBits"]),t=async(s,i)=>{let a;i!=null?a=await qe.get().subtle.importKey("jwk",qR(r,i),{name:"ECDH",namedCurve:r},!1,["deriveBits"]):a=e.privateKey;let c=await qe.get().subtle.importKey("jwk",Hm(r,s),{name:"ECDH",namedCurve:r},!1,[]),l=await qe.get().subtle.deriveBits({name:"ECDH",namedCurve:r,public:c},a,Vm[r]);return new Uint8Array(l,0,l.byteLength)},n=await qe.get().subtle.exportKey("jwk",e.publicKey);return{key:HR(n),genSharedKey:t}}var $m={"P-256":32,"P-384":48,"P-521":66};function HR(r){if(r.crv==null||r.x==null||r.y==null)throw new g("JWK was missing components","ERR_INVALID_PARAMETERS");if(r.crv!=="P-256"&&r.crv!=="P-384"&&r.crv!=="P-521")throw new g(`Unknown curve: ${r.crv}. Must be ${e0}`,"ERR_INVALID_CURVE");let e=$m[r.crv];return ve([Uint8Array.from([4]),Ph(r.x,e),Ph(r.y,e)],1+e*2)}function Hm(r,e){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new g(`Unknown curve: ${r}. Must be ${e0}`,"ERR_INVALID_CURVE");let t=$m[r];if(!Z(e.subarray(0,1),Uint8Array.from([4])))throw new g("Cannot unmarshal public key - invalid key format","ERR_INVALID_KEY_FORMAT");return{kty:"EC",crv:r,x:O(e.subarray(1,t+1),"base64url"),y:O(e.subarray(1+t),"base64url"),ext:!0}}var qR=(r,e)=>({...Hm(r,e.public),d:O(e.private,"base64url")});var qm=Km;async function Gm(r,e){let t=st.decode(r);return yl().decrypt(t,e)}var Wm={"AES-128":{ivSize:16,keySize:16},"AES-256":{ivSize:16,keySize:32},Blowfish:{ivSize:8,keySize:32}};async function zm(r,e,t){let n=Wm[r];if(n==null){let b=Object.keys(Wm).join(" / ");throw new g(`unknown cipher type '${r}'. Must be ${b}`,"ERR_INVALID_CIPHER_TYPE")}if(e==null)throw new g("missing hash type","ERR_MISSING_HASH_TYPE");let o=n.keySize,s=n.ivSize,i=20,a=M("key expansion"),c=2*(s+o+i),l=await fm(e,t),d=await l.digest(a),u=[],h=0;for(;h<c;){let b=await l.digest(ve([d,a])),E=b.length;h+E>c&&(E=c-h),u.push(b),h+=E,d=await l.digest(d)}let f=c/2,p=ve(u),m=p.subarray(0,f),y=p.subarray(f,c),w=b=>({iv:b.subarray(0,s),cipherKey:b.subarray(s,s+o),macKey:b.subarray(s+o)});return{k1:w(m),k2:w(y)}}var d0={};pe(d0,{MAX_RSA_KEY_SIZE:()=>ds,RsaPrivateKey:()=>Eo,RsaPublicKey:()=>us,fromJwk:()=>pS,generateKeyPair:()=>mS,unmarshalRsaPrivateKey:()=>l0,unmarshalRsaPublicKey:()=>hS});function pt(r){if(isNaN(r)||r<=0)throw new g("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return ss(r)}var wo={};pe(wo,{exportToPem:()=>lS,importFromPem:()=>c0,jwkToPkcs1:()=>sS,jwkToPkix:()=>aS,pkcs1ToJwk:()=>oS,pkixToJwk:()=>iS});var wl=class extends js{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ns(e);let n=Fr(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Qs(this),this.iHash.update(e),this}digestInto(e){Qs(this),Xs(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},po=(r,e,t)=>new wl(r,e).update(t).digest();po.create=(r,e)=>new wl(r,e);function Ym(r,e,t,n){ns(r);let o=mm({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(io(s),io(i),io(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Fr(e),l=Fr(t),d=new Uint8Array(i),u=po.create(r,c),h=u._cloneInto().update(l);return{c:s,dkLen:i,asyncTick:a,DK:d,PRF:u,PRFSalt:h}}function Xm(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}function Qm(r,e,t,n){let{c:o,dkLen:s,DK:i,PRF:a,PRFSalt:c}=Ym(r,e,t,n),l,d=new Uint8Array(4),u=os(d),h=new Uint8Array(a.outputLen);for(let f=1,p=0;p<s;f++,p+=a.outputLen){let m=i.subarray(p,p+a.outputLen);u.setInt32(0,f,!1),(l=c._cloneInto(l)).update(d).digestInto(h),m.set(h.subarray(0,m.length));for(let y=1;y<o;y++){a._cloneInto(l).update(h).digestInto(h);for(let w=0;w<m.length;w++)m[w]^=h[w]}}return Xm(a,c,i,l,h)}async function t0(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=Ym(r,e,t,n),d,u=new Uint8Array(4),h=os(u),f=new Uint8Array(c.outputLen);for(let p=1,m=0;m<s;p++,m+=c.outputLen){let y=a.subarray(m,m+c.outputLen);h.setInt32(0,p,!1),(d=l._cloneInto(d)).update(u).digestInto(f),y.set(f.subarray(0,y.length)),await pm(o-1,i,()=>{c._cloneInto(d).update(f).digestInto(f);for(let w=0;w<y.length;w++)y[w]^=f[w]})}return Xm(c,l,a,d,f)}var we=Qe(jm());function ls(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 mo(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let d=a-1;d>=0;d--){let u=Math.pow(2,d*e);l[s-d-1]=Math.floor(o/u),o-=l[s-d-1]*u}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function xl(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function n0(){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=ls(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,ls(s,8)-n}function Zm(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=mo(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=mo(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function Jm(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 zt(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var HM=Math.log(2);function vl(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function o0(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Un(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 Ia=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return o0(this.items)}},Aa=[new Uint8Array([1])],e8="0123456789";var ai="",Gr=new ArrayBuffer(0),s0=new Uint8Array(0),Da="EndOfContent",r8="OCTET STRING",n8="BIT STRING";function Fn(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?we.BufferSourceConverter.toUint8Array(s.valueHex):s0}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Un(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Gr)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:we.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var On=class{constructor({blockLength:e=0,error:t=ai,warnings:n=[],valueBeforeDecode:o=s0}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=we.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:we.Convert.ToHex(this.valueBeforeDecodeView)}}};On.NAME="baseBlock";var Lt=class extends On{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Lt.NAME="valueBlock";var Rl=class extends Fn(On){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?we.BufferSourceConverter.toUint8Array(e.valueHex):s0,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",Gr}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=mo(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=we.BufferSourceConverter.toUint8Array(e);if(!Un(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),d=255;for(;s[c]&128;){if(l[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===d){d+=255;let h=new Uint8Array(d);for(let f=0;f<l.length;f++)h[f]=l[f];l=this.valueHexView=new Uint8Array(d)}}this.blockLength=c+1,l[c-1]=s[c]&127;let u=new Uint8Array(c);for(let h=0;h<c;h++)u[h]=l[h];l=this.valueHexView=new Uint8Array(c),l.set(u),this.blockLength<=9?this.tagNumber=ls(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}}};Rl.NAME="identificationBlock";var Sl=class extends On{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=we.BufferSourceConverter.toUint8Array(e);if(!Un(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=ls(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=mo(this.length,8);if(o.byteLength>127)return this.error="Too big length",Gr;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Sl.NAME="lengthBlock";var W={},Et=class extends On{constructor({name:e=ai,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Rl(o),this.lenBlock=new Sl(o),this.valueBlock=s?new s(o):new Lt(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new Ia;t||o8(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?Gr: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():we.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${we.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return Jm(t,n)}};Et.NAME="BaseBlock";function o8(r){if(r instanceof W.Constructed)for(let e of r.valueBlock.value)o8(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var _l=class extends Et{constructor({value:e=ai,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=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}'`}};_l.NAME="BaseStringBlock";var Al=class extends Fn(Lt){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Al.NAME="PrimitiveValueBlock";var s8,Il=class extends Et{constructor(e={}){super(e,Al),this.idBlock.isConstructed=!1}};s8=Il;W.Primitive=s8;Il.NAME="PRIMITIVE";function JR(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 iu(r,e=0,t=r.length){let n=e,o=new Et({},Lt),s=new On;if(!Un(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Et;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=W.EndOfContent;break;case 1:c=W.Boolean;break;case 2:c=W.Integer;break;case 3:c=W.BitString;break;case 4:c=W.OctetString;break;case 5:c=W.Null;break;case 6:c=W.ObjectIdentifier;break;case 10:c=W.Enumerated;break;case 12:c=W.Utf8String;break;case 13:c=W.RelativeObjectIdentifier;break;case 14:c=W.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=W.Sequence;break;case 17:c=W.Set;break;case 18:c=W.NumericString;break;case 19:c=W.PrintableString;break;case 20:c=W.TeletexString;break;case 21:c=W.VideotexString;break;case 22:c=W.IA5String;break;case 23:c=W.UTCTime;break;case 24:c=W.GeneralizedTime;break;case 25:c=W.GraphicString;break;case 26:c=W.VisibleString;break;case 27:c=W.GeneralString;break;case 28:c=W.UniversalString;break;case 29:c=W.CharacterString;break;case 30:c=W.BmpString;break;case 31:c=W.DATE;break;case 32:c=W.TimeOfDay;break;case 33:c=W.DateTime;break;case 34:c=W.Duration;break;default:{let l=o.idBlock.isConstructed?new W.Constructed:new W.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?W.Constructed:W.Primitive}return o=JR(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function ci(r){if(!r.byteLength){let e=new Et({},Lt);return e.error="Input buffer has zero length",{offset:-1,result:e}}return iu(we.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function eS(r,e){return r?1:e}var un=class extends Lt{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=we.BufferSourceConverter.toUint8Array(e);if(!Un(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;eS(this.isIndefiniteForm,n)>0;){let i=iu(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===Da)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Da?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Ia;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?Gr:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};un.NAME="ConstructedValueBlock";var i8,go=class extends Et{constructor(e={}){super(e,un),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
17
|
+
`});var fE=ke(()=>{dE();zd();$o();T3();Tc()});var N3,Xae,hE=ke(()=>{Vw();Kw();$w();Hw();qw();b3();Gw();R3();Ww();Yw();nE();iE();aE();cE();fE();N3={...p3,...m3,...g3,...y3,...w3,...E3,...x3,...v3,...S3,..._3},Xae={...k3,...C3}});function sa(r){return globalThis.Buffer!=null?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r}var jd=ke(()=>{});function Zd(r=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?sa(globalThis.Buffer.allocUnsafe(r)):new Uint8Array(r)}var L3=ke(()=>{jd()});function mE(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var pE,P3,$C,Jd,O3=ke(()=>{hE();L3();pE=mE("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),P3=mE("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=Zd(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),$C={utf8:pE,"utf-8":pE,hex:N3.base16,latin1:P3,ascii:P3,binary:P3,...N3},Jd=$C});var gE={};pe(gE,{toString:()=>HC});function HC(r,e="utf8"){let t=Jd[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(r.buffer,r.byteOffset,r.byteLength).toString("utf8"):t.encoder.encode(r).substring(1)}var yE=ke(()=>{O3()});var wE={};pe(wE,{fromString:()=>qC});function qC(r,e="utf8"){let t=Jd[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?sa(globalThis.Buffer.from(r,"utf-8")):t.decoder.decode(`${t.prefix}${r}`)}var EE=ke(()=>{O3();jd()});var bE={};pe(bE,{concat:()=>GC});function GC(r,e){e||(e=r.reduce((o,s)=>o+s.length,0));let t=Zd(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return sa(t)}var xE=ke(()=>{L3();jd()});var M3=Re((cce,IE)=>{"use strict";var vE=Ew(),ia=kw(),{names:Cc}=Nw(),{toString:ef}=(yE(),Mc(gE)),{fromString:WC}=(EE(),Mc(wE)),{concat:zC}=(xE(),Mc(bE)),aa={};for(let r in Cc){let e=r;aa[Cc[e]]=e}Object.freeze(aa);function YC(r){if(!(r instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return ef(r,"base16")}function XC(r){return WC(r,"base16")}function QC(r){if(!(r instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return ef(vE.encode("base58btc",r)).slice(1)}function jC(r){let e=r instanceof Uint8Array?ef(r):r;return vE.decode("z"+e)}function RE(r){if(!(r instanceof Uint8Array))throw new Error("multihash must be a Uint8Array");if(r.length<2)throw new Error("multihash too short. must be > 2 bytes.");let e=ia.decode(r);if(!_E(e))throw new Error(`multihash unknown function code: 0x${e.toString(16)}`);r=r.slice(ia.decode.bytes);let t=ia.decode(r);if(t<0)throw new Error(`multihash invalid length: ${t}`);if(r=r.slice(ia.decode.bytes),r.length!==t)throw new Error(`multihash length inconsistent: 0x${ef(r,"base16")}`);return{code:e,name:aa[e],length:t,digest:r}}function ZC(r,e,t){if(!r||e===void 0)throw new Error("multihash encode requires at least two args: digest, code");let n=SE(e);if(!(r instanceof Uint8Array))throw new Error("digest should be a Uint8Array");if(t==null&&(t=r.length),t&&r.length!==t)throw new Error("digest length should be equal to specified length.");let o=ia.encode(n),s=ia.encode(t);return zC([o,s,r],o.length+s.length+r.length)}function SE(r){let e=r;if(typeof r=="string"){if(Cc[r]===void 0)throw new Error(`Unrecognized hash function named: ${r}`);e=Cc[r]}if(typeof e!="number")throw new Error(`Hash function code should be a number. Got: ${e}`);if(aa[e]===void 0&&!B3(e))throw new Error(`Unrecognized function code: ${e}`);return e}function B3(r){return r>0&&r<16}function _E(r){return!!(B3(r)||aa[r])}function AE(r){RE(r)}function JC(r){return AE(r),r.subarray(0,2)}IE.exports={names:Cc,codes:aa,toHexString:YC,fromHexString:XC,toB58String:QC,fromB58String:jC,decode:RE,encode:ZC,coerceCode:SE,isAppCode:B3,validate:AE,prefix:JC,isValidCode:_E}});var VE=Re(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var K3=class{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;let t={value:e,done:!1};if(this.pullQueue.length){let n=this.pullQueue.shift();n&&n.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),this.highWaterMark!==void 0&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(let e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(let t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{let t=Promise.reject(e);t.catch(()=>{}),this.pushQueue.push(t)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{let t=this.pushQueue.shift();return t?(this.lowWaterMark!==void 0&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((n,o)=>{this.pullQueue.push({resolve:n,reject:o})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}},nf=class{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){let o=new K3;o.highWaterMark=t,o.lowWaterMark=n,o.removeCallback=e({push:s=>o.push(s),stop:()=>o.stop(),fail:s=>o.fail(s),on:(s,i)=>{o.eventHandlers[s]=i}})||(()=>{}),this[Symbol.asyncIterator]=()=>o[Symbol.asyncIterator](),Object.freeze(this)}};of.EventIterator=nf;of.default=nf});var KE=Re(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var $3=VE();Nc.EventIterator=$3.EventIterator;function aN(r,e,t){return new $3.EventIterator(({push:n})=>(this.addEventListener(r,n,e),()=>this.removeEventListener(r,n,e)),t)}Nc.subscribe=aN;Nc.default=$3.EventIterator});var UN={};pe(UN,{DEFAULT_SESSION_MAX_PROVIDERS:()=>tg,DEFAULT_SESSION_MIN_PROVIDERS:()=>eg,createHelia:()=>BN,libp2pDefaults:()=>lf});var v4=Symbol.for("@libp2p/connection");var on=Symbol.for("@libp2p/content-routing");var Wo=Symbol.for("@libp2p/peer-discovery");var ha=Symbol.for("@libp2p/peer-id");function Ms(r){return r!=null&&!!r[ha]}var sn=Symbol.for("@libp2p/peer-routing");var R4="keep-alive";var an=Symbol.for("@libp2p/transport");var to;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(to||(to={}));var Kt=class r extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=r.code,this.type=r.type}static code="ABORT_ERR";static type="aborted"},g=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}},Uc=class extends AggregateError{code;props;constructor(e,t,n,o){super(e,t),this.code=n,this.name=o?.name??"AggregateCodeError",this.props=o??{}}};var vn="ERR_TIMEOUT";var zo="ERR_INVALID_MESSAGE";var H=(r,...e)=>{try{[...e]}catch{}};var ye=class extends EventTarget{#e=new Map;constructor(){super(),H(1/0,this)}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new Ot(e,t))}},Bf=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Ot=globalThis.CustomEvent??Bf;function Fc(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function cn(...r){let e=[];for(let t of r)Fc(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 ln(...r){let e=[];for(let t of r)Fc(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()}))}function Ae(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}function J(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Vc=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)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}},Us=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Vc(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Vc(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Mf=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function kt(r={}){return Kb(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 Kb(r,e){e=e??{};let t=e.onEnd,n=new Us,o,s,i,a=J(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,w)=>{s=b=>{s=null,n.push(b);try{y(r(n))}catch(E){w(E)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=J()})}},l=y=>s!=null?s(y):(n.push(y),o),d=y=>(n=new Us,s!=null?s({error:y}):(n.push({error:y}),o)),u=y=>{if(i)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},h=y=>i?o:(i=!0,y!=null?d(y):l({done:!0})),f=()=>(n=new Us,h(),{done:!0}),p=y=>(h(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:f,throw:p,push:u,end:h,get readableLength(){return n.size},onEmpty:async y=>{let w=y?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let b,E;w!=null&&(b=new Promise((x,v)=>{E=()=>{v(new Mf)},w.addEventListener("abort",E)}));try{await Promise.race([a.promise,b])}finally{E!=null&&w!=null&&w?.removeEventListener("abort",E)}}},t==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(y){return m.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},o}var Uf=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function er(r,e,t,n){let o=new Uf(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",d),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=u=>{try{if(n?.filter?.(u)===!1)return}catch(h){a(),i(h);return}a(),s(u)},l=u=>{a(),i(u.detail)},d=()=>{a(),i(o)};t?.addEventListener("abort",d),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var Kc=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Ue(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new Kc(t?.errorMessage,t?.errorCode));let n,o=new Kc(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var $c=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=J(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Kt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function $b(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Hc=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=$b(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,H(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Kt),this.cleanup())}async join(e={}){let t=new $c(new Error("where").stack,e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await Ue(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var tr=class extends ye{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!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){t?.signal?.throwIfAborted();let n=new Hc(e,t),o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("error",{detail:s}),this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Kt)}),this.clear()}async onEmpty(e){this.size!==0&&await er(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await er(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await er(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=kt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail)},i=()=>{n()},a=()=>{n(new g("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var wr=class extends tr{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function Hb(r){return r[Symbol.asyncIterator]!=null}function qb(r){if(Hb(r))return(async()=>{for await(let e of r);})();for(let e of r);}var $t=qb;function Ie(r=0){return new Uint8Array(r)}function ze(r=0){return new Uint8Array(r)}var Gb=Math.pow(2,7),Wb=Math.pow(2,14),zb=Math.pow(2,21),Ff=Math.pow(2,28),Vf=Math.pow(2,35),Kf=Math.pow(2,42),$f=Math.pow(2,49),Ce=128,Ct=127;function Se(r){if(r<Gb)return 1;if(r<Wb)return 2;if(r<zb)return 3;if(r<Ff)return 4;if(r<Vf)return 5;if(r<Kf)return 6;if(r<$f)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Hf(r,e,t=0){switch(Se(r)){case 8:e[t++]=r&255|Ce,r/=128;case 7:e[t++]=r&255|Ce,r/=128;case 6:e[t++]=r&255|Ce,r/=128;case 5:e[t++]=r&255|Ce,r/=128;case 4:e[t++]=r&255|Ce,r>>>=7;case 3:e[t++]=r&255|Ce,r>>>=7;case 2:e[t++]=r&255|Ce,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Yb(r,e,t=0){switch(Se(r)){case 8:e.set(t++,r&255|Ce),r/=128;case 7:e.set(t++,r&255|Ce),r/=128;case 6:e.set(t++,r&255|Ce),r/=128;case 5:e.set(t++,r&255|Ce),r/=128;case 4:e.set(t++,r&255|Ce),r>>>=7;case 3:e.set(t++,r&255|Ce),r>>>=7;case 2:e.set(t++,r&255|Ce),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function qf(r,e){let t=r[e],n=0;if(n+=t&Ct,t<Ce||(t=r[e+1],n+=(t&Ct)<<7,t<Ce)||(t=r[e+2],n+=(t&Ct)<<14,t<Ce)||(t=r[e+3],n+=(t&Ct)<<21,t<Ce)||(t=r[e+4],n+=(t&Ct)*Ff,t<Ce)||(t=r[e+5],n+=(t&Ct)*Vf,t<Ce)||(t=r[e+6],n+=(t&Ct)*Kf,t<Ce)||(t=r[e+7],n+=(t&Ct)*$f,t<Ce))return n;throw new RangeError("Could not decode varint")}function Xb(r,e){let t=r.get(e),n=0;if(n+=t&Ct,t<Ce||(t=r.get(e+1),n+=(t&Ct)<<7,t<Ce)||(t=r.get(e+2),n+=(t&Ct)<<14,t<Ce)||(t=r.get(e+3),n+=(t&Ct)<<21,t<Ce)||(t=r.get(e+4),n+=(t&Ct)*Ff,t<Ce)||(t=r.get(e+5),n+=(t&Ct)*Vf,t<Ce)||(t=r.get(e+6),n+=(t&Ct)*Kf,t<Ce)||(t=r.get(e+7),n+=(t&Ct)*$f,t<Ce))return n;throw new RangeError("Could not decode varint")}function $e(r,e,t=0){return e==null&&(e=ze(Se(r))),e instanceof Uint8Array?Hf(r,e,t):Yb(r,e,t)}function Bt(r,e=0){return r instanceof Uint8Array?qf(r,e):Xb(r,e)}function ve(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=ze(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function Z(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var _4=Symbol.for("@achingbrain/uint8arraylist");function S4(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 qc(r){return!!r?.[_4]}var ce=class r{bufs;length;[_4]=!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(qc(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(qc(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=S4(this.bufs,e);return t.buf[t.index]}set(e,t){let n=S4(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(qc(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 ve(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:ve(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,d=t>a&&t<=c;if(l&&d){if(e===a&&t===c){n.push(i);break}let u=e-a;n.push(i.subarray(u,u+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(d){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!qc(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,d;for(let u=t;u<=c;u+=d){d=0;for(let h=l;h>=0;h--){let f=this.get(u+h);if(n[h]!==f){d=Math.max(1,h-a[f]);break}}if(d===0)return u}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ze(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=Ie(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=Ie(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=Ie(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=ze(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=Ie(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=Ie(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=Ie(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=Ie(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=Ie(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Z(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function Gc(r){return r[Symbol.asyncIterator]!=null}var Wc=r=>{let e=Se(r),t=ze(e);return $e(r,t),Wc.bytes=e,t};Wc.bytes=0;function Ht(r,e){e=e??{};let t=e.lengthEncoder??Wc;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Gc(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Ht.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Wc;return new ce(t(r.byteLength),r)};var Fs=Qe(Yo(),1);var Zb=8,Jb=1024*1024*4,Xo;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Xo||(Xo={}));var Gf=r=>{let e=Bt(r);return Gf.bytes=Se(e),e};Gf.bytes=0;function qt(r,e){let t=new ce,n=Xo.LENGTH,o=-1,s=e?.lengthDecoder??Gf,i=e?.maxLengthLength??Zb,a=e?.maxDataLength??Jb;function*c(){for(;t.byteLength>0;){if(n===Xo.LENGTH)try{if(o=s(t),o<0)throw(0,Fs.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>a)throw(0,Fs.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=Xo.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw(0,Fs.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(n===Xo.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=Xo.LENGTH}}}return Gc(r)?async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw(0,Fs.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw(0,Fs.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}qt.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return qt(n,{...e??{},onLength:s=>{t=s}})};function ex(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Vs=ex;function tx(r){return r[Symbol.asyncIterator]!=null}function rx(r,e){let t=0;if(tx(r))return async function*(){for await(let c of r)yield e(c,t++)}();let n=Vs(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){yield await i;for await(let c of n)yield e(c,t++)}();let a=e;return function*(){yield i;for(let c of n)yield a(c,t++)}()}var Gt=rx;function nx(r){return r[Symbol.asyncIterator]!=null}function ox(...r){let e=[];for(let t of r)nx(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=kt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var Mt=ox;function je(r,...e){if(r==null)throw new Error("Empty pipeline");if(Wf(r)){let n=r;r=()=>n.source}else if(T4(r)||D4(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Wf(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++)Wf(t[n])&&(t[n]=ix(t[n]));return sx(...t)}var sx=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},D4=r=>r?.[Symbol.asyncIterator]!=null,T4=r=>r?.[Symbol.iterator]!=null,Wf=r=>r==null?!1:r.sink!=null&&r.source!=null,ix=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=kt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(D4(s))o=async function*(){yield*s,n.end()};else if(T4(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Mt(n,o())}return r.source};function ax(r){return r[Symbol.asyncIterator]!=null}function cx(r,e){return ax(r)?async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}}():function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}}()}var ro=cx;var me=class extends Event{constructor(e,t){super(e),this.detail=t}};var pa="/ipfs/bitswap/1.2.0";var zf=new Float32Array([-0]),no=new Uint8Array(zf.buffer);function k4(r,e,t){zf[0]=r,e[t]=no[0],e[t+1]=no[1],e[t+2]=no[2],e[t+3]=no[3]}function C4(r,e){return no[0]=r[e],no[1]=r[e+1],no[2]=r[e+2],no[3]=r[e+3],zf[0]}var Yf=new Float64Array([-0]),Nt=new Uint8Array(Yf.buffer);function N4(r,e,t){Yf[0]=r,e[t]=Nt[0],e[t+1]=Nt[1],e[t+2]=Nt[2],e[t+3]=Nt[3],e[t+4]=Nt[4],e[t+5]=Nt[5],e[t+6]=Nt[6],e[t+7]=Nt[7]}function L4(r,e){return Nt[0]=r[e],Nt[1]=r[e+1],Nt[2]=r[e+2],Nt[3]=r[e+3],Nt[4]=r[e+4],Nt[5]=r[e+5],Nt[6]=r[e+6],Nt[7]=r[e+7],Yf[0]}var lx=BigInt(Number.MAX_SAFE_INTEGER),ux=BigInt(Number.MIN_SAFE_INTEGER),rr=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 Qo;if(e<lx&&e>ux)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>P4&&(o=0n,++n>P4&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Qo;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):Qo}},Qo=new rr(0,0);Qo.toBigInt=function(){return 0n};Qo.zzEncode=Qo.zzDecode=function(){return this};Qo.length=function(){return 1};var P4=4294967296n;function O4(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 B4(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Xf(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Or(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Yc(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Qf=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,Or(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 Or(this,4);return Yc(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Or(this,4);return Yc(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Or(this,4);let e=C4(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Or(this,4);let e=L4(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 Or(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return B4(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Or(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Or(this);while(this.buf[this.pos++]&128);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 rr(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 Or(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 Or(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 Or(this,8);let e=Yc(this.buf,this.pos+=4),t=Yc(this.buf,this.pos+=4);return new rr(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=qf(this.buf,this.pos);return this.pos+=Se(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 jf(r){return new Qf(r instanceof Uint8Array?r:r.subarray())}function te(r,e,t){let n=jf(r);return e.decode(n,void 0,t)}var rh={};pe(rh,{base10:()=>gx});var cP=new Uint8Array(0);function U4(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 Sn(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 F4(r){return new TextEncoder().encode(r)}function V4(r){return new TextDecoder().decode(r)}function dx(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var m=0,y=0,w=0,b=p.length;w!==b&&p[w]===0;)w++,m++;for(var E=(b-w)*d+1>>>0,x=new Uint8Array(E);w!==b;){for(var v=p[w],I=0,S=E-1;(v!==0||I<y)&&S!==-1;S--,I++)v+=256*x[S]>>>0,x[S]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");y=I,w++}for(var R=E-y;R!==E&&x[R]===0;)R++;for(var T=c.repeat(m);R<E;++R)T+=r.charAt(x[R]);return T}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var m=0;if(p[m]!==" "){for(var y=0,w=0;p[m]===c;)y++,m++;for(var b=(p.length-m)*l+1>>>0,E=new Uint8Array(b);p[m];){var x=t[p.charCodeAt(m)];if(x===255)return;for(var v=0,I=b-1;(x!==0||v<w)&&I!==-1;I--,v++)x+=a*E[I]>>>0,E[I]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");w=v,m++}if(p[m]!==" "){for(var S=b-w;S!==b&&E[S]===0;)S++;for(var R=new Uint8Array(y+(b-S)),T=y;S!==b;)R[T++]=E[S++];return R}}}function f(p){var m=h(p);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:h,decode:f}}var fx=dx,hx=fx,$4=hx;var Zf=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")}},Jf=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),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 H4(this,e)}},eh=class{decoders;constructor(e){this.decoders=e}or(e){return H4(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 H4(r,e){return new eh({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var th=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 Zf(e,t,n),this.decoder=new Jf(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ks({name:r,prefix:e,encode:t,decode:n}){return new th(r,e,t,n)}function oo({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=$4(t,r);return Ks({prefix:e,name:r,encode:n,decode:s=>Sn(o(s))})}function px(r,e,t,n){let o={};for(let d=0;d<e.length;++d)o[e[d]]=d;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,l=0;for(let d=0;d<s;++d){let u=o[r[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,a+=t,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function mx(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;s.length*t&7;)s+="=";return s}function Ze({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Ks({prefix:e,name:r,encode(o){return mx(o,n,t)},decode(o){return px(o,n,t,r)}})}var gx=oo({prefix:"9",name:"base10",alphabet:"0123456789"});var nh={};pe(nh,{base16:()=>yx,base16upper:()=>wx});var yx=Ze({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),wx=Ze({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var oh={};pe(oh,{base2:()=>Ex});var Ex=Ze({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var sh={};pe(sh,{base256emoji:()=>Sx});var q4=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}"),bx=q4.reduce((r,e,t)=>(r[t]=e,r),[]),xx=q4.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function vx(r){return r.reduce((e,t)=>(e+=bx[t],e),"")}function Rx(r){let e=[];for(let t of r){let n=xx[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Sx=Ks({prefix:"\u{1F680}",name:"base256emoji",encode:vx,decode:Rx});var ih={};pe(ih,{base32:()=>ut,base32hex:()=>Ix,base32hexpad:()=>Tx,base32hexpadupper:()=>kx,base32hexupper:()=>Dx,base32pad:()=>_x,base32padupper:()=>Ax,base32upper:()=>G4,base32z:()=>Cx});var ut=Ze({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),G4=Ze({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),_x=Ze({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ax=Ze({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ix=Ze({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Dx=Ze({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Tx=Ze({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),kx=Ze({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Cx=Ze({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ah={};pe(ah,{base36:()=>so,base36upper:()=>Nx});var so=oo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Nx=oo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ch={};pe(ch,{base58btc:()=>Ye,base58flickr:()=>Lx});var Ye=oo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Lx=oo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var uh={};pe(uh,{base64:()=>st,base64pad:()=>Px,base64url:()=>lh,base64urlpad:()=>Ox});var st=Ze({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Px=Ze({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),lh=Ze({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ox=Ze({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var dh={};pe(dh,{base8:()=>Bx});var Bx=Ze({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var fh={};pe(fh,{identity:()=>Mx});var Mx=Ks({prefix:"\0",name:"identity",encode:r=>V4(r),decode:r=>F4(r)});var SP=new TextEncoder,_P=new TextDecoder;var W4=512;var Xc=85;var gh={};pe(gh,{identity:()=>Wt});var Er={};pe(Er,{Digest:()=>jo,create:()=>Br,decode:()=>Mr,equals:()=>mh});var Ux=Q4,Y4=128,Fx=127,Vx=~Fx,Kx=Math.pow(2,31);function Q4(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Kx;)e[t++]=r&255|Y4,r/=128;for(;r&Vx;)e[t++]=r&255|Y4,r>>>=7;return e[t]=r|0,Q4.bytes=t-n+1,e}var $x=ph,Hx=128,X4=127;function ph(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ph.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&X4)<<o:(i&X4)*Math.pow(2,o),o+=7}while(i>=Hx);return ph.bytes=s-n,t}var qx=Math.pow(2,7),Gx=Math.pow(2,14),Wx=Math.pow(2,21),zx=Math.pow(2,28),Yx=Math.pow(2,35),Xx=Math.pow(2,42),Qx=Math.pow(2,49),jx=Math.pow(2,56),Zx=Math.pow(2,63),Jx=function(r){return r<qx?1:r<Gx?2:r<Wx?3:r<zx?4:r<Yx?5:r<Xx?6:r<Qx?7:r<jx?8:r<Zx?9:10},ev={encode:Ux,decode:$x,encodingLength:Jx},tv=ev,ma=tv;function ga(r,e=0){return[ma.decode(r,e),ma.decode.bytes]}function $s(r,e,t=0){return ma.encode(r,e,t),e}function Hs(r){return ma.encodingLength(r)}function Br(r,e){let t=e.byteLength,n=Hs(r),o=n+Hs(t),s=new Uint8Array(o+t);return $s(r,s,0),$s(t,s,n),s.set(e,o),new jo(r,t,e,s)}function Mr(r){let e=Sn(r),[t,n]=ga(e),[o,s]=ga(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new jo(t,o,i,e)}function mh(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&U4(r.bytes,t.bytes)}}var jo=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var j4=0,rv="identity",Z4=Sn;function nv(r){return Br(j4,Z4(r))}var Wt={code:j4,name:rv,encode:Z4,digest:nv};var bh={};pe(bh,{sha256:()=>Ne,sha512:()=>Eh});function wh({name:r,code:e,encode:t}){return new yh(r,e,t)}var yh=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?Br(this.code,t):t.then(n=>Br(this.code,n))}else throw Error("Unknown type, must be binary type")}};function e8(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Ne=wh({name:"sha2-256",code:18,encode:e8("SHA-256")}),Eh=wh({name:"sha2-512",code:19,encode:e8("SHA-512")});function t8(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return sv(t,xh(r),e??Ye.encoder);default:return iv(t,xh(r),e??ut.encoder)}}var r8=new WeakMap;function xh(r){let e=r8.get(r);if(e==null){let t=new Map;return r8.set(r,t),t}return e}var le=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!==ya)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==av)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=Br(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&&mh(e.multihash,n.multihash)}toString(e){return t8(this,e)}toJSON(){return{"/":t8(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??n8(n,o,s.bytes))}else if(t[cv]===!0){let{version:n,multihash:o,code:s}=t,i=Mr(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ya)throw new Error(`Version 0 CID must use dag-pb (code: ${ya}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=n8(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ya,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=Sn(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new jo(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,h]=ga(e.subarray(t));return t+=h,u},o=n(),s=ya;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,d=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(e,t){let[n,o]=ov(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return xh(s).set(n,e),s}};function ov(r,e){switch(r[0]){case"Q":{let t=e??Ye;return[Ye.prefix,t.decode(`${Ye.prefix}${r}`)]}case Ye.prefix:{let t=e??Ye;return[Ye.prefix,t.decode(r)]}case ut.prefix:{let t=e??ut;return[ut.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function sv(r,e,t){let{prefix:n}=t;if(n!==Ye.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function iv(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var ya=112,av=18;function n8(r,e,t){let n=Hs(r),o=n+Hs(e),s=new Uint8Array(o+t.byteLength);return $s(r,s,0),$s(e,s,n),s.set(t,o),s}var cv=Symbol.for("@ipld/js-cid/CID");var br={...fh,...oh,...dh,...rh,...nh,...ih,...ah,...ch,...uh,...sh},WP={...bh,...gh};function s8(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var o8=s8("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),vh=s8("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ze(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),lv={utf8:o8,"utf-8":o8,hex:br.base16,latin1:vh,ascii:vh,binary:vh,...br},jc=lv;function M(r,e="utf8"){let t=jc[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Rh(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return ze(i);o+i>e&&(n=ze(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var Zo=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function Sh(){}var Ah=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},uv=Rh();function dv(r){return globalThis.Buffer!=null?ze(r):uv(r)}var Ea=class{len;head;tail;states;constructor(){this.len=0,this.head=new Zo(Sh,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Zo(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ih((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(Zc,10,rr.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=rr.fromBigInt(e);return this._push(Zc,t.length(),t)}uint64Number(e){return this._push(Hf,Se(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=rr.fromBigInt(e).zzEncode();return this._push(Zc,t.length(),t)}sint64Number(e){let t=rr.fromNumber(e).zzEncode();return this._push(Zc,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(_h,1,e?1:0)}fixed32(e){return this._push(wa,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=rr.fromBigInt(e);return this._push(wa,4,t.lo)._push(wa,4,t.hi)}fixed64Number(e){let t=rr.fromNumber(e);return this._push(wa,4,t.lo)._push(wa,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(k4,4,e)}double(e){return this._push(N4,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(_h,1,0):this.uint32(t)._push(hv,t,e)}string(e){let t=O4(e);return t!==0?this.uint32(t)._push(Xf,t,e):this._push(_h,1,0)}fork(){return this.states=new Ah(this),this.head=this.tail=new Zo(Sh,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 Zo(Sh,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=dv(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function _h(r,e,t){e[t]=r&255}function fv(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var Ih=class extends Zo{next;constructor(e,t){super(fv,e,t),this.next=void 0}};function Zc(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 wa(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 hv(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Ea.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(pv,e,r),this},Ea.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(mv,e,r),this});function pv(r,e,t){e.set(r,t)}function mv(r,e,t){r.length<40?Xf(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(M(r),t)}function Dh(){return new Ea}function re(r,e){let t=Dh();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var qs;(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"})(qs||(qs={}));function Jc(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function He(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return Jc("enum",qs.VARINT,t,n)}function ne(r,e){return Jc("message",qs.LENGTH_DELIMITED,r,e)}var _n=class extends Error{code;constructor(e,t,n){super(e,n),this.code=t}};var rt;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(rt||(rt={}));var Th;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(Th||(Th={}));(function(r){r.codec=()=>He(Th)})(rt||(rt={}));var Gs;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.priority!=null&&t.priority!==0&&(n.uint32(16),n.int32(t.priority)),t.cancel!=null&&(n.uint32(24),n.bool(t.cancel)),t.wantType!=null&&(n.uint32(32),rt.codec().encode(t.wantType,n)),t.sendDontHave!=null&&(n.uint32(40),n.bool(t.sendDontHave)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={cid:Ie(0),priority:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.cid=t.bytes();break}case 2:{s.priority=t.int32();break}case 3:{s.cancel=t.bool();break}case 4:{s.wantType=rt.codec().decode(t);break}case 5:{s.sendDontHave=t.bool();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(Gs||(Gs={}));var el;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.entries!=null)for(let s of t.entries)n.uint32(10),Gs.codec().encode(s,n);t.full!=null&&(n.uint32(16),n.bool(t.full)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={entries:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.entries!=null&&s.entries.length===o.limits.entries)throw new _n('decode error - map field "entries" had too many elements',"ERR_MAX_LENGTH");s.entries.push(Gs.codec().decode(t,t.uint32(),{limits:o.limits?.entries$}));break}case 2:{s.full=t.bool();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(el||(el={}));var Ws;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.prefix!=null&&t.prefix.byteLength>0&&(n.uint32(10),n.bytes(t.prefix)),t.data!=null&&t.data.byteLength>0&&(n.uint32(18),n.bytes(t.data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={prefix:Ie(0),data:Ie(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.prefix=t.bytes();break}case 2:{s.data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(Ws||(Ws={}));var xr;(function(r){r.HaveBlock="HaveBlock",r.DontHaveBlock="DontHaveBlock"})(xr||(xr={}));var tl;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DontHaveBlock=1]="DontHaveBlock"})(tl||(tl={}));(function(r){r.codec=()=>He(tl)})(xr||(xr={}));var zs;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.type!=null&&tl[t.type]!==0&&(n.uint32(16),xr.codec().encode(t.type,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={cid:Ie(0),type:xr.HaveBlock},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.cid=t.bytes();break}case 2:{s.type=xr.codec().decode(t);break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(zs||(zs={}));var Jo;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.wantlist!=null&&(n.uint32(10),el.codec().encode(t.wantlist,n)),t.blocks!=null)for(let s of t.blocks)n.uint32(26),Ws.codec().encode(s,n);if(t.blockPresences!=null)for(let s of t.blockPresences)n.uint32(34),zs.codec().encode(s,n);t.pendingBytes!=null&&t.pendingBytes!==0&&(n.uint32(40),n.int32(t.pendingBytes)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={blocks:[],blockPresences:[],pendingBytes:0},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.wantlist=el.codec().decode(t,t.uint32(),{limits:o.limits?.wantlist});break}case 3:{if(o.limits?.blocks!=null&&s.blocks.length===o.limits.blocks)throw new _n('decode error - map field "blocks" had too many elements',"ERR_MAX_LENGTH");s.blocks.push(Ws.codec().decode(t,t.uint32(),{limits:o.limits?.blocks$}));break}case 4:{if(o.limits?.blockPresences!=null&&s.blockPresences.length===o.limits.blockPresences)throw new _n('decode error - map field "blockPresences" had too many elements',"ERR_MAX_LENGTH");s.blockPresences.push(zs.codec().decode(t,t.uint32(),{limits:o.limits?.blockPresences$}));break}case 5:{s.pendingBytes=t.int32();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>re(t,r.codec()),r.decode=(t,n)=>te(t,r.codec(),n)})(Jo||(Jo={}));function i8(r,e){for(let[t,n]of e.wantlist.entries()){let o=r.wantlist.get(t);o!=null&&(o.priority>n.priority&&(n.priority=o.priority),n.cancel=n.cancel??o.cancel,n.wantType=n.wantType??o.wantType,n.sendDontHave=n.sendDontHave??o.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var gv=4193648,yv=gv+16;function*a8(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],o=[...r.blocks.values()],s=0,i=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},d=Jo.encode(l).byteLength,{added:u,hasMore:h,newSize:f}=kh(o,l.blocks,a,e,d,wv);a+=u,d=f;let p=h;({added:u,hasMore:h,newSize:f}=kh(n,l.blockPresences,i,e,d,Ev)),i+=u,d=f;let m=h;if({added:u,hasMore:h,newSize:f}=kh(t,l.wantlist.entries,s,e,d,bv),s+=u,d=f,c=!p&&!m&&!h,c||(l.wantlist.full=!1),yield Jo.encode(l),c)break}}function kh(r,e,t,n,o,s){let i=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],d=s(l);if(d>yv)throw new g("Cannot send block as after encoding it is over the max message size","ERR_BLOCK_TOO_LARGE");let u=o+d;if(u>n){a=!0;break}e.push(l),i++,o=u}return{hasMore:a,added:i,newSize:o}}function wv(r){return Ch(3,Ws.encode(r))}function Ev(r){return Ch(4,zs.encode(r))}function bv(r){return Ch(1,Gs.encode(r))}function Ch(r,e){let t=Se(r),n=Se(e.byteLength);return t+n+e.byteLength}var rl=class extends ye{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnTransientConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[pa],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??5e3,this.runOnTransientConnections=t.runOnTransientConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new wr({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e){if(!this.running)return;let{stream:t,connection:n}=e;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,n.remotePeer);let o=()=>{t.status==="open"?t.abort(new g(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`,"ERR_TIMEOUT")):this.log("stream aborted with status %s",t.status)},s=AbortSignal.timeout(this.messageReceiveTimeout);H(1/0,s),s.addEventListener("abort",o),await t.closeWrite(),await je(t,i=>qt(i,{maxDataLength:this.maxIncomingMessageSize}),async i=>{for await(let a of i)try{let c=Jo.decode(a);this.log("incoming new bitswap %s message from %p on stream",t.protocol,n.remotePeer,t.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:c}}),s.removeEventListener("abort",o),s=AbortSignal.timeout(this.messageReceiveTimeout),H(1/0,s),s.addEventListener("abort",o)}catch(c){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,t.id,c),t.abort(c);break}})}).catch(o=>{this.log.error("error handling incoming stream from %p",n.remotePeer,o),t.abort(o)})}async*findProviders(e,t){t?.onProgress?.(new me("bitswap:network:find-providers",e));for await(let n of this.routing.findProviders(e,t))await this.libp2p.isDialable(n.multiaddrs,{runOnTransientConnection:this.runOnTransientConnections})&&(yield n)}async findAndConnect(e,t){await $t(Gt(ro(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let o=this.sendQueue.queue.find(s=>e.equals(s.options.peerId)&&s.status==="queued");if(o!=null){o.options.message=i8(o.options.message,t),await o.join({signal:n?.signal});return}await this.sendQueue.add(async s=>{let i=s?.message;if(i==null)throw new g("No message to send","ERR_NO_MESSAGE");this.log("sendMessage to %p",e),s?.onProgress?.(new me("bitswap:network:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,pa,s);await a.closeRead();try{await je(a8(i,this.maxOutgoingMessageSize),c=>Ht(c),a),await a.close(s)}catch(c){s?.onProgress?.(new me("bitswap:network:send-wantlist:error",{peer:e,error:c})),this.log.error("error sending message to %p",e,c),a.abort(c)}this._updateSentStats(i.blocks)},{peerId:e,signal:n?.signal,message:t})}async connectTo(e,t){if(!this.running)throw new g("Network isn't running","ERR_NOT_STARTED");t?.onProgress?.(new me("bitswap:network:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),er(this.libp2p,"peer:identify",t?.signal,{filter:o=>{if(!o.detail.peerId.equals(e))return!1;if(o.detail.protocols.includes(pa))return!0;throw new g(`${e} did not support ${pa}`,"ERR_BITSWAP_UNSUPPORTED_BY_PEER")}})]);return n}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};var Tv=Symbol.for("nodejs.util.inspect.custom"),c8=Object.values(br).map(r=>r.decoder).reduce((r,e)=>r.or(e),br.identity.decoder),l8=114,Nh=36,Lh=37,ba=class{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[ha]=!0;toString(){return this.string==null&&(this.string=Ye.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return le.createV1(l8,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Z(this.multihash.bytes,e);if(typeof e=="string")return ge(e).equals(this);if(e?.multihash?.bytes!=null)return Z(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Tv](){return`PeerId(${this.toString()})`}},es=class extends ba{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},ts=class extends ba{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},rs=class extends ba{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function u8(r){if(r.type==="RSA")return new es(r);if(r.type==="Ed25519")return new ts(r);if(r.type==="secp256k1")return new rs(r);throw new g("Not a PeerId","ERR_INVALID_PARAMETERS")}function ge(r,e){if(e=e??c8,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Mr(Ye.decode(`z${r}`));return r.startsWith("12D")?new ts({multihash:t}):r.startsWith("16U")?new rs({multihash:t}):new es({multihash:t})}return Je(c8.decode(r))}function Je(r){try{let e=Mr(r);if(e.code===Wt.code){if(e.digest.length===Nh)return new ts({multihash:e});if(e.digest.length===Lh)return new rs({multihash:e})}if(e.code===Ne.code)return new es({multihash:e})}catch{return kv(le.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function kv(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==l8)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Ne.code)return new es({multihash:r.multihash});if(e.code===Wt.code){if(e.digest.length===Nh)return new ts({multihash:r.multihash});if(e.digest.length===Lh)return new rs({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function dt(r,e){return r.length===Nh?new ts({multihash:Br(Wt.code,r),privateKey:e}):r.length===Lh?new rs({multihash:Br(Wt.code,r),privateKey:e}):new es({multihash:await Ne.digest(r),publicKey:r,privateKey:e})}function Ys(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var it=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),n)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Ys(this.map.entries(),e=>[ge(e[0]),e[1]])}forEach(e){this.map.forEach((t,n)=>{e(t,ge(n),this)})}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return Ys(this.map.keys(),e=>ge(e))}values(){return this.map.values()}get size(){return this.map.size}};var ht=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Ys(this.set.entries(),e=>{let t=ge(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=ge(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Ys(this.set.values(),e=>ge(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};var qe={get(r=globalThis){let e=r.crypto;if(e==null||e.subtle==null)throw Object.assign(new Error("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"),{code:"ERR_MISSING_WEB_CRYPTO"});return e}};var d8={SHA1:20,SHA256:32,SHA512:64};var Nv={SHA1:"SHA-1",SHA256:"SHA-256",SHA512:"SHA-512"},Lv=async(r,e)=>{let t=await qe.get().subtle.sign({name:"HMAC"},r,e);return new Uint8Array(t,0,t.byteLength)};async function f8(r,e){let t=Nv[r],n=await qe.get().subtle.importKey("raw",e,{name:"HMAC",hash:{name:t}},!1,["sign"]);return{async digest(o){return Lv(n,o)},length:d8[r]}}var cu={};pe(cu,{Ed25519PrivateKey:()=>Ln,Ed25519PublicKey:()=>cs,MAX_RSA_KEY_SIZE:()=>ds,RsaPrivateKey:()=>Eo,RsaPublicKey:()=>us,Secp256k1PrivateKey:()=>ps,Secp256k1PublicKey:()=>hs,generateEphemeralKeyPair:()=>q8,generateKeyPair:()=>Oa,generateKeyPairFromSeed:()=>TS,importKey:()=>li,keyStretcher:()=>z8,keysPBM:()=>ni,marshalPrivateKey:()=>b0,marshalPublicKey:()=>E0,supportedKeys:()=>Kn,unmarshalPrivateKey:()=>Ar,unmarshalPublicKey:()=>zr});var Jh={};pe(Jh,{Ed25519PrivateKey:()=>Ln,Ed25519PublicKey:()=>cs,generateKeyPair:()=>KR,generateKeyPairFromSeed:()=>Zh,unmarshalEd25519PrivateKey:()=>FR,unmarshalEd25519PublicKey:()=>VR});function Ph(r,e){let t=M(r,"base64urlpad");if(e!=null){if(t.length>e)throw new Error("byte array longer than desired length");t=ve([new Uint8Array(e-t.length),t])}return t}function vr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function io(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Ov(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Xs(r,...e){if(!Ov(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${r.length}`)}function ns(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");io(r.outputLen),io(r.blockLen)}function Qs(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 h8(r,e){Xs(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var nl=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var os=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Ur=(r,e)=>r<<32-e|r>>>e,ol=(r,e)=>r<<e|r>>>32-e>>>0,mB=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Bv=async()=>{};async function p8(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let s=Date.now()-n;s>=0&&s<e||(await Bv(),n+=s)}}function Oh(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Fr(r){return typeof r=="string"&&(r=Oh(r)),Xs(r),r}function sl(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Xs(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var js=class{clone(){return this._cloneInto()}},Mv={}.toString;function m8(r,e){if(e!==void 0&&Mv.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Zs(r){let e=n=>r().update(Fr(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function ss(r=32){if(nl&&typeof nl.getRandomValues=="function")return nl.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Uv(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,l=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+l,a,n)}var il=(r,e,t)=>r&e^~r&t,al=(r,e,t)=>r&e^r&t^e&t,ao=class extends js{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=os(this.buffer)}update(e){Qs(this);let{view:t,buffer:n,blockLen:o}=this;e=Fr(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=os(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Qs(this),h8(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)t[u]=0;Uv(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=os(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var cl=BigInt(4294967295),Bh=BigInt(32);function g8(r,e=!1){return e?{h:Number(r&cl),l:Number(r>>Bh&cl)}:{h:Number(r>>Bh&cl)|0,l:Number(r&cl)|0}}function Fv(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=g8(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var Vv=(r,e)=>BigInt(r>>>0)<<Bh|BigInt(e>>>0),Kv=(r,e,t)=>r>>>t,$v=(r,e,t)=>r<<32-t|e>>>t,Hv=(r,e,t)=>r>>>t|e<<32-t,qv=(r,e,t)=>r<<32-t|e>>>t,Gv=(r,e,t)=>r<<64-t|e>>>t-32,Wv=(r,e,t)=>r>>>t-32|e<<64-t,zv=(r,e)=>e,Yv=(r,e)=>r,Xv=(r,e,t)=>r<<t|e>>>32-t,Qv=(r,e,t)=>e<<t|r>>>32-t,jv=(r,e,t)=>e<<t-32|r>>>64-t,Zv=(r,e,t)=>r<<t-32|e>>>64-t;function Jv(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var eR=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),tR=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,rR=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),nR=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,oR=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),sR=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var iR={fromBig:g8,split:Fv,toBig:Vv,shrSH:Kv,shrSL:$v,rotrSH:Hv,rotrSL:qv,rotrBH:Gv,rotrBL:Wv,rotr32H:zv,rotr32L:Yv,rotlSH:Xv,rotlSL:Qv,rotlBH:jv,rotlBL:Zv,add:Jv,add3L:eR,add3H:tR,add4L:rR,add4H:nR,add5H:sR,add5L:oR},fe=iR;var[aR,cR]=fe.split(["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))),co=new Uint32Array(80),lo=new Uint32Array(80),Mh=class extends ao{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:h,Gh:f,Gl:p,Hh:m,Hl:y}=this;return[e,t,n,o,s,i,a,c,l,d,u,h,f,p,m,y]}set(e,t,n,o,s,i,a,c,l,d,u,h,f,p,m,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=h|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=y|0}process(e,t){for(let E=0;E<16;E++,t+=4)co[E]=e.getUint32(t),lo[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let x=co[E-15]|0,v=lo[E-15]|0,I=fe.rotrSH(x,v,1)^fe.rotrSH(x,v,8)^fe.shrSH(x,v,7),S=fe.rotrSL(x,v,1)^fe.rotrSL(x,v,8)^fe.shrSL(x,v,7),R=co[E-2]|0,T=lo[E-2]|0,P=fe.rotrSH(R,T,19)^fe.rotrBH(R,T,61)^fe.shrSH(R,T,6),N=fe.rotrSL(R,T,19)^fe.rotrBL(R,T,61)^fe.shrSL(R,T,6),B=fe.add4L(S,N,lo[E-7],lo[E-16]),k=fe.add4H(B,I,P,co[E-7],co[E-16]);co[E]=k|0,lo[E]=B|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:h,Fh:f,Fl:p,Gh:m,Gl:y,Hh:w,Hl:b}=this;for(let E=0;E<80;E++){let x=fe.rotrSH(u,h,14)^fe.rotrSH(u,h,18)^fe.rotrBH(u,h,41),v=fe.rotrSL(u,h,14)^fe.rotrSL(u,h,18)^fe.rotrBL(u,h,41),I=u&f^~u&m,S=h&p^~h&y,R=fe.add5L(b,v,S,cR[E],lo[E]),T=fe.add5H(R,w,x,I,aR[E],co[E]),P=R|0,N=fe.rotrSH(n,o,28)^fe.rotrBH(n,o,34)^fe.rotrBH(n,o,39),B=fe.rotrSL(n,o,28)^fe.rotrBL(n,o,34)^fe.rotrBL(n,o,39),k=n&s^n&a^s&a,X=o&i^o&c^i&c;w=m|0,b=y|0,m=f|0,y=p|0,f=u|0,p=h|0,{h:u,l:h}=fe.add(l|0,d|0,T|0,P|0),l=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let D=fe.add3L(P,B,X);n=fe.add3H(D,T,N,k),o=D|0}({h:n,l:o}=fe.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=fe.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=fe.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=fe.add(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:h}=fe.add(this.Eh|0,this.El|0,u|0,h|0),{h:f,l:p}=fe.add(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:y}=fe.add(this.Gh|0,this.Gl|0,m|0,y|0),{h:w,l:b}=fe.add(this.Hh|0,this.Hl|0,w|0,b|0),this.set(n,o,s,i,a,c,l,d,u,h,f,p,m,y,w,b)}roundClean(){co.fill(0),lo.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var uo=Zs(()=>new Mh);var ul={};pe(ul,{abytes:()=>Js,bitGet:()=>mR,bitLen:()=>pR,bitMask:()=>xa,bitSet:()=>gR,bytesToHex:()=>In,bytesToNumberBE:()=>Dn,bytesToNumberLE:()=>Vr,concatBytes:()=>kn,createHmacDrbg:()=>Vh,ensureBytes:()=>Fe,equalBytes:()=>fR,hexToBytes:()=>is,hexToNumber:()=>Fh,isBytes:()=>fo,numberToBytesBE:()=>ho,numberToBytesLE:()=>Tn,numberToHexUnpadded:()=>b8,numberToVarBytesBE:()=>dR,utf8ToBytes:()=>hR,validateObject:()=>Rr});var E8=BigInt(0),ll=BigInt(1),lR=BigInt(2);function fo(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Js(r){if(!fo(r))throw new Error("Uint8Array expected")}var uR=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function In(r){Js(r);let e="";for(let t=0;t<r.length;t++)e+=uR[r[t]];return e}function b8(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function Fh(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var An={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function y8(r){if(r>=An._0&&r<=An._9)return r-An._0;if(r>=An._A&&r<=An._F)return r-(An._A-10);if(r>=An._a&&r<=An._f)return r-(An._a-10)}function is(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=y8(r.charCodeAt(s)),a=y8(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Dn(r){return Fh(In(r))}function Vr(r){return Js(r),Fh(In(Uint8Array.from(r).reverse()))}function ho(r,e){return is(r.toString(16).padStart(e*2,"0"))}function Tn(r,e){return ho(r,e).reverse()}function dR(r){return is(b8(r))}function Fe(r,e,t){let n;if(typeof e=="string")try{n=is(e)}catch(s){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${s}`)}else if(fo(e))n=Uint8Array.from(e);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(`${r} expected ${t} bytes, got ${o}`);return n}function kn(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Js(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function fR(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 hR(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function pR(r){let e;for(e=0;r>E8;r>>=ll,e+=1);return e}function mR(r,e){return r>>BigInt(e)&ll}function gR(r,e,t){return r|(t?ll:E8)<<BigInt(e)}var xa=r=>(lR<<BigInt(r-1))-ll,Uh=r=>new Uint8Array(r),w8=r=>Uint8Array.from(r);function Vh(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=Uh(r),o=Uh(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...u)=>t(o,n,...u),c=(u=Uh())=>{o=a(w8([0]),u),n=a(),u.length!==0&&(o=a(w8([1]),u),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let u=0,h=[];for(;u<e;){n=a();let f=n.slice();h.push(f),u+=n.length}return kn(...h)};return(u,h)=>{i(),c(u);let f;for(;!(f=h(l()));)c();return i(),f}}var yR={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||fo(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Rr(r,e,t={}){let n=(o,s,i)=>{let a=yR[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var ft=BigInt(0),Ge=BigInt(1),as=BigInt(2),wR=BigInt(3),Kh=BigInt(4),x8=BigInt(5),v8=BigInt(8),ER=BigInt(9),bR=BigInt(16);function De(r,e){let t=r%e;return t>=ft?t:e+t}function $h(r,e,t){if(t<=ft||e<ft)throw new Error("Expected power/modulo > 0");if(t===Ge)return ft;let n=Ge;for(;e>ft;)e&Ge&&(n=n*r%t),r=r*r%t,e>>=Ge;return n}function Ve(r,e,t){let n=r;for(;e-- >ft;)n*=n,n%=t;return n}function dl(r,e){if(r===ft||e<=ft)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=De(r,e),n=e,o=ft,s=Ge,i=Ge,a=ft;for(;t!==ft;){let l=n/t,d=n%t,u=o-i*l,h=s-a*l;n=t,t=d,o=i,s=a,i=u,a=h}if(n!==Ge)throw new Error("invert: does not exist");return De(o,e)}function xR(r){let e=(r-Ge)/as,t,n,o;for(t=r-Ge,n=0;t%as===ft;t/=as,n++);for(o=as;o<r&&$h(o,e,r)!==r-Ge;o++);if(n===1){let i=(r+Ge)/Kh;return function(c,l){let d=c.pow(l,i);if(!c.eql(c.sqr(d),l))throw new Error("Cannot find square root");return d}}let s=(t+Ge)/as;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,d=a.pow(a.mul(a.ONE,o),t),u=a.pow(c,s),h=a.pow(c,t);for(;!a.eql(h,a.ONE);){if(a.eql(h,a.ZERO))return a.ZERO;let f=1;for(let m=a.sqr(h);f<l&&!a.eql(m,a.ONE);f++)m=a.sqr(m);let p=a.pow(d,Ge<<BigInt(l-f-1));d=a.sqr(p),u=a.mul(u,p),h=a.mul(h,d),l=f}return u}}function vR(r){if(r%Kh===wR){let e=(r+Ge)/Kh;return function(n,o){let s=n.pow(o,e);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%v8===x8){let e=(r-x8)/v8;return function(n,o){let s=n.mul(o,as),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,as),i),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%bR,xR(r)}var R8=(r,e)=>(De(r,e)&Ge)===Ge,RR=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Hh(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=RR.reduce((n,o)=>(n[o]="function",n),e);return Rr(r,t)}function SR(r,e,t){if(t<ft)throw new Error("Expected power > 0");if(t===ft)return r.ONE;if(t===Ge)return e;let n=r.ONE,o=e;for(;t>ft;)t&Ge&&(n=r.mul(n,o)),o=r.sqr(o),t>>=Ge;return n}function _R(r,e){let t=new Array(e.length),n=e.reduce((s,i,a)=>r.is0(i)?s:(t[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return e.reduceRight((s,i,a)=>r.is0(i)?s:(t[a]=r.mul(s,t[a]),r.mul(s,i)),o),t}function qh(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function fl(r,e,t=!1,n={}){if(r<=ft)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=qh(r,e);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=vR(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:xa(o),ZERO:ft,ONE:Ge,create:c=>De(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return ft<=c&&c<r},is0:c=>c===ft,isOdd:c=>(c&Ge)===Ge,neg:c=>De(-c,r),eql:(c,l)=>c===l,sqr:c=>De(c*c,r),add:(c,l)=>De(c+l,r),sub:(c,l)=>De(c-l,r),mul:(c,l)=>De(c*l,r),pow:(c,l)=>SR(a,c,l),div:(c,l)=>De(c*dl(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>dl(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>_R(a,c),cmov:(c,l,d)=>d?l:c,toBytes:c=>t?Tn(c,s):ho(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return t?Vr(c):Dn(c)}});return Object.freeze(a)}function S8(r,e){if(!r.isOdd)throw new Error("Field doesn't have isOdd");let t=r.sqrt(e);return r.isOdd(t)?r.neg(t):t}function _8(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function Gh(r){let e=_8(r);return e+Math.ceil(e/2)}function A8(r,e,t=!1){let n=r.length,o=_8(e),s=Gh(e);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=t?Dn(r):Vr(r),a=De(i,e-Ge)+Ge;return t?Tn(a,o):ho(a,o)}var IR=BigInt(0),Wh=BigInt(1);function hl(r,e){let t=(o,s)=>{let i=s.negate();return o?i:s},n=o=>{let s=Math.ceil(e/o)+1,i=2**(o-1);return{windows:s,windowSize:i}};return{constTimeNegate:t,unsafeLadder(o,s){let i=r.ZERO,a=o;for(;s>IR;)s&Wh&&(i=i.add(a)),a=a.double(),s>>=Wh;return i},precomputeWindow(o,s){let{windows:i,windowSize:a}=n(s),c=[],l=o,d=l;for(let u=0;u<i;u++){d=l,c.push(d);for(let h=1;h<a;h++)d=d.add(l),c.push(d);l=d.double()}return c},wNAF(o,s,i){let{windows:a,windowSize:c}=n(o),l=r.ZERO,d=r.BASE,u=BigInt(2**o-1),h=2**o,f=BigInt(o);for(let p=0;p<a;p++){let m=p*c,y=Number(i&u);i>>=f,y>c&&(y-=h,i+=Wh);let w=m,b=m+Math.abs(y)-1,E=p%2!==0,x=y<0;y===0?d=d.add(t(E,s[w])):l=l.add(t(x,s[b]))}return{p:l,f:d}},wNAFCached(o,s,i,a){let c=o._WINDOW_SIZE||1,l=s.get(o);return l||(l=this.precomputeWindow(o,c),c!==1&&s.set(o,a(l))),this.wNAF(c,l,i)}}}function va(r){return Hh(r.Fp),Rr(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...qh(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Kr=BigInt(0),nr=BigInt(1),pl=BigInt(2),DR=BigInt(8),TR={zip215:!0};function kR(r){let e=va(r);return Rr(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function ml(r){let e=kR(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,l=pl<<BigInt(a*8)-nr,d=t.create,u=e.uvRatio||((C,A)=>{try{return{isValid:!0,value:t.sqrt(C*t.inv(A))}}catch{return{isValid:!1,value:Kr}}}),h=e.adjustScalarBytes||(C=>C),f=e.domain||((C,A,U)=>{if(A.length||U)throw new Error("Contexts/pre-hash are not supported");return C}),p=C=>typeof C=="bigint"&&Kr<C,m=(C,A)=>p(C)&&p(A)&&C<A,y=C=>C===Kr||m(C,l);function w(C,A){if(m(C,A))return C;throw new Error(`Expected valid scalar < ${A}, got ${typeof C} ${C}`)}function b(C){return C===Kr?C:w(C,n)}let E=new Map;function x(C){if(!(C instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(A,U,V,q){if(this.ex=A,this.ey=U,this.ez=V,this.et=q,!y(A))throw new Error("x required");if(!y(U))throw new Error("y required");if(!y(V))throw new Error("z required");if(!y(q))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(A){if(A instanceof v)throw new Error("extended point not allowed");let{x:U,y:V}=A||{};if(!y(U)||!y(V))throw new Error("invalid affine point");return new v(U,V,nr,d(U*V))}static normalizeZ(A){let U=t.invertBatch(A.map(V=>V.ez));return A.map((V,q)=>V.toAffine(U[q])).map(v.fromAffine)}_setWindowSize(A){this._WINDOW_SIZE=A,E.delete(this)}assertValidity(){let{a:A,d:U}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:V,ey:q,ez:se,et:ie}=this,de=d(V*V),ae=d(q*q),ue=d(se*se),Me=d(ue*ue),Le=d(de*A),yt=d(ue*d(Le+ae)),wt=d(Me+d(U*d(de*ae)));if(yt!==wt)throw new Error("bad point: equation left != right (1)");let lt=d(V*q),Tt=d(se*ie);if(lt!==Tt)throw new Error("bad point: equation left != right (2)")}equals(A){x(A);let{ex:U,ey:V,ez:q}=this,{ex:se,ey:ie,ez:de}=A,ae=d(U*de),ue=d(se*q),Me=d(V*de),Le=d(ie*q);return ae===ue&&Me===Le}is0(){return this.equals(v.ZERO)}negate(){return new v(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:A}=e,{ex:U,ey:V,ez:q}=this,se=d(U*U),ie=d(V*V),de=d(pl*d(q*q)),ae=d(A*se),ue=U+V,Me=d(d(ue*ue)-se-ie),Le=ae+ie,yt=Le-de,wt=ae-ie,lt=d(Me*yt),Tt=d(Le*wt),xn=d(Me*wt),Go=d(yt*Le);return new v(lt,Tt,Go,xn)}add(A){x(A);let{a:U,d:V}=e,{ex:q,ey:se,ez:ie,et:de}=this,{ex:ae,ey:ue,ez:Me,et:Le}=A;if(U===BigInt(-1)){let p4=d((se-q)*(ue+ae)),m4=d((se+q)*(ue-ae)),Of=d(m4-p4);if(Of===Kr)return this.double();let g4=d(ie*pl*Le),y4=d(de*pl*Me),w4=y4+g4,E4=m4+p4,b4=y4-g4,Nb=d(w4*Of),Lb=d(E4*b4),Pb=d(w4*b4),Ob=d(Of*E4);return new v(Nb,Lb,Ob,Pb)}let yt=d(q*ae),wt=d(se*ue),lt=d(de*V*Le),Tt=d(ie*Me),xn=d((q+se)*(ae+ue)-yt-wt),Go=Tt-lt,fa=Tt+lt,h4=d(wt-U*yt),Db=d(xn*Go),Tb=d(fa*h4),kb=d(xn*h4),Cb=d(Go*fa);return new v(Db,Tb,Cb,kb)}subtract(A){return this.add(A.negate())}wNAF(A){return R.wNAFCached(this,E,A,v.normalizeZ)}multiply(A){let{p:U,f:V}=this.wNAF(w(A,n));return v.normalizeZ([U,V])[0]}multiplyUnsafe(A){let U=b(A);return U===Kr?S:this.equals(S)||U===nr?this:this.equals(I)?this.wNAF(U).p:R.unsafeLadder(this,U)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return R.unsafeLadder(this,n).is0()}toAffine(A){let{ex:U,ey:V,ez:q}=this,se=this.is0();A==null&&(A=se?DR:t.inv(q));let ie=d(U*A),de=d(V*A),ae=d(q*A);if(se)return{x:Kr,y:nr};if(ae!==nr)throw new Error("invZ was invalid");return{x:ie,y:de}}clearCofactor(){let{h:A}=e;return A===nr?this:this.multiplyUnsafe(A)}static fromHex(A,U=!1){let{d:V,a:q}=e,se=t.BYTES;A=Fe("pointHex",A,se);let ie=A.slice(),de=A[se-1];ie[se-1]=de&-129;let ae=Vr(ie);ae===Kr||(U?w(ae,l):w(ae,t.ORDER));let ue=d(ae*ae),Me=d(ue-nr),Le=d(V*ue-q),{isValid:yt,value:wt}=u(Me,Le);if(!yt)throw new Error("Point.fromHex: invalid y coordinate");let lt=(wt&nr)===nr,Tt=(de&128)!==0;if(!U&&wt===Kr&&Tt)throw new Error("Point.fromHex: x=0 and x_0=1");return Tt!==lt&&(wt=d(-wt)),v.fromAffine({x:wt,y:ae})}static fromPrivateKey(A){return N(A).point}toRawBytes(){let{x:A,y:U}=this.toAffine(),V=Tn(U,t.BYTES);return V[V.length-1]|=A&nr?128:0,V}toHex(){return In(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,nr,d(e.Gx*e.Gy)),v.ZERO=new v(Kr,nr,nr,Kr);let{BASE:I,ZERO:S}=v,R=hl(v,a*8);function T(C){return De(C,n)}function P(C){return T(Vr(C))}function N(C){let A=a;C=Fe("private key",C,A);let U=Fe("hashed private key",s(C),2*A),V=h(U.slice(0,A)),q=U.slice(A,2*A),se=P(V),ie=I.multiply(se),de=ie.toRawBytes();return{head:V,prefix:q,scalar:se,point:ie,pointBytes:de}}function B(C){return N(C).pointBytes}function k(C=new Uint8Array,...A){let U=kn(...A);return P(s(f(U,Fe("context",C),!!o)))}function X(C,A,U={}){C=Fe("message",C),o&&(C=o(C));let{prefix:V,scalar:q,pointBytes:se}=N(A),ie=k(U.context,V,C),de=I.multiply(ie).toRawBytes(),ae=k(U.context,de,se,C),ue=T(ie+ae*q);b(ue);let Me=kn(de,Tn(ue,t.BYTES));return Fe("result",Me,a*2)}let D=TR;function L(C,A,U,V=D){let{context:q,zip215:se}=V,ie=t.BYTES;C=Fe("signature",C,2*ie),A=Fe("message",A),o&&(A=o(A));let de=Vr(C.slice(ie,2*ie)),ae,ue,Me;try{ae=v.fromHex(U,se),ue=v.fromHex(C.slice(0,ie),se),Me=I.multiplyUnsafe(de)}catch{return!1}if(!se&&ae.isSmallOrder())return!1;let Le=k(q,ue.toRawBytes(),ae.toRawBytes(),A);return ue.add(ae.multiplyUnsafe(Le)).subtract(Me).clearCofactor().equals(v.ZERO)}return I._setWindowSize(8),{CURVE:e,getPublicKey:B,sign:X,verify:L,ExtendedPoint:v,utils:{getExtendedPublicKey:N,randomPrivateKey:()=>i(t.BYTES),precompute(C=8,A=v.BASE){return A._setWindowSize(C),A.multiply(BigInt(3)),A}}}}var Ra=BigInt(0),zh=BigInt(1);function CR(r){return Rr(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function I8(r){let e=CR(r),{P:t}=e,n=E=>De(E,t),o=e.montgomeryBits,s=Math.ceil(o/8),i=e.nByteLength,a=e.adjustScalarBytes||(E=>E),c=e.powPminus2||(E=>$h(E,t-BigInt(2),t));function l(E,x,v){let I=n(E*(x-v));return x=n(x-I),v=n(v+I),[x,v]}function d(E){if(typeof E=="bigint"&&Ra<=E&&E<t)return E;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let u=(e.a-BigInt(2))/BigInt(4);function h(E,x){let v=d(E),I=d(x),S=v,R=zh,T=Ra,P=v,N=zh,B=Ra,k;for(let D=BigInt(o-1);D>=Ra;D--){let L=I>>D&zh;B^=L,k=l(B,R,P),R=k[0],P=k[1],k=l(B,T,N),T=k[0],N=k[1],B=L;let $=R+T,C=n($*$),A=R-T,U=n(A*A),V=C-U,q=P+N,se=P-N,ie=n(se*$),de=n(q*A),ae=ie+de,ue=ie-de;P=n(ae*ae),N=n(S*n(ue*ue)),R=n(C*U),T=n(V*(C+n(u*V)))}k=l(B,R,P),R=k[0],P=k[1],k=l(B,T,N),T=k[0],N=k[1];let X=c(T);return n(R*X)}function f(E){return Tn(n(E),s)}function p(E){let x=Fe("u coordinate",E,s);return i===32&&(x[31]&=127),Vr(x)}function m(E){let x=Fe("scalar",E),v=x.length;if(v!==s&&v!==i)throw new Error(`Expected ${s} or ${i} bytes, got ${v}`);return Vr(a(x))}function y(E,x){let v=p(x),I=m(E),S=h(v,I);if(S===Ra)throw new Error("Invalid private or public key received");return f(S)}let w=f(e.Gu);function b(E){return y(E,w)}return{scalarMult:y,scalarMultBase:b,getSharedSecret:(E,x)=>y(E,x),getPublicKey:E=>b(E),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:w}}var Sa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),D8=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),KB=BigInt(0),NR=BigInt(1),Yh=BigInt(2),LR=BigInt(5),T8=BigInt(10),PR=BigInt(20),OR=BigInt(40),k8=BigInt(80);function C8(r){let e=Sa,n=r*r%e*r%e,o=Ve(n,Yh,e)*n%e,s=Ve(o,NR,e)*r%e,i=Ve(s,LR,e)*s%e,a=Ve(i,T8,e)*i%e,c=Ve(a,PR,e)*a%e,l=Ve(c,OR,e)*c%e,d=Ve(l,k8,e)*l%e,u=Ve(d,k8,e)*l%e,h=Ve(u,T8,e)*i%e;return{pow_p_5_8:Ve(h,Yh,e)*r%e,b2:n}}function N8(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function BR(r,e){let t=Sa,n=De(e*e*e,t),o=De(n*n*e,t),s=C8(r*o).pow_p_5_8,i=De(r*n*s,t),a=De(e*i*i,t),c=i,l=De(i*D8,t),d=a===r,u=a===De(-r,t),h=a===De(-r*D8,t);return d&&(i=c),(u||h)&&(i=l),R8(i,t)&&(i=De(-i,t)),{isValid:d||u,value:i}}var Cn=fl(Sa,void 0,!0),Xh={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Cn,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:uo,randomBytes:ss,adjustScalarBytes:N8,uvRatio:BR},ei=ml(Xh);function L8(r,e,t){if(e.length>255)throw new Error("Context is too big");return sl(Oh("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var $B=ml({...Xh,domain:L8}),HB=ml({...Xh,domain:L8,prehash:uo}),_a=I8({P:Sa,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let e=Sa,{pow_p_5_8:t,b2:n}=C8(r);return De(Ve(t,BigInt(3),e)*n,e)},adjustScalarBytes:N8,randomBytes:ss});var MR=(Cn.ORDER+BigInt(3))/BigInt(8),qB=Cn.pow(Yh,MR),GB=Cn.sqrt(Cn.neg(Cn.ONE)),WB=(Cn.ORDER-BigInt(5))/BigInt(8),zB=BigInt(486662);var YB=S8(Cn,Cn.neg(BigInt(486664)));var XB=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),QB=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),jB=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),ZB=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var JB=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ti=32,Nn=64,gl=32;function P8(){let r=ei.utils.randomPrivateKey(),e=ei.getPublicKey(r);return{privateKey:U8(r,e),publicKey:e}}function O8(r){if(r.length!==gl)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=r,t=ei.getPublicKey(e);return{privateKey:U8(e,t),publicKey:t}}function B8(r,e){let t=r.subarray(0,gl);return ei.sign(e instanceof Uint8Array?e:e.subarray(),t)}function M8(r,e,t){return ei.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function U8(r,e){let t=new Uint8Array(Nn);for(let n=0;n<gl;n++)t[n]=r[n],t[gl+n]=e[n];return t}var Qh={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function yl(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=qe.get();t*=8;async function c(u,h){let f=a.getRandomValues(new Uint8Array(s)),p=a.getRandomValues(new Uint8Array(n)),m={name:e,iv:p};typeof h=="string"&&(h=M(h));let y;if(h.length===0){y=await a.subtle.importKey("jwk",Qh,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:f,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",Qh,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:f,iterations:i,hash:{name:o}},E=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,E,{name:e,length:t},!0,["encrypt"])}let w=await a.subtle.encrypt(m,y,u);return ve([f,m.iv,new Uint8Array(w)])}async function l(u,h){let f=u.subarray(0,s),p=u.subarray(s,s+n),m=u.subarray(s+n),y={name:e,iv:p};typeof h=="string"&&(h=M(h));let w;if(h.length===0)try{let E={name:"PBKDF2",salt:f,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(E,x,{name:e,length:t},!0,["decrypt"])}catch{w=await a.subtle.importKey("jwk",Qh,{name:"AES-GCM"},!0,["decrypt"])}else{let E={name:"PBKDF2",salt:f,iterations:i,hash:{name:o}},x=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);w=await a.subtle.deriveKey(E,x,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(y,w,m);return new Uint8Array(b)}return{encrypt:c,decrypt:l}}async function ri(r,e){let n=await yl().encrypt(r,e);return st.encode(n)}var ni={};pe(ni,{KeyType:()=>Ke,PrivateKey:()=>Hr,PublicKey:()=>$r});var Ke;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(Ke||(Ke={}));var jh;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(jh||(jh={}));(function(r){r.codec=()=>He(jh)})(Ke||(Ke={}));var $r;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ke.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=Ke.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})($r||($r={}));var Hr;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ke.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.Type=Ke.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(Hr||(Hr={}));var cs=class{_key;constructor(e){this._key=oi(e,ti)}verify(e,t){return M8(this._key,t,e)}marshal(){return this._key}get bytes(){return $r.encode({Type:Ke.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}},Ln=class{_key;_publicKey;constructor(e,t){this._key=oi(e,Nn),this._publicKey=oi(t,ti)}sign(e){return B8(this._key,e)}get public(){return new cs(this._publicKey)}marshal(){return this._key}get bytes(){return Hr.encode({Type:Ke.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}async hash(){let e=Ne.digest(this.bytes),t;return vr(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=Wt.digest(this.public.bytes);return Ye.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return ri(this.bytes,e);throw new g(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function FR(r){if(r.length>Nn){r=oi(r,Nn+ti);let n=r.subarray(0,Nn),o=r.subarray(Nn,r.length);return new Ln(n,o)}r=oi(r,Nn);let e=r.subarray(0,Nn),t=r.subarray(ti);return new Ln(e,t)}function VR(r){return r=oi(r,ti),new cs(r)}async function KR(){let{privateKey:r,publicKey:e}=P8();return new Ln(r,e)}async function Zh(r){let{privateKey:e,publicKey:t}=O8(r);return new Ln(e,t)}function oi(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new g(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}function O(r,e="utf8"){let t=jc[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var V8={"P-256":256,"P-384":384,"P-521":521},$R=Object.keys(V8),e0=$R.join(" / ");async function K8(r){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new g(`Unknown curve: ${r}. Must be ${e0}`,"ERR_INVALID_CURVE");let e=await qe.get().subtle.generateKey({name:"ECDH",namedCurve:r},!0,["deriveBits"]),t=async(s,i)=>{let a;i!=null?a=await qe.get().subtle.importKey("jwk",qR(r,i),{name:"ECDH",namedCurve:r},!1,["deriveBits"]):a=e.privateKey;let c=await qe.get().subtle.importKey("jwk",H8(r,s),{name:"ECDH",namedCurve:r},!1,[]),l=await qe.get().subtle.deriveBits({name:"ECDH",namedCurve:r,public:c},a,V8[r]);return new Uint8Array(l,0,l.byteLength)},n=await qe.get().subtle.exportKey("jwk",e.publicKey);return{key:HR(n),genSharedKey:t}}var $8={"P-256":32,"P-384":48,"P-521":66};function HR(r){if(r.crv==null||r.x==null||r.y==null)throw new g("JWK was missing components","ERR_INVALID_PARAMETERS");if(r.crv!=="P-256"&&r.crv!=="P-384"&&r.crv!=="P-521")throw new g(`Unknown curve: ${r.crv}. Must be ${e0}`,"ERR_INVALID_CURVE");let e=$8[r.crv];return ve([Uint8Array.from([4]),Ph(r.x,e),Ph(r.y,e)],1+e*2)}function H8(r,e){if(r!=="P-256"&&r!=="P-384"&&r!=="P-521")throw new g(`Unknown curve: ${r}. Must be ${e0}`,"ERR_INVALID_CURVE");let t=$8[r];if(!Z(e.subarray(0,1),Uint8Array.from([4])))throw new g("Cannot unmarshal public key - invalid key format","ERR_INVALID_KEY_FORMAT");return{kty:"EC",crv:r,x:O(e.subarray(1,t+1),"base64url"),y:O(e.subarray(1+t),"base64url"),ext:!0}}var qR=(r,e)=>({...H8(r,e.public),d:O(e.private,"base64url")});var q8=K8;async function G8(r,e){let t=st.decode(r);return yl().decrypt(t,e)}var W8={"AES-128":{ivSize:16,keySize:16},"AES-256":{ivSize:16,keySize:32},Blowfish:{ivSize:8,keySize:32}};async function z8(r,e,t){let n=W8[r];if(n==null){let b=Object.keys(W8).join(" / ");throw new g(`unknown cipher type '${r}'. Must be ${b}`,"ERR_INVALID_CIPHER_TYPE")}if(e==null)throw new g("missing hash type","ERR_MISSING_HASH_TYPE");let o=n.keySize,s=n.ivSize,i=20,a=M("key expansion"),c=2*(s+o+i),l=await f8(e,t),d=await l.digest(a),u=[],h=0;for(;h<c;){let b=await l.digest(ve([d,a])),E=b.length;h+E>c&&(E=c-h),u.push(b),h+=E,d=await l.digest(d)}let f=c/2,p=ve(u),m=p.subarray(0,f),y=p.subarray(f,c),w=b=>({iv:b.subarray(0,s),cipherKey:b.subarray(s,s+o),macKey:b.subarray(s+o)});return{k1:w(m),k2:w(y)}}var d0={};pe(d0,{MAX_RSA_KEY_SIZE:()=>ds,RsaPrivateKey:()=>Eo,RsaPublicKey:()=>us,fromJwk:()=>pS,generateKeyPair:()=>mS,unmarshalRsaPrivateKey:()=>l0,unmarshalRsaPublicKey:()=>hS});function pt(r){if(isNaN(r)||r<=0)throw new g("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return ss(r)}var wo={};pe(wo,{exportToPem:()=>lS,importFromPem:()=>c0,jwkToPkcs1:()=>sS,jwkToPkix:()=>aS,pkcs1ToJwk:()=>oS,pkixToJwk:()=>iS});var wl=class extends js{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ns(e);let n=Fr(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Qs(this),this.iHash.update(e),this}digestInto(e){Qs(this),Xs(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},po=(r,e,t)=>new wl(r,e).update(t).digest();po.create=(r,e)=>new wl(r,e);function Y8(r,e,t,n){ns(r);let o=m8({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(io(s),io(i),io(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Fr(e),l=Fr(t),d=new Uint8Array(i),u=po.create(r,c),h=u._cloneInto().update(l);return{c:s,dkLen:i,asyncTick:a,DK:d,PRF:u,PRFSalt:h}}function X8(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}function Q8(r,e,t,n){let{c:o,dkLen:s,DK:i,PRF:a,PRFSalt:c}=Y8(r,e,t,n),l,d=new Uint8Array(4),u=os(d),h=new Uint8Array(a.outputLen);for(let f=1,p=0;p<s;f++,p+=a.outputLen){let m=i.subarray(p,p+a.outputLen);u.setInt32(0,f,!1),(l=c._cloneInto(l)).update(d).digestInto(h),m.set(h.subarray(0,m.length));for(let y=1;y<o;y++){a._cloneInto(l).update(h).digestInto(h);for(let w=0;w<m.length;w++)m[w]^=h[w]}}return X8(a,c,i,l,h)}async function t0(r,e,t,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=Y8(r,e,t,n),d,u=new Uint8Array(4),h=os(u),f=new Uint8Array(c.outputLen);for(let p=1,m=0;m<s;p++,m+=c.outputLen){let y=a.subarray(m,m+c.outputLen);h.setInt32(0,p,!1),(d=l._cloneInto(d)).update(u).digestInto(f),y.set(f.subarray(0,y.length)),await p8(o-1,i,()=>{c._cloneInto(d).update(f).digestInto(f);for(let w=0;w<y.length;w++)y[w]^=f[w]})}return X8(c,l,a,d,f)}var we=Qe(j8());function ls(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 mo(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let d=a-1;d>=0;d--){let u=Math.pow(2,d*e);l[s-d-1]=Math.floor(o/u),o-=l[s-d-1]*u}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function xl(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function n0(){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=ls(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,ls(s,8)-n}function Z8(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=mo(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=mo(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function J8(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 zt(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var HM=Math.log(2);function vl(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function o0(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Un(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 Ia=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return o0(this.items)}},Aa=[new Uint8Array([1])],em="0123456789";var ai="",Gr=new ArrayBuffer(0),s0=new Uint8Array(0),Da="EndOfContent",rm="OCTET STRING",nm="BIT STRING";function Fn(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?we.BufferSourceConverter.toUint8Array(s.valueHex):s0}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Un(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Gr)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:we.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var On=class{constructor({blockLength:e=0,error:t=ai,warnings:n=[],valueBeforeDecode:o=s0}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=we.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:we.Convert.ToHex(this.valueBeforeDecodeView)}}};On.NAME="baseBlock";var Lt=class extends On{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Lt.NAME="valueBlock";var Rl=class extends Fn(On){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?we.BufferSourceConverter.toUint8Array(e.valueHex):s0,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",Gr}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=mo(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=we.BufferSourceConverter.toUint8Array(e);if(!Un(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),d=255;for(;s[c]&128;){if(l[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===d){d+=255;let h=new Uint8Array(d);for(let f=0;f<l.length;f++)h[f]=l[f];l=this.valueHexView=new Uint8Array(d)}}this.blockLength=c+1,l[c-1]=s[c]&127;let u=new Uint8Array(c);for(let h=0;h<c;h++)u[h]=l[h];l=this.valueHexView=new Uint8Array(c),l.set(u),this.blockLength<=9?this.tagNumber=ls(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}}};Rl.NAME="identificationBlock";var Sl=class extends On{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=we.BufferSourceConverter.toUint8Array(e);if(!Un(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=ls(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=mo(this.length,8);if(o.byteLength>127)return this.error="Too big length",Gr;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Sl.NAME="lengthBlock";var W={},Et=class extends On{constructor({name:e=ai,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Rl(o),this.lenBlock=new Sl(o),this.valueBlock=s?new s(o):new Lt(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new Ia;t||om(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?Gr: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():we.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${we.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return J8(t,n)}};Et.NAME="BaseBlock";function om(r){if(r instanceof W.Constructed)for(let e of r.valueBlock.value)om(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var _l=class extends Et{constructor({value:e=ai,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=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}'`}};_l.NAME="BaseStringBlock";var Al=class extends Fn(Lt){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};Al.NAME="PrimitiveValueBlock";var sm,Il=class extends Et{constructor(e={}){super(e,Al),this.idBlock.isConstructed=!1}};sm=Il;W.Primitive=sm;Il.NAME="PRIMITIVE";function JR(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 iu(r,e=0,t=r.length){let n=e,o=new Et({},Lt),s=new On;if(!Un(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Et;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=W.EndOfContent;break;case 1:c=W.Boolean;break;case 2:c=W.Integer;break;case 3:c=W.BitString;break;case 4:c=W.OctetString;break;case 5:c=W.Null;break;case 6:c=W.ObjectIdentifier;break;case 10:c=W.Enumerated;break;case 12:c=W.Utf8String;break;case 13:c=W.RelativeObjectIdentifier;break;case 14:c=W.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=W.Sequence;break;case 17:c=W.Set;break;case 18:c=W.NumericString;break;case 19:c=W.PrintableString;break;case 20:c=W.TeletexString;break;case 21:c=W.VideotexString;break;case 22:c=W.IA5String;break;case 23:c=W.UTCTime;break;case 24:c=W.GeneralizedTime;break;case 25:c=W.GraphicString;break;case 26:c=W.VisibleString;break;case 27:c=W.GeneralString;break;case 28:c=W.UniversalString;break;case 29:c=W.CharacterString;break;case 30:c=W.BmpString;break;case 31:c=W.DATE;break;case 32:c=W.TimeOfDay;break;case 33:c=W.DateTime;break;case 34:c=W.Duration;break;default:{let l=o.idBlock.isConstructed?new W.Constructed:new W.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?W.Constructed:W.Primitive}return o=JR(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function ci(r){if(!r.byteLength){let e=new Et({},Lt);return e.error="Input buffer has zero length",{offset:-1,result:e}}return iu(we.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function eS(r,e){return r?1:e}var un=class extends Lt{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=we.BufferSourceConverter.toUint8Array(e);if(!Un(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;eS(this.isIndefiniteForm,n)>0;){let i=iu(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===Da)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Da?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new Ia;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?Gr:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};un.NAME="ConstructedValueBlock";var im,go=class extends Et{constructor(e={}){super(e,un),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
|
18
18
|
`).map(o=>` ${o}`).join(`
|
|
19
19
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
|
20
20
|
${e.join(`
|
|
21
|
-
`)}`:`${t} :`}};i8=go;W.Constructed=i8;go.NAME="CONSTRUCTED";var Dl=class extends Lt{fromBER(e,t,n){return t}toBER(e){return Gr}};Dl.override="EndOfContentValueBlock";var a8,Tl=class extends Et{constructor(e={}){super(e,Dl),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};a8=Tl;W.EndOfContent=a8;Tl.NAME=Da;var c8,yo=class extends Et{constructor(e={}){super(e,Lt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};c8=yo;W.Null=c8;yo.NAME="NULL";var kl=class extends Fn(Lt){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=we.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=we.BufferSourceConverter.toUint8Array(e);return Un(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,n0.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};kl.NAME="BooleanValueBlock";var l8,Cl=class extends Et{constructor(e={}){super(e,kl),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};l8=Cl;W.Boolean=l8;Cl.NAME="BOOLEAN";var Nl=class extends Fn(un){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=un.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Da){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==r8)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?un.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Nl.NAME="OctetStringValueBlock";var u8,Bn=class r extends Et{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Nl),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=iu(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?go.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${we.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return we.BufferSourceConverter.concat(e)}};u8=Bn;W.OctetString=u8;Bn.NAME=r8;var Ll=class extends Fn(un){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=un.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Da){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==n8)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let s=we.BufferSourceConverter.toUint8Array(e);if(!Un(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=iu(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return un.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Gr;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Ll.NAME="BitStringValueBlock";var d8,ii=class extends Et{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ll),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return go.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};d8=ii;W.BitString=d8;ii.NAME=n8;var f8;function tS(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,d=c<i?i:c,u=0;for(let h=d;h>=0;h--,u++){switch(!0){case u<a.length:l=s[i-u]+a[c-u]+t[0];break;default:l=s[i-u]+t[0]}switch(t[0]=l/10,!0){case u>=s.length:s=xl(new Uint8Array([l%10]),s);break;default:s[i-u]=l%10}}return t[0]>0&&(s=xl(t,s)),s}function t8(r){if(r>=Aa.length)for(let e=Aa.length;e<=r;e++){let t=new Uint8Array([0]),n=Aa[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=xl(t,n)),Aa.push(n)}return Aa[r]}function rS(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,d=0;for(let u=c;u>=0;u--,d++)switch(l=s[i-d]-a[c-d]-t,!0){case l<0:t=1,s[i-d]=l+10;break;default:t=0,s[i-d]=l}if(t>0)for(let u=i-c+1;u>=0;u--,d++)if(l=s[i-d]-t,l<0)t=1,s[i-d]=l+10;else{t=0,s[i-d]=l;break}return s.slice()}var Ta=class extends Fn(Lt){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=n0.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Zm(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=rS(t8(n),t),i="-";break;default:t=tS(t,t8(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=e8.charAt(t[c]));return a===!1&&(i+=e8.charAt(0)),i}};f8=Ta;Ta.NAME="IntegerValueBlock";Object.defineProperty(f8.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var h8,at=class r extends Et{constructor(e={}){super(e,Ta),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return vl(),BigInt(this.valueBlock.toString())}static fromBigInt(e){vl();let t=BigInt(e),n=new Ia,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(we.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${we.Convert.ToHex(a)}`)+t,d=we.BufferSourceConverter.toUint8Array(we.Convert.FromHex(l.toString(16)));d[0]|=128,n.write(d)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};h8=at;W.Integer=h8;at.NAME="INTEGER";var p8,Pl=class extends at{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};p8=Pl;W.Enumerated=p8;Pl.NAME="ENUMERATED";var ka=class extends Fn(Lt){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=we.BufferSourceConverter.toUint8Array(e);if(!Un(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ls(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){vl();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=mo(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Gr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=we.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};ka.NAME="sidBlock";var Ol=class extends Lt{constructor({value:e=ai,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new ka;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,Gr;t.push(o)}return o0(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new ka;if(o>Number.MAX_SAFE_INTEGER){vl();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Ol.NAME="ObjectIdentifierValueBlock";var m8,qr=class extends Et{constructor(e={}){super(e,Ol),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};m8=qr;W.ObjectIdentifier=m8;qr.NAME="OBJECT IDENTIFIER";var Ca=class extends Fn(On){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=we.BufferSourceConverter.toUint8Array(e);if(!Un(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ls(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=mo(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Gr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=we.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Ca.NAME="relativeSidBlock";var Bl=class extends Lt{constructor({value:e=ai,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Ca;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,Gr;n.push(s)}return o0(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Ca;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Bl.NAME="RelativeObjectIdentifierValueBlock";var g8,Ml=class extends Et{constructor(e={}){super(e,Bl),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};g8=Ml;W.RelativeObjectIdentifier=g8;Ml.NAME="RelativeObjectIdentifier";var y8,mt=class extends go{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};y8=mt;W.Sequence=y8;mt.NAME="SEQUENCE";var w8,Ul=class extends go{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};w8=Ul;W.Set=w8;Ul.NAME="SET";var Fl=class extends Fn(Lt){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ai}toJSON(){return{...super.toJSON(),value:this.value}}};Fl.NAME="StringValueBlock";var Vl=class extends Fl{};Vl.NAME="SimpleStringValueBlock";var Ut=class extends _l{constructor({...e}={}){super(e,Vl)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,we.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Ut.NAME="SIMPLE STRING";var Kl=class extends Ut{fromBuffer(e){this.valueBlock.valueHexView=we.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=we.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=we.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(we.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Kl.NAME="Utf8StringValueBlock";var E8,Mn=class extends Kl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};E8=Mn;W.Utf8String=E8;Mn.NAME="UTF8String";var $l=class extends Ut{fromBuffer(e){this.valueBlock.value=we.Convert.ToUtf16String(e),this.valueBlock.valueHexView=we.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(we.Convert.FromUtf16String(e))}};$l.NAME="BmpStringValueBlock";var b8,Hl=class extends $l{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};b8=Hl;W.BmpString=b8;Hl.NAME="BMPString";var ql=class extends Ut{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=mo(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};ql.NAME="UniversalStringValueBlock";var x8,Gl=class extends ql{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};x8=Gl;W.UniversalString=x8;Gl.NAME="UniversalString";var v8,Wl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};v8=Wl;W.NumericString=v8;Wl.NAME="NumericString";var R8,zl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};R8=zl;W.PrintableString=R8;zl.NAME="PrintableString";var S8,Yl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};S8=Yl;W.TeletexString=S8;Yl.NAME="TeletexString";var _8,Xl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};_8=Xl;W.VideotexString=_8;Xl.NAME="VideotexString";var A8,Ql=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};A8=Ql;W.IA5String=A8;Ql.NAME="IA5String";var I8,jl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};I8=jl;W.GraphicString=I8;jl.NAME="GraphicString";var D8,Na=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};D8=Na;W.VisibleString=D8;Na.NAME="VisibleString";var T8,Zl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};T8=Zl;W.GeneralString=T8;Zl.NAME="GeneralString";var k8,Jl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};k8=Jl;W.CharacterString=k8;Jl.NAME="CharacterString";var C8,La=class extends Na{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,we.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=zt(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=zt(this.month,2),t[2]=zt(this.day,2),t[3]=zt(this.hour,2),t[4]=zt(this.minute,2),t[5]=zt(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};C8=La;W.UTCTime=C8;La.NAME="UTCTime";var N8,eu=class extends La{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let u=new Number(e[e.length-1]);if(isNaN(u.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let u=1,h=n.indexOf("+"),f="";if(h===-1&&(h=n.indexOf("-"),u=-1),h!==-1){if(f=n.substring(h+1),n=n.substring(0,h),f.length!==2&&f.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(f.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=u*p,f.length===4){if(p=parseInt(f.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=u*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let u=new Number(`0${n.substring(l)}`);if(isNaN(u.valueOf()))throw new Error("Wrong input string for conversion");s=u.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=60*s;this.minute=Math.floor(u),u=60*(u-this.minute),this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=60*s;this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=1e3*s;this.millisecond=Math.floor(u)}break;default:throw new Error("Wrong input string for conversion")}let d=i.exec(o);if(d===null)throw new Error("Wrong input string for conversion");for(let u=1;u<d.length;u++)switch(u){case 1:this.year=parseInt(d[u],10);break;case 2:this.month=parseInt(d[u],10);break;case 3:this.day=parseInt(d[u],10);break;case 4:this.hour=parseInt(d[u],10)+a;break;case 5:this.minute=parseInt(d[u],10)+c;break;case 6:this.second=parseInt(d[u],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let u=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=u.getUTCFullYear(),this.month=u.getUTCMonth(),this.day=u.getUTCDay(),this.hour=u.getUTCHours(),this.minute=u.getUTCMinutes(),this.second=u.getUTCSeconds(),this.millisecond=u.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(zt(this.year,4)),t.push(zt(this.month,2)),t.push(zt(this.day,2)),t.push(zt(this.hour,2)),t.push(zt(this.minute,2)),t.push(zt(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(zt(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};N8=eu;W.GeneralizedTime=N8;eu.NAME="GeneralizedTime";var L8,tu=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};L8=tu;W.DATE=L8;tu.NAME="DATE";var P8,ru=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};P8=ru;W.TimeOfDay=P8;ru.NAME="TimeOfDay";var O8,nu=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};O8=nu;W.DateTime=O8;nu.NAME="DateTime";var B8,ou=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};B8=ou;W.Duration=B8;ou.NAME="Duration";var M8,su=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};M8=su;W.TIME=M8;su.NAME="TIME";function oS(r){let{result:e}=ci(r),t=e.valueBlock.value;return{n:O(dn(t[1].toBigInt()),"base64url"),e:O(dn(t[2].toBigInt()),"base64url"),d:O(dn(t[3].toBigInt()),"base64url"),p:O(dn(t[4].toBigInt()),"base64url"),q:O(dn(t[5].toBigInt()),"base64url"),dp:O(dn(t[6].toBigInt()),"base64url"),dq:O(dn(t[7].toBigInt()),"base64url"),qi:O(dn(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function sS(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new g("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new mt({value:[new at({value:0}),at.fromBigInt(fn(M(r.n,"base64url"))),at.fromBigInt(fn(M(r.e,"base64url"))),at.fromBigInt(fn(M(r.d,"base64url"))),at.fromBigInt(fn(M(r.p,"base64url"))),at.fromBigInt(fn(M(r.q,"base64url"))),at.fromBigInt(fn(M(r.dp,"base64url"))),at.fromBigInt(fn(M(r.dq,"base64url"))),at.fromBigInt(fn(M(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function iS(r){let{result:e}=ci(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:O(dn(t[0].toBigInt()),"base64url"),e:O(dn(t[1].toBigInt()),"base64url")}}function aS(r){if(r.n==null||r.e==null)throw new g("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new mt({value:[new mt({value:[new qr({value:"1.2.840.113549.1.1.1"}),new yo]}),new ii({valueHex:new mt({value:[at.fromBigInt(fn(M(r.n,"base64url"))),at.fromBigInt(fn(M(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function dn(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function fn(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var cS=16,i0=32,a0=1e4;async function lS(r,e){let t=qe.get(),o=new mt({value:[new at({value:0}),new mt({value:[new qr({value:"1.2.840.113549.1.1.1"}),new yo]}),new Bn({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=pt(cS),a=await t0(uo,e,i,{c:a0,dkLen:i0}),c=pt(16),l=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),d=await t.subtle.encrypt({name:"AES-CBC",iv:c},l,s),u=new mt({value:[new Bn({valueHex:i}),new at({value:a0}),new at({value:i0}),new mt({value:[new qr({value:"1.2.840.113549.2.11"}),new yo]})]}),h=new mt({value:[new qr({value:"1.2.840.113549.1.5.13"}),new mt({value:[new mt({value:[new qr({value:"1.2.840.113549.1.5.12"}),u]}),new mt({value:[new qr({value:"2.16.840.1.101.3.4.1.42"}),new Bn({valueHex:c})]})]})]}),p=new mt({value:[h,new Bn({valueHex:d})]}).toBER(),m=new Uint8Array(p,0,p.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...O(m,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
|
22
|
-
`)}async function c0(r,e){let t=qe.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=M(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=ci(o),{iv:i,salt:a,iterations:c,keySize:l,cipherText:d}=uS(s),u=await t0(uo,e,a,{c,dkLen:l}),h=await t.subtle.importKey("raw",u,"AES-CBC",!1,["decrypt"]),f=Pa(await t.subtle.decrypt({name:"AES-CBC",iv:i},h,d)),{result:p}=ci(f);n=U8(p)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=M(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=ci(o);n=U8(s)}else throw new g("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return l0(n)}function uS(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new g("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new g("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Pa(s.valueBlock.value[0].getValue()),a=a0,c=i0;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new g("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let l=e.valueBlock.value[1].valueBlock.value[1],d=l.valueBlock.value[0].toString();if(d!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(d!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(d!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(d!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(d!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new g("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let u=Pa(l.valueBlock.value[1].getValue());return{cipherText:Pa(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:u}}function U8(r){return Pa(r.valueBlock.value[2].getValue())}function Pa(r){return new Uint8Array(r,0,r.byteLength)}async function F8(r){let e=await qe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await $8(e);return{privateKey:t[0],publicKey:t[1]}}async function u0(r){let t=[await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await dS(r)],n=await $8({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function V8(r,e){let t=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await qe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function K8(r,e,t){let n=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return qe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function $8(r){if(r.privateKey==null||r.publicKey==null)throw new g("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([qe.get().subtle.exportKey("jwk",r.privateKey),qe.get().subtle.exportKey("jwk",r.publicKey)])}async function dS(r){return qe.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function au(r){if(r.kty!=="RSA")throw new g("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new g("invalid key modulus","ERR_INVALID_KEY_MODULUS");return M(r.n,"base64url").length*8}var ds=8192,us=class{_key;constructor(e){this._key=e}verify(e,t){return K8(this._key,t,e)}marshal(){return wo.jwkToPkix(this._key)}get bytes(){return $r.encode({Type:Ke.RSA,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}},Eo=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return pt(16)}sign(e){return V8(this._key,e)}get public(){if(this._publicKey==null)throw new g("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new us(this._publicKey)}marshal(){return wo.jwkToPkcs1(this._key)}get bytes(){return Hr.encode({Type:Ke.RSA,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return O(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return wo.exportToPem(this,e);if(t==="libp2p-key")return ri(this.bytes,e);throw new g(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function l0(r){let e=wo.pkcs1ToJwk(r);if(au(e)>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await u0(e);return new Eo(t.privateKey,t.publicKey)}function hS(r){let e=wo.pkixToJwk(r);if(au(e)>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new us(e)}async function pS(r){if(au(r)>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await u0(r);return new Eo(e.privateKey,e.publicKey)}async function mS(r){if(r>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await F8(r);return new Eo(e.privateKey,e.publicKey)}var g0={};pe(g0,{Secp256k1PrivateKey:()=>ps,Secp256k1PublicKey:()=>hs,generateKeyPair:()=>DS,unmarshalSecp256k1PrivateKey:()=>AS,unmarshalSecp256k1PublicKey:()=>IS});var gS=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),bo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xo=new Uint32Array(64),f0=class extends ao{constructor(){super(64,32,8,!1),this.A=bo[0]|0,this.B=bo[1]|0,this.C=bo[2]|0,this.D=bo[3]|0,this.E=bo[4]|0,this.F=bo[5]|0,this.G=bo[6]|0,this.H=bo[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)xo[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let h=xo[u-15],f=xo[u-2],p=Ur(h,7)^Ur(h,18)^h>>>3,m=Ur(f,17)^Ur(f,19)^f>>>10;xo[u]=m+xo[u-7]+p+xo[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){let h=Ur(a,6)^Ur(a,11)^Ur(a,25),f=d+h+il(a,c,l)+gS[u]+xo[u]|0,m=(Ur(n,2)^Ur(n,13)^Ur(n,22))+al(n,o,s)|0;d=l,l=c,c=a,a=i+f|0,i=s,s=o,o=n,n=f+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,l,d)}roundClean(){xo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var vo=Zs(()=>new f0);function yS(r){let e=va(r);Rr(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:wS,hexToBytes:ES}=ul,fs={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=fs;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:wS(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=fs,t=typeof r=="string"?ES(r):r;Js(t);let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:s}=fs._parseInt(t.subarray(2)),{d:i,l:a}=fs._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{let d=l.toString(16);return d.length&1?`0${d}`:d},n=e(t(r.s)),o=e(t(r.r)),s=n.length/2,i=o.length/2,a=t(s),c=t(i);return`30${t(i+s+4)}02${c}${o}02${a}${n}`}},Vn=BigInt(0),_r=BigInt(1),mU=BigInt(2),H8=BigInt(3),gU=BigInt(4);function bS(r){let e=yS(r),{Fp:t}=e,n=e.toBytes||((p,m,y)=>{let w=m.toAffine();return kn(Uint8Array.from([4]),t.toBytes(w.x),t.toBytes(w.y))}),o=e.fromBytes||(p=>{let m=p.subarray(1),y=t.fromBytes(m.subarray(0,t.BYTES)),w=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:y,y:w}});function s(p){let{a:m,b:y}=e,w=t.sqr(p),b=t.mul(w,p);return t.add(t.add(b,t.mul(p,m)),y)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(p){return typeof p=="bigint"&&Vn<p&&p<e.n}function a(p){if(!i(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:w,n:b}=e;if(m&&typeof p!="bigint"){if(fo(p)&&(p=In(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let E;try{E=typeof p=="bigint"?p:Dn(Fe("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return w&&(E=De(E,b)),a(E),E}let l=new Map;function d(p){if(!(p instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(m,y,w){if(this.px=m,this.py=y,this.pz=w,m==null||!t.isValid(m))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(w==null||!t.isValid(w))throw new Error("z required")}static fromAffine(m){let{x:y,y:w}=m||{};if(!m||!t.isValid(y)||!t.isValid(w))throw new Error("invalid affine point");if(m instanceof u)throw new Error("projective point not allowed");let b=E=>t.eql(E,t.ZERO);return b(y)&&b(w)?u.ZERO:new u(y,w,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=t.invertBatch(m.map(w=>w.pz));return m.map((w,b)=>w.toAffine(y[b])).map(u.fromAffine)}static fromHex(m){let y=u.fromAffine(o(Fe("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return u.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not FE");let w=t.sqr(y),b=s(m);if(!t.eql(w,b))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){d(m);let{px:y,py:w,pz:b}=this,{px:E,py:x,pz:v}=m,I=t.eql(t.mul(y,v),t.mul(E,b)),S=t.eql(t.mul(w,v),t.mul(x,b));return I&&S}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,w=t.mul(y,H8),{px:b,py:E,pz:x}=this,v=t.ZERO,I=t.ZERO,S=t.ZERO,R=t.mul(b,b),T=t.mul(E,E),P=t.mul(x,x),N=t.mul(b,E);return N=t.add(N,N),S=t.mul(b,x),S=t.add(S,S),v=t.mul(m,S),I=t.mul(w,P),I=t.add(v,I),v=t.sub(T,I),I=t.add(T,I),I=t.mul(v,I),v=t.mul(N,v),S=t.mul(w,S),P=t.mul(m,P),N=t.sub(R,P),N=t.mul(m,N),N=t.add(N,S),S=t.add(R,R),R=t.add(S,R),R=t.add(R,P),R=t.mul(R,N),I=t.add(I,R),P=t.mul(E,x),P=t.add(P,P),R=t.mul(P,N),v=t.sub(v,R),S=t.mul(P,T),S=t.add(S,S),S=t.add(S,S),new u(v,I,S)}add(m){d(m);let{px:y,py:w,pz:b}=this,{px:E,py:x,pz:v}=m,I=t.ZERO,S=t.ZERO,R=t.ZERO,T=e.a,P=t.mul(e.b,H8),N=t.mul(y,E),B=t.mul(w,x),k=t.mul(b,v),X=t.add(y,w),D=t.add(E,x);X=t.mul(X,D),D=t.add(N,B),X=t.sub(X,D),D=t.add(y,b);let L=t.add(E,v);return D=t.mul(D,L),L=t.add(N,k),D=t.sub(D,L),L=t.add(w,b),I=t.add(x,v),L=t.mul(L,I),I=t.add(B,k),L=t.sub(L,I),R=t.mul(T,D),I=t.mul(P,k),R=t.add(I,R),I=t.sub(B,R),R=t.add(B,R),S=t.mul(I,R),B=t.add(N,N),B=t.add(B,N),k=t.mul(T,k),D=t.mul(P,D),B=t.add(B,k),k=t.sub(N,k),k=t.mul(T,k),D=t.add(D,k),N=t.mul(B,D),S=t.add(S,N),N=t.mul(L,D),I=t.mul(X,I),I=t.sub(I,N),N=t.mul(X,B),R=t.mul(L,R),R=t.add(R,N),new u(I,S,R)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return f.wNAFCached(this,l,m,y=>{let w=t.invertBatch(y.map(b=>b.pz));return y.map((b,E)=>b.toAffine(w[E])).map(u.fromAffine)})}multiplyUnsafe(m){let y=u.ZERO;if(m===Vn)return y;if(a(m),m===_r)return this;let{endo:w}=e;if(!w)return f.unsafeLadder(this,m);let{k1neg:b,k1:E,k2neg:x,k2:v}=w.splitScalar(m),I=y,S=y,R=this;for(;E>Vn||v>Vn;)E&_r&&(I=I.add(R)),v&_r&&(S=S.add(R)),R=R.double(),E>>=_r,v>>=_r;return b&&(I=I.negate()),x&&(S=S.negate()),S=new u(t.mul(S.px,w.beta),S.py,S.pz),I.add(S)}multiply(m){a(m);let y=m,w,b,{endo:E}=e;if(E){let{k1neg:x,k1:v,k2neg:I,k2:S}=E.splitScalar(y),{p:R,f:T}=this.wNAF(v),{p:P,f:N}=this.wNAF(S);R=f.constTimeNegate(x,R),P=f.constTimeNegate(I,P),P=new u(t.mul(P.px,E.beta),P.py,P.pz),w=R.add(P),b=T.add(N)}else{let{p:x,f:v}=this.wNAF(y);w=x,b=v}return u.normalizeZ([w,b])[0]}multiplyAndAddUnsafe(m,y,w){let b=u.BASE,E=(v,I)=>I===Vn||I===_r||!v.equals(b)?v.multiplyUnsafe(I):v.multiply(I),x=E(this,y).add(E(m,w));return x.is0()?void 0:x}toAffine(m){let{px:y,py:w,pz:b}=this,E=this.is0();m==null&&(m=E?t.ONE:t.inv(b));let x=t.mul(y,m),v=t.mul(w,m),I=t.mul(b,m);if(E)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x,y:v}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===_r)return!0;if(y)return y(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===_r?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return In(this.toRawBytes(m))}}u.BASE=new u(e.Gx,e.Gy,t.ONE),u.ZERO=new u(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,f=hl(u,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function xS(r){let e=va(r);return Rr(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function q8(r){let e=xS(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(D){return Vn<D&&D<t.ORDER}function a(D){return De(D,n)}function c(D){return dl(D,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:d,weierstrassEquation:u,isWithinCurveOrder:h}=bS({...e,toBytes(D,L,$){let C=L.toAffine(),A=t.toBytes(C.x),U=kn;return $?U(Uint8Array.from([L.hasEvenY()?2:3]),A):U(Uint8Array.from([4]),A,t.toBytes(C.y))},fromBytes(D){let L=D.length,$=D[0],C=D.subarray(1);if(L===o&&($===2||$===3)){let A=Dn(C);if(!i(A))throw new Error("Point is not on curve");let U=u(A),V;try{V=t.sqrt(U)}catch(ie){let de=ie instanceof Error?": "+ie.message:"";throw new Error("Point is not on curve"+de)}let q=(V&_r)===_r;return($&1)===1!==q&&(V=t.neg(V)),{x:A,y:V}}else if(L===s&&$===4){let A=t.fromBytes(C.subarray(0,t.BYTES)),U=t.fromBytes(C.subarray(t.BYTES,2*t.BYTES));return{x:A,y:U}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),f=D=>In(ho(D,e.nByteLength));function p(D){let L=n>>_r;return D>L}function m(D){return p(D)?a(-D):D}let y=(D,L,$)=>Dn(D.slice(L,$));class w{constructor(L,$,C){this.r=L,this.s=$,this.recovery=C,this.assertValidity()}static fromCompact(L){let $=e.nByteLength;return L=Fe("compactSignature",L,$*2),new w(y(L,0,$),y(L,$,2*$))}static fromDER(L){let{r:$,s:C}=fs.toSig(Fe("DER",L));return new w($,C)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(L){return new w(this.r,this.s,L)}recoverPublicKey(L){let{r:$,s:C,recovery:A}=this,U=S(Fe("msgHash",L));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let V=A===2||A===3?$+e.n:$;if(V>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let q=A&1?"03":"02",se=l.fromHex(q+f(V)),ie=c(V),de=a(-U*ie),ae=a(C*ie),ue=l.BASE.multiplyAndAddUnsafe(se,de,ae);if(!ue)throw new Error("point at infinify");return ue.assertValidity(),ue}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return is(this.toDERHex())}toDERHex(){return fs.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return is(this.toCompactHex())}toCompactHex(){return f(this.r)+f(this.s)}}let b={isValidPrivateKey(D){try{return d(D),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let D=Gh(e.n);return Am(e.randomBytes(D),e.n)},precompute(D=8,L=l.BASE){return L._setWindowSize(D),L.multiply(BigInt(3)),L}};function E(D,L=!0){return l.fromPrivateKey(D).toRawBytes(L)}function x(D){let L=fo(D),$=typeof D=="string",C=(L||$)&&D.length;return L?C===o||C===s:$?C===2*o||C===2*s:D instanceof l}function v(D,L,$=!0){if(x(D))throw new Error("first arg must be private key");if(!x(L))throw new Error("second arg must be public key");return l.fromHex(L).multiply(d(D)).toRawBytes($)}let I=e.bits2int||function(D){let L=Dn(D),$=D.length*8-e.nBitLength;return $>0?L>>BigInt($):L},S=e.bits2int_modN||function(D){return a(I(D))},R=xa(e.nBitLength);function T(D){if(typeof D!="bigint")throw new Error("bigint expected");if(!(Vn<=D&&D<R))throw new Error(`bigint expected < 2^${e.nBitLength}`);return ho(D,e.nByteLength)}function P(D,L,$=N){if(["recovered","canonical"].some(Le=>Le in $))throw new Error("sign() legacy options not supported");let{hash:C,randomBytes:A}=e,{lowS:U,prehash:V,extraEntropy:q}=$;U==null&&(U=!0),D=Fe("msgHash",D),V&&(D=Fe("prehashed msgHash",C(D)));let se=S(D),ie=d(L),de=[T(ie),T(se)];if(q!=null&&q!==!1){let Le=q===!0?A(t.BYTES):q;de.push(Fe("extraEntropy",Le))}let ae=kn(...de),ue=se;function Me(Le){let yt=I(Le);if(!h(yt))return;let wt=c(yt),lt=l.BASE.multiply(yt).toAffine(),Tt=a(lt.x);if(Tt===Vn)return;let xn=a(wt*a(ue+Tt*ie));if(xn===Vn)return;let Go=(lt.x===Tt?0:2)|Number(lt.y&_r),fa=xn;return U&&p(xn)&&(fa=m(xn),Go^=1),new w(Tt,fa,Go)}return{seed:ae,k2sig:Me}}let N={lowS:e.lowS,prehash:!1},B={lowS:e.lowS,prehash:!1};function k(D,L,$=N){let{seed:C,k2sig:A}=P(D,L,$),U=e;return Vh(U.hash.outputLen,U.nByteLength,U.hmac)(C,A)}l.BASE._setWindowSize(8);function X(D,L,$,C=B){let A=D;if(L=Fe("msgHash",L),$=Fe("publicKey",$),"strict"in C)throw new Error("options.strict was renamed to lowS");let{lowS:U,prehash:V}=C,q,se;try{if(typeof A=="string"||fo(A))try{q=w.fromDER(A)}catch(lt){if(!(lt instanceof fs.Err))throw lt;q=w.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:lt,s:Tt}=A;q=new w(lt,Tt)}else throw new Error("PARSE");se=l.fromHex($)}catch(lt){if(lt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(U&&q.hasHighS())return!1;V&&(L=e.hash(L));let{r:ie,s:de}=q,ae=S(L),ue=c(de),Me=a(ae*ue),Le=a(ie*ue),yt=l.BASE.multiplyAndAddUnsafe(se,Me,Le)?.toAffine();return yt?a(yt.x)===ie:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:v,sign:k,verify:X,ProjectivePoint:l,Signature:w,utils:b}}function vS(r){return{hash:r,hmac:(e,...t)=>po(r,e,sl(...t)),randomBytes:ss}}function G8(r,e){let t=n=>q8({...r,...vS(n)});return Object.freeze({...t(e),create:t})}var Y8=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),W8=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),RS=BigInt(1),h0=BigInt(2),z8=(r,e)=>(r+e/h0)/e;function SS(r){let e=Y8,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,u=Ve(d,t,e)*d%e,h=Ve(u,t,e)*d%e,f=Ve(h,h0,e)*l%e,p=Ve(f,o,e)*f%e,m=Ve(p,s,e)*p%e,y=Ve(m,a,e)*m%e,w=Ve(y,c,e)*y%e,b=Ve(w,a,e)*m%e,E=Ve(b,t,e)*d%e,x=Ve(E,i,e)*p%e,v=Ve(x,n,e)*l%e,I=Ve(v,h0,e);if(!p0.eql(p0.sqr(I),r))throw new Error("Cannot find square root");return I}var p0=fl(Y8,void 0,void 0,{sqrt:SS}),Wr=G8({a:BigInt(0),b:BigInt(7),Fp:p0,n:W8,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=W8,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-RS*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=z8(s*r,e),c=z8(-n*r,e),l=De(r-a*t-c*o,e),d=De(-a*n-c*s,e),u=l>i,h=d>i;if(u&&(l=e-l),h&&(d=e-d),l>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:h,k2:d}}}},vo),_U=BigInt(0);var AU=Wr.ProjectivePoint;function X8(){return Wr.utils.randomPrivateKey()}function Q8(r,e){let t=Ne.digest(e instanceof Uint8Array?e:e.subarray());if(vr(t))return t.then(({digest:n})=>Wr.sign(n,r).toDERRawBytes()).catch(n=>{throw new g(String(n),"ERR_INVALID_INPUT")});try{return Wr.sign(t.digest,r).toDERRawBytes()}catch(n){throw new g(String(n),"ERR_INVALID_INPUT")}}function j8(r,e,t){let n=Ne.digest(t instanceof Uint8Array?t:t.subarray());if(vr(n))return n.then(({digest:o})=>Wr.verify(e,o,r)).catch(o=>{throw new g(String(o),"ERR_INVALID_INPUT")});try{return Wr.verify(e,n.digest,r)}catch(o){throw new g(String(o),"ERR_INVALID_INPUT")}}function Z8(r){return Wr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function J8(r){try{Wr.getPublicKey(r,!0)}catch(e){throw new g(String(e),"ERR_INVALID_PRIVATE_KEY")}}function m0(r){try{Wr.ProjectivePoint.fromHex(r)}catch(e){throw new g(String(e),"ERR_INVALID_PUBLIC_KEY")}}function e6(r){try{return Wr.getPublicKey(r,!0)}catch(e){throw new g(String(e),"ERR_INVALID_PRIVATE_KEY")}}var hs=class{_key;constructor(e){m0(e),this._key=e}verify(e,t){return j8(this._key,t,e)}marshal(){return Z8(this._key)}get bytes(){return $r.encode({Type:Ke.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}async hash(){let e=Ne.digest(this.bytes),t;return vr(e)?{bytes:t}=await e:t=e.bytes,t}},ps=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??e6(e),J8(this._key),m0(this._publicKey)}sign(e){return Q8(this._key,e)}get public(){return new hs(this._publicKey)}marshal(){return this._key}get bytes(){return Hr.encode({Type:Ke.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return O(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return ri(this.bytes,e);throw new g(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function AS(r){return new ps(r)}function IS(r){return new hs(r)}async function DS(){let r=X8();return new ps(r)}var Kn={rsa:d0,ed25519:Jh,secp256k1:g0};function y0(r){let e=Object.keys(Kn).join(" / ");return new g(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function w0(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return Kn[r];throw y0(r)}async function Oa(r,e){return w0(r).generateKeyPair(e??2048)}async function TS(r,e,t){if(r.toLowerCase()!=="ed25519")throw new g("Seed key derivation is unimplemented for RSA or secp256k1","ERR_UNSUPPORTED_KEY_DERIVATION_TYPE");return Zh(e)}function zr(r){let e=$r.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Ke.RSA:return Kn.rsa.unmarshalRsaPublicKey(t);case Ke.Ed25519:return Kn.ed25519.unmarshalEd25519PublicKey(t);case Ke.Secp256k1:return Kn.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw y0(e.Type??"unknown")}}function E0(r,e){return e=(e??"rsa").toLowerCase(),w0(e),r.bytes}async function Ar(r){let e=Hr.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Ke.RSA:return Kn.rsa.unmarshalRsaPrivateKey(t);case Ke.Ed25519:return Kn.ed25519.unmarshalEd25519PrivateKey(t);case Ke.Secp256k1:return Kn.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw y0(e.Type??"RSA")}}function b0(r,e){return e=(e??"rsa").toLowerCase(),w0(e),r.bytes}async function li(r,e){try{let t=await Gm(r,e);return await Ar(t)}catch{}if(!r.includes("BEGIN"))throw new g("Encrypted key was not a libp2p-key or a PEM file","ERR_INVALID_IMPORT_FORMAT");return c0(r,e)}var Ba=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),Ro=new Uint32Array(80),x0=class extends ao{constructor(){super(64,20,8,!1),this.A=Ba[0]|0,this.B=Ba[1]|0,this.C=Ba[2]|0,this.D=Ba[3]|0,this.E=Ba[4]|0}get(){let{A:e,B:t,C:n,D:o,E:s}=this;return[e,t,n,o,s]}set(e,t,n,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0}process(e,t){for(let c=0;c<16;c++,t+=4)Ro[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Ro[c]=ol(Ro[c-3]^Ro[c-8]^Ro[c-14]^Ro[c-16],1);let{A:n,B:o,C:s,D:i,E:a}=this;for(let c=0;c<80;c++){let l,d;c<20?(l=il(o,s,i),d=1518500249):c<40?(l=o^s^i,d=1859775393):c<60?(l=al(o,s,i),d=2400959708):(l=o^s^i,d=3395469782);let u=ol(n,5)+l+a+d+Ro[c]|0;a=i,i=s,s=ol(o,30),o=n,n=u}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,this.set(n,o,s,i,a)}roundClean(){Ro.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}},t6=Zs(()=>new x0);var r6={sha1:t6,"sha2-256":vo,"sha2-512":uo};function Ma(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(r6).join(" / ");throw new g(`Hash '${o}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let s=r6[o],i=Qm(s,r,e,{c:t,dkLen:n});return st.encode(i).substring(1)}var v0=class extends it{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Fa(r){let{name:e,metrics:t}=r,n;return t!=null?n=new v0({name:e,metrics:t}):n=new it,n}var $n=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=st.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=st.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=st.encode(e.multihash.bytes);this.blocks.set(n,t)}};function kS(r){let e=new Uint8Array(r.reduce((n,o)=>n+Se(o),0)),t=0;for(let n of r)e=$e(n,e,t),t+=Se(n);return e}var i6=kS;function R0(r){return i6([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var uu=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t=new $n,n=new Set;for(let[o,s]of this.wants.entries())try{let i=await this.blockstore.get(s.cid,e);s.wantType===rt.WantHave?i.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",s.cid),n.add(o),t.addBlock(s.cid,{data:i,prefix:R0(s.cid)})):(this.log("sending have for %c",s.cid),t.addBlockPresence(s.cid,{cid:s.cid.bytes,type:xr.HaveBlock})):(this.log("sending block for %c",s.cid),n.add(o),t.addBlock(s.cid,{data:i,prefix:R0(s.cid)}))}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i;if(this.log("do not have block for %c",s.cid),!s.sendDontHave||s.sentDontHave===!0)continue;s.sentDontHave=!0,t.addBlockPresence(s.cid,{cid:s.cid.bytes,type:xr.DontHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((o,s)=>o+s.data.byteLength,0));for(let o of n)this.wants.delete(o)}}};var du=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=Fa({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new uu({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let o of t.wantlist.entries){let s=le.decode(o.cid),i=O(s.multihash.bytes,"base64");o.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,s),n.wants.delete(i)):(o.wantType===rt.WantHave?this.log("peer %p wanted block presence for %c",e,s):this.log("peer %p wanted block for %c",e,s),n.wants.set(i,{cid:s,priority:o.priority,wantType:o.wantType??rt.WantBlock,sendDontHave:o.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=O(e.multihash.bytes,"base64"),o=[];for(let s of this.ledgerMap.values())s.wants.has(n)&&o.push(s);await Promise.all(o.map(async s=>s.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var sr=Qe(d6(),1);sr.default.formatters.b=r=>r==null?"undefined":Ye.baseEncode(r);sr.default.formatters.t=r=>r==null?"undefined":ut.baseEncode(r);sr.default.formatters.m=r=>r==null?"undefined":st.baseEncode(r);sr.default.formatters.p=r=>r==null?"undefined":r.toString();sr.default.formatters.c=r=>r==null?"undefined":r.toString();sr.default.formatters.k=r=>r==null?"undefined":r.toString();sr.default.formatters.a=r=>r==null?"undefined":r.toString();function HS(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function So(){return{forComponent(r){return ir(r)}}}function ir(r){let e=HS(`${r}:trace`);return sr.default.enabled(`${r}:trace`)&&sr.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,sr.default)(`${r}:trace`)),Object.assign((0,sr.default)(r),{error:(0,sr.default)(`${r}:error`),trace:e})}var _0=Qe(h6(),1);var _o=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},A0=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},p6=r=>globalThis.DOMException===void 0?new A0(r):new DOMException(r),m6=r=>{let e=r.reason===void 0?p6("This operation was aborted."):r.reason;return e instanceof Error?e:p6(e)};function Yr(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((l,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&d(m6(h)),h.addEventListener("abort",()=>{d(m6(h))})}if(t===Number.POSITIVE_INFINITY){r.then(l,d);return}let u=new _o;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(h){d(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?d(o):(u.message=o??`Promise timed out after ${t} milliseconds`,d(u))},t),(async()=>{try{l(await r)}catch(h){d(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function I0(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Ka=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=I0(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var Ir=class extends _0.default{#e;#t;#r=0;#o;#a;#l=0;#s;#u;#n;#m;#i=0;#d;#c;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ka,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#o=e.intervalCap,this.#a=e.interval,this.#n=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#c=e.autoStart===!1}get#E(){return this.#t||this.#r<this.#o}get#b(){return this.#i<this.#d}#x(){this.#i--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#u=void 0}get#R(){let e=Date.now();if(this.#s===void 0){let t=this.#l-e;if(t<0)this.#r=this.#e?this.#i:0;else return this.#u===void 0&&(this.#u=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#n.size===0)return this.#s&&clearInterval(this.#s),this.#s=void 0,this.emit("empty"),this.#i===0&&this.emit("idle"),!1;if(!this.#c){let e=!this.#R;if(this.#E&&this.#b){let t=this.#n.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#s!==void 0||(this.#s=setInterval(()=>{this.#w()},this.#a),this.#l=Date.now()+this.#a)}#w(){this.#r===0&&this.#i===0&&this.#s&&(clearInterval(this.#s),this.#s=void 0),this.#r=this.#e?this.#i:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#d}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#d=e,this.#h()}async#S(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#i++,this.#r++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=Yr(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#S(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof _o&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#x()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#c?(this.#c=!1,this.#h(),this):this}pause(){this.#c=!0}clear(){this.#n=new this.#m}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#i===0&&this.#n.size===0||await this.#p("idle")}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#i}get isPaused(){return this.#c}};function mu(r){let e=[ar.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var D0=60;function gu(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:ar[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:ar[e.type],TTL:e.TTL??e.ttl??D0,data:e.data instanceof Uint8Array?O(e.data):e.data}))}}var WS=4;function T0(r,e={}){let t=new Ir({concurrency:e.queryConcurrency??WS});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),mu(o.types).forEach(a=>{s.append("type",ar[a])}),o.onProgress?.(new me("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=gu(await a.json());return o.onProgress?.(new me("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function g6(){return[T0("https://cloudflare-dns.com/dns-query"),T0("https://dns.google/resolve")]}var w6=Qe(k0(),1);var C0=class{lru;constructor(e){this.lru=(0,w6.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return gu({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:ar[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??D0)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function E6(r){return new C0(r)}var zS=1e3,yu=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=E6(e.cacheSize??zS),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=g6())}async query(e,t={}){let n=mu(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new me("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let d of l.Answer)this.cache.add(e,d);return l}catch(l){a.push(l),t.onProgress?.(new me("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var ar;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(ar||(ar={}));function wu(r={}){return new yu(r)}var YS=["string","number","bigint","symbol"],XS=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function b6(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(YS.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(QS(r))return"Buffer";let t=jS(r);return t||"Object"}function QS(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function jS(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(XS.includes(e))return e}var _=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};_.uint=new _(0,"uint",!0);_.negint=new _(1,"negint",!0);_.bytes=new _(2,"bytes",!0);_.string=new _(3,"string",!0);_.array=new _(4,"array",!1);_.map=new _(5,"map",!1);_.tag=new _(6,"tag",!1);_.float=new _(7,"float",!0);_.false=new _(7,"false",!0);_.true=new _(7,"true",!0);_.null=new _(7,"null",!0);_.undefined=new _(7,"undefined",!0);_.break=new _(7,"break",!0);var F=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var hi=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ZS=new TextDecoder,JS=new TextEncoder;function Eu(r){return hi&&globalThis.Buffer.isBuffer(r)}function $a(r){return r instanceof Uint8Array?Eu(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var S6=hi?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):v6(r,e,t):(r,e,t)=>t-e>64?ZS.decode(r.subarray(e,t)):v6(r,e,t),bu=hi?r=>r.length>64?globalThis.Buffer.from(r):x6(r):r=>r.length>64?JS.encode(r):x6(r),hn=r=>Uint8Array.from(r),pi=hi?(r,e,t)=>Eu(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),_6=hi?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),$a(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},A6=hi?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function I6(r,e){if(Eu(r)&&Eu(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function x6(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function v6(r,e,t){let n=[];for(;e<t;){let o=r[e],s=null,i=o>239?4:o>223?3:o>191?2:1;if(e+i<=t){let a,c,l,d;switch(i){case 1:o<128&&(s=o);break;case 2:a=r[e+1],(a&192)===128&&(d=(o&31)<<6|a&63,d>127&&(s=d));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(d=(o&15)<<12|(a&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(d=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,d>65535&&d<1114112&&(s=d))}}s===null?(s=65533,i=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),e+=i}return N0(n)}var R6=4096;function N0(r){let e=r.length;if(e<=R6)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=R6));return t}var e_=256,Ha=class{constructor(e=e_){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=A6(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=pi(n,0,this.cursor)}else t=_6(this.chunks,this.cursor);return e&&this.reset(),t}};var Q="CBOR decode error:",mi="CBOR encode error:",qa=[];qa[23]=1;qa[24]=2;qa[25]=3;qa[26]=5;qa[27]=9;function Hn(r,e,t){if(r.length-e<t)throw new Error(`${Q} not enough data for type`)}var gt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function cr(r,e,t){Hn(r,e,1);let n=r[e];if(t.strict===!0&&n<gt[0])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);return n}function lr(r,e,t){Hn(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<gt[1])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);return n}function ur(r,e,t){Hn(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<gt[2])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);return n}function dr(r,e,t){Hn(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],s=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&s<gt[3])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${Q} integers outside of the safe integer range are not supported`)}function D6(r,e,t,n){return new F(_.uint,cr(r,e+1,n),2)}function T6(r,e,t,n){return new F(_.uint,lr(r,e+1,n),3)}function k6(r,e,t,n){return new F(_.uint,ur(r,e+1,n),5)}function C6(r,e,t,n){return new F(_.uint,dr(r,e+1,n),9)}function Dr(r,e){return bt(r,0,e.value)}function bt(r,e,t){if(t<gt[0]){let n=Number(t);r.push([e|n])}else if(t<gt[1]){let n=Number(t);r.push([e|24,n])}else if(t<gt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<gt[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<gt[4]){let o=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=s&255,s=s>>8,o[7]=s&255,s=s>>8,o[6]=s&255,s=s>>8,o[5]=s&255,o[4]=i&255,i=i>>8,o[3]=i&255,i=i>>8,o[2]=i&255,i=i>>8,o[1]=i&255,r.push(o)}else throw new Error(`${Q} encountered BigInt larger than allowable range`)}}Dr.encodedSize=function(e){return bt.encodedSize(e.value)};bt.encodedSize=function(e){return e<gt[0]?1:e<gt[1]?2:e<gt[2]?3:e<gt[3]?5:9};Dr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function N6(r,e,t,n){return new F(_.negint,-1-cr(r,e+1,n),2)}function L6(r,e,t,n){return new F(_.negint,-1-lr(r,e+1,n),3)}function P6(r,e,t,n){return new F(_.negint,-1-ur(r,e+1,n),5)}var L0=BigInt(-1),O6=BigInt(1);function B6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o!="bigint"){let s=-1-o;if(s>=Number.MIN_SAFE_INTEGER)return new F(_.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${Q} integers outside of the safe integer range are not supported`);return new F(_.negint,L0-BigInt(o),9)}function xu(r,e){let t=e.value,n=typeof t=="bigint"?t*L0-O6:t*-1-1;bt(r,e.type.majorEncoded,n)}xu.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*L0-O6:t*-1-1;return n<gt[0]?1:n<gt[1]?2:n<gt[2]?3:n<gt[3]?5:9};xu.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Ga(r,e,t,n){Hn(r,e,t+n);let o=pi(r,e+t,e+t+n);return new F(_.bytes,o,t+n)}function M6(r,e,t,n){return Ga(r,e,1,t)}function U6(r,e,t,n){return Ga(r,e,2,cr(r,e+1,n))}function F6(r,e,t,n){return Ga(r,e,3,lr(r,e+1,n))}function V6(r,e,t,n){return Ga(r,e,5,ur(r,e+1,n))}function K6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer bytes lengths not supported`);return Ga(r,e,9,o)}function vu(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===_.string?bu(r.value):r.value),r.encodedBytes}function gi(r,e){let t=vu(e);bt(r,e.type.majorEncoded,t.length),r.push(t)}gi.encodedSize=function(e){let t=vu(e);return bt.encodedSize(t.length)+t.length};gi.compareTokens=function(e,t){return r_(vu(e),vu(t))};function r_(r,e){return r.length<e.length?-1:r.length>e.length?1:I6(r,e)}function Wa(r,e,t,n,o){let s=t+n;Hn(r,e,s);let i=new F(_.string,S6(r,e+t,e+s),s);return o.retainStringBytes===!0&&(i.byteValue=pi(r,e+t,e+s)),i}function $6(r,e,t,n){return Wa(r,e,1,t,n)}function H6(r,e,t,n){return Wa(r,e,2,cr(r,e+1,n),n)}function q6(r,e,t,n){return Wa(r,e,3,lr(r,e+1,n),n)}function G6(r,e,t,n){return Wa(r,e,5,ur(r,e+1,n),n)}function W6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer string lengths not supported`);return Wa(r,e,9,o,n)}var z6=gi;function yi(r,e,t,n){return new F(_.array,n,t)}function Y6(r,e,t,n){return yi(r,e,1,t)}function X6(r,e,t,n){return yi(r,e,2,cr(r,e+1,n))}function Q6(r,e,t,n){return yi(r,e,3,lr(r,e+1,n))}function j6(r,e,t,n){return yi(r,e,5,ur(r,e+1,n))}function Z6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer array lengths not supported`);return yi(r,e,9,o)}function J6(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Q} indefinite length items not allowed`);return yi(r,e,1,1/0)}function Ru(r,e){bt(r,_.array.majorEncoded,e.value)}Ru.compareTokens=Dr.compareTokens;Ru.encodedSize=function(e){return bt.encodedSize(e.value)};function wi(r,e,t,n){return new F(_.map,n,t)}function e5(r,e,t,n){return wi(r,e,1,t)}function t5(r,e,t,n){return wi(r,e,2,cr(r,e+1,n))}function r5(r,e,t,n){return wi(r,e,3,lr(r,e+1,n))}function n5(r,e,t,n){return wi(r,e,5,ur(r,e+1,n))}function o5(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer map lengths not supported`);return wi(r,e,9,o)}function s5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Q} indefinite length items not allowed`);return wi(r,e,1,1/0)}function Su(r,e){bt(r,_.map.majorEncoded,e.value)}Su.compareTokens=Dr.compareTokens;Su.encodedSize=function(e){return bt.encodedSize(e.value)};function i5(r,e,t,n){return new F(_.tag,t,1)}function a5(r,e,t,n){return new F(_.tag,cr(r,e+1,n),2)}function c5(r,e,t,n){return new F(_.tag,lr(r,e+1,n),3)}function l5(r,e,t,n){return new F(_.tag,ur(r,e+1,n),5)}function u5(r,e,t,n){return new F(_.tag,dr(r,e+1,n),9)}function _u(r,e){bt(r,_.tag.majorEncoded,e.value)}_u.compareTokens=Dr.compareTokens;_u.encodedSize=function(e){return bt.encodedSize(e.value)};var c_=20,l_=21,u_=22,d_=23;function d5(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Q} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new F(_.null,null,1):new F(_.undefined,void 0,1)}function f5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Q} indefinite length items not allowed`);return new F(_.break,void 0,1)}function P0(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Q} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Q} Infinity values are not supported`)}return new F(_.float,r,e)}function h5(r,e,t,n){return P0(O0(r,e+1),3,n)}function p5(r,e,t,n){return P0(B0(r,e+1),5,n)}function m5(r,e,t,n){return P0(E5(r,e+1),9,n)}function Au(r,e,t){let n=e.value;if(n===!1)r.push([_.float.majorEncoded|c_]);else if(n===!0)r.push([_.float.majorEncoded|l_]);else if(n===null)r.push([_.float.majorEncoded|u_]);else if(n===void 0)r.push([_.float.majorEncoded|d_]);else{let o,s=!1;(!t||t.float64!==!0)&&(y5(n),o=O0(Xr,1),n===o||Number.isNaN(n)?(Xr[0]=249,r.push(Xr.slice(0,3)),s=!0):(w5(n),o=B0(Xr,1),n===o&&(Xr[0]=250,r.push(Xr.slice(0,5)),s=!0))),s||(f_(n),o=E5(Xr,1),Xr[0]=251,r.push(Xr.slice(0,9)))}}Au.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){y5(n);let o=O0(Xr,1);if(n===o||Number.isNaN(n))return 3;if(w5(n),o=B0(Xr,1),n===o)return 5}return 9};var g5=new ArrayBuffer(9),Tr=new DataView(g5,1),Xr=new Uint8Array(g5,0);function y5(r){if(r===1/0)Tr.setUint16(0,31744,!1);else if(r===-1/0)Tr.setUint16(0,64512,!1);else if(Number.isNaN(r))Tr.setUint16(0,32256,!1);else{Tr.setFloat32(0,r);let e=Tr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Tr.setUint16(0,31744,!1);else if(t===0)Tr.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Tr.setUint16(0,0):o<-14?Tr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Tr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function O0(r,e){if(r.length-e<2)throw new Error(`${Q} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,s;return n===0?s=o*2**-24:n!==31?s=(o+1024)*2**(n-25):s=o===0?1/0:NaN,t&32768?-s:s}function w5(r){Tr.setFloat32(0,r,!1)}function B0(r,e){if(r.length-e<4)throw new Error(`${Q} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function f_(r){Tr.setFloat64(0,r,!1)}function E5(r,e){if(r.length-e<8)throw new Error(`${Q} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Au.compareTokens=Dr.compareTokens;function _e(r,e,t){throw new Error(`${Q} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Iu(r){return()=>{throw new Error(`${Q} ${r}`)}}var K=[];for(let r=0;r<=23;r++)K[r]=_e;K[24]=D6;K[25]=T6;K[26]=k6;K[27]=C6;K[28]=_e;K[29]=_e;K[30]=_e;K[31]=_e;for(let r=32;r<=55;r++)K[r]=_e;K[56]=N6;K[57]=L6;K[58]=P6;K[59]=B6;K[60]=_e;K[61]=_e;K[62]=_e;K[63]=_e;for(let r=64;r<=87;r++)K[r]=M6;K[88]=U6;K[89]=F6;K[90]=V6;K[91]=K6;K[92]=_e;K[93]=_e;K[94]=_e;K[95]=Iu("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)K[r]=$6;K[120]=H6;K[121]=q6;K[122]=G6;K[123]=W6;K[124]=_e;K[125]=_e;K[126]=_e;K[127]=Iu("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)K[r]=Y6;K[152]=X6;K[153]=Q6;K[154]=j6;K[155]=Z6;K[156]=_e;K[157]=_e;K[158]=_e;K[159]=J6;for(let r=160;r<=183;r++)K[r]=e5;K[184]=t5;K[185]=r5;K[186]=n5;K[187]=o5;K[188]=_e;K[189]=_e;K[190]=_e;K[191]=s5;for(let r=192;r<=215;r++)K[r]=i5;K[216]=a5;K[217]=c5;K[218]=l5;K[219]=u5;K[220]=_e;K[221]=_e;K[222]=_e;K[223]=_e;for(let r=224;r<=243;r++)K[r]=Iu("simple values are not supported");K[244]=_e;K[245]=_e;K[246]=_e;K[247]=d5;K[248]=Iu("simple values are not supported");K[249]=h5;K[250]=p5;K[251]=m5;K[252]=_e;K[253]=_e;K[254]=_e;K[255]=f5;var Qr=[];for(let r=0;r<24;r++)Qr[r]=new F(_.uint,r,1);for(let r=-1;r>=-24;r--)Qr[31-r]=new F(_.negint,r,1);Qr[64]=new F(_.bytes,new Uint8Array(0),1);Qr[96]=new F(_.string,"",1);Qr[128]=new F(_.array,0,1);Qr[160]=new F(_.map,0,1);Qr[244]=new F(_.false,!1,1);Qr[245]=new F(_.true,!0,1);Qr[246]=new F(_.null,null,1);function b5(r){switch(r.type){case _.false:return hn([244]);case _.true:return hn([245]);case _.null:return hn([246]);case _.bytes:return r.value.length?void 0:hn([64]);case _.string:return r.value===""?hn([96]):void 0;case _.array:return r.value===0?hn([128]):void 0;case _.map:return r.value===0?hn([160]):void 0;case _.uint:return r.value<24?hn([Number(r.value)]):void 0;case _.negint:if(r.value>=-24)return hn([31-Number(r.value)])}}var p_={float64:!1,mapSorter:y_,quickEncodeToken:b5};function m_(){let r=[];return r[_.uint.major]=Dr,r[_.negint.major]=xu,r[_.bytes.major]=gi,r[_.string.major]=z6,r[_.array.major]=Ru,r[_.map.major]=Su,r[_.tag.major]=_u,r[_.float.major]=Au,r}var x5=m_(),M0=new Ha,Tu=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${mi} object contains circular references`);return new r(t,e)}},Ao={null:new F(_.null,null),undefined:new F(_.undefined,void 0),true:new F(_.true,!0),false:new F(_.false,!1),emptyArray:new F(_.array,0),emptyMap:new F(_.map,0)},Io={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new F(_.float,r):r>=0?new F(_.uint,r):new F(_.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new F(_.uint,r):new F(_.negint,r)},Uint8Array(r,e,t,n){return new F(_.bytes,r)},string(r,e,t,n){return new F(_.string,r)},boolean(r,e,t,n){return r?Ao.true:Ao.false},null(r,e,t,n){return Ao.null},undefined(r,e,t,n){return Ao.undefined},ArrayBuffer(r,e,t,n){return new F(_.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new F(_.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Ao.emptyArray,new F(_.break)]:Ao.emptyArray;n=Tu.createCheck(n,r);let o=[],s=0;for(let i of r)o[s++]=Du(i,t,n);return t.addBreakTokens?[new F(_.array,r.length),o,new F(_.break)]:[new F(_.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",s=o?r.keys():Object.keys(r),i=o?r.size:s.length;if(!i)return t.addBreakTokens===!0?[Ao.emptyMap,new F(_.break)]:Ao.emptyMap;n=Tu.createCheck(n,r);let a=[],c=0;for(let l of s)a[c++]=[Du(l,t,n),Du(o?r.get(l):r[l],t,n)];return g_(a,t),t.addBreakTokens?[new F(_.map,i),a,new F(_.break)]:[new F(_.map,i),a]}};Io.Map=Io.Object;Io.Buffer=Io.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Io[`${r}Array`]=Io.DataView;function Du(r,e={},t){let n=b6(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Io[n];if(typeof o=="function"){let i=o(r,n,e,t);if(i!=null)return i}let s=Io[n];if(!s)throw new Error(`${mi} unsupported type: ${n}`);return s(r,n,e,t)}function g_(r,e){e.mapSorter&&r.sort(e.mapSorter)}function y_(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,s=x5[o].compareTokens(t,n);return s===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),s}function v5(r,e,t,n){if(Array.isArray(e))for(let o of e)v5(r,o,t,n);else t[e.type.major](r,e,n)}function R5(r,e,t){let n=Du(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let s=e[n.type.major];if(s.encodedSize){let i=s.encodedSize(n,t),a=new Ha(i);if(s(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return $a(a.chunks[0])}}return M0.reset(),v5(M0,n,e,t),M0.toBytes(!0)}function Ei(r,e){return e=Object.assign({},p_,e),R5(r,x5,e)}var w_={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},ku=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Qr[e];if(t===void 0){let n=K[e];if(!n)throw new Error(`${Q} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},za=Symbol.for("DONE"),Cu=Symbol.for("BREAK");function E_(r,e,t){let n=[];for(let o=0;o<r.value;o++){let s=bi(e,t);if(s===Cu){if(r.value===1/0)break;throw new Error(`${Q} got unexpected break to lengthed array`)}if(s===za)throw new Error(`${Q} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=s}return n}function b_(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},s=n?new Map:void 0;for(let i=0;i<r.value;i++){let a=bi(e,t);if(a===Cu){if(r.value===1/0)break;throw new Error(`${Q} got unexpected break to lengthed map`)}if(a===za)throw new Error(`${Q} found map but not enough entries (got ${i} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${Q} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&s.has(a)||!n&&a in o))throw new Error(`${Q} found repeat map key "${a}"`);let c=bi(e,t);if(c===za)throw new Error(`${Q} found map but not enough entries (got ${i} [no value], expected ${r.value})`);n?s.set(a,c):o[a]=c}return n?s:o}function bi(r,e){if(r.done())return za;let t=r.next();if(t.type===_.break)return Cu;if(t.type.terminal)return t.value;if(t.type===_.array)return E_(t,r,e);if(t.type===_.map)return b_(t,r,e);if(t.type===_.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=bi(r,e);return e.tags[t.value](n)}throw new Error(`${Q} tag not supported (${t.value})`)}throw new Error("unsupported")}function U0(r,e){if(!(r instanceof Uint8Array))throw new Error(`${Q} data to decode must be a Uint8Array`);e=Object.assign({},w_,e);let t=e.tokenizer||new ku(r,e),n=bi(t,e);if(n===za)throw new Error(`${Q} did not find any content to decode`);if(n===Cu)throw new Error(`${Q} got unexpected break`);return[n,r.subarray(t.pos())]}function kr(r,e){let[t,n]=U0(r,e);if(n.length>0)throw new Error(`${Q} too many terminals, data makes no sense`);return t}var qn="/",S5=new TextEncoder().encode(qn),Lu=S5[0],Pe=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=M(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Lu)throw new Error("Invalid key")}toString(e="utf8"){return O(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(qn))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=S5),this._buf[0]!==Lu){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Lu,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Lu;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(qn).slice(1)}type(){return x_(this.baseNamespace())}name(){return v_(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(qn)||(e+=qn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(qn):new r(e.slice(0,-1).join(qn))}child(e){return this.toString()===qn?e:e.toString()===qn?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...R_(e.map(t=>t.namespaces()))])}};function x_(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function v_(r){let e=r.split(":");return e[e.length-1]}function R_(r){return[].concat(...r)}var D5="/pin/",_5="/pinned-block/",F0=so,A5=1;function I5(r){return r.version===0&&(r=r.toV1()),new Pe(`${D5}${r.toString(F0)}`)}var Pu=class{datastore;blockstore;dagWalkers;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.dagWalkers=n}async*add(e,t={}){let n=I5(e);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let s=new tr({concurrency:A5});for await(let a of this.#e(e,s,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>Z(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Ei(i),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=this.dagWalkers[e.code];if(o==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let s=await this.blockstore.get(e,n);yield e;for await(let i of o.walk(s))yield*await t.add(async()=>this.#e(i,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new Pe(`${_5}${F0.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=kr(await this.datastore.get(o,n))}catch(a){if(a.code!=="ERR_NOT_FOUND")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Ei(s),n),n.onProgress?.(new me("helia:pin:add",e))}}async*rm(e,t={}){let n=I5(e),o=await this.datastore.get(n,t),s=kr(o);await this.datastore.delete(n,t);let i=new tr({concurrency:A5});for await(let a of this.#e(e,i,{...t,depth:s.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>Z(l,e.bytes)),!0),{...t,depth:s.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:D5+(e.cid!=null?`${e.cid.toString(so)}`:"")},e)){let o=le.parse(t.toString().substring(5),so),s=kr(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new Pe(`${_5}${F0.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}};var S_=5,Ou=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??S_}async start(){await cn(...this.routers)}async stop(){await ln(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new g("No content routers available","ERR_NO_ROUTERS_AVAILABLE");let n=new wr({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of Mt(n.toGenerator(),...xi(this.routers,"findProviders").map(s=>s.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let s=await this.findPeer(o.id,t);return s.multiaddrs.length===0?null:s}catch(s){return this.log.error("could not load multiaddrs for peer %p",o.id,s),null}},{peerId:o.id,signal:t.signal}).catch(s=>{this.log.error("could not load multiaddrs for peer %p",o.id,s)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new g("No content routers available","ERR_NO_ROUTERS_AVAILABLE");await Promise.all(xi(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async put(e,t,n){await Promise.all(xi(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(xi(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new g("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");let n=this,o=Mt(...xi(this.routers,"findPeer").map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s;throw new g("Could not find peer in routing","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new g("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");for await(let n of Mt(...xi(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function xi(r,e){return r.filter(t=>t[e]!=null)}var Do={},vi=r=>{r.addEventListener("message",e=>{vi.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{vi.dispatchEvent("message",r,e)})};vi.addEventListener=(r,e)=>{Do[r]==null&&(Do[r]=[]),Do[r].push(e)};vi.removeEventListener=(r,e)=>{Do[r]!=null&&(Do[r]=Do[r].filter(t=>t===e))};vi.dispatchEvent=function(r,e,t){Do[r]!=null&&Do[r].forEach(n=>n(e,t))};var V0=vi;var K0="lock:worker:request-read",$0="lock:worker:release-read",H0="lock:master:grant-read",q0="lock:worker:request-write",G0="lock:worker:release-write",W0="lock:master:grant-write";var T5=(r=21)=>Math.random().toString().substring(2);var k5=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=d=>{if(d==null||d.data==null)return;let u={type:d.data.type,name:d.data.name,identifier:d.data.identifier};u.type===n&&u.identifier===a.identifier&&(s.removeEventListener("message",l),c())};s.addEventListener("message",l)})}}}))},C5=(r,e,t,n)=>async()=>{let o=T5();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},__={singleProcess:!1},N5=r=>{if(r=Object.assign({},__,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return V0.addEventListener("message",k5(t,"requestReadLock",K0,$0,H0)),V0.addEventListener("message",k5(t,"requestWriteLock",q0,G0,W0)),t}return{isWorker:!0,readLock:t=>C5(t,K0,H0,$0),writeLock:t=>C5(t,q0,W0,G0)}};var ys={},To;async function z0(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>Yr((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var A_=(r,e)=>{if(To.isWorker===!0)return{readLock:To.readLock(r,e),writeLock:To.writeLock(r,e)};let t=new Ir({concurrency:1}),n;return{async readLock(){if(n!=null)return z0(n,e);n=new Ir({concurrency:e.concurrency,autoStart:!1});let o=n,s=z0(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,z0(t,e)}}},I_={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Ya(r){let e=Object.assign({},I_,r);return To==null&&(To=N5(e),To.isWorker!==!0&&(To.addEventListener("requestReadLock",t=>{ys[t.data.name]!=null&&ys[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),To.addEventListener("requestWriteLock",async t=>{ys[t.data.name]!=null&&ys[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),ys[e.name]==null&&(ys[e.name]=A_(e.name,e)),ys[e.name]}var Bu=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Ya({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await cn(this.child),this.started=!0}async stop(){await ln(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let s of e){if(await o.pins.isPinned(s))throw new Error("CID was pinned");yield s}}(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var P5=42;function D_(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=le.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new F(_.tag,P5),new F(_.bytes,t)]}function T_(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function k_(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var L5={float64:!0,typeEncoders:{Object:D_,undefined:T_,number:k_}},GK={...L5,typeEncoders:{...L5.typeEncoders}};function C_(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return le.decode(r.subarray(1))}var Y0={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Y0.tags[P5]=C_;var WK={...Y0,tags:Y0.tags.slice()};var O5=113;var B5=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===_.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===_.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[_.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s);e.push(o)}[_.negint.major](e,t){this[_.uint.major](e,t)}[_.bytes.major](e,t){throw new Error(`${mi} unsupported type: Uint8Array`)}[_.string.major](e,t){this.prefix(e);let n=bu(JSON.stringify(t.value));e.push(n.length>32?$a(n):n)}[_.array.major](e,t){this.prefix(e),this.inRecursive.push({type:_.array,elements:0}),e.push([91])}[_.map.major](e,t){this.prefix(e),this.inRecursive.push({type:_.map,elements:0}),e.push([123])}[_.tag.major](e,t){}[_.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(i.type===_.array)e.push([93]);else if(i.type===_.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${mi} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],s=!1;for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i),!s&&(o[i]===46||o[i]===101||o[i]===69)&&(s=!0);s||(o.push(46),o.push(48)),e.push(o)}};var ws=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${Q} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${Q} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new F(_.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${Q} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${Q} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let s=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(s);return n?new F(_.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new F(i>=0?_.uint:_.negint,i,this._pos-e):new F(i>=0?_.uint:_.negint,BigInt(s),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${Q} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let s=this._pos,i=0;s<this.data.length&&i<65536;s++,i++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,s));return this._pos=s+1,new F(_.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${Q} unexpected end of unicode escape sequence at position ${this._pos}`);let s=0;for(let i=0;i<4;i++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${Q} unexpected unicode escape character at position ${this._pos}`);s=s*16+a,this._pos++}return s},o=()=>{let s=this.ch(),i=null,a=s>239?4:s>223?3:s>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${Q} unexpected unicode sequence at position ${this._pos}`);let c,l,d,u;switch(a){case 1:s<128&&(i=s);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(u=(s&31)<<6|c&63,u>127&&(i=u));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(u=(s&15)<<12|(c&63)<<6|l&63,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],d=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(d&192)===128&&(u=(s&15)<<18|(c&63)<<12|(l&63)<<6|d&63,u>65535&&u<1114112&&(i=u))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let s=this.ch(),i;switch(s){case 92:if(this._pos++,this.done())throw new Error(`${Q} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${Q} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new F(_.string,N0(t),this._pos-e);default:if(s<32)throw new Error(`${Q} invalid control character at position ${this._pos}`);s<128?(t.push(s),this._pos++):o()}}throw new Error(`${Q} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new F(_.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new F(_.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new F(_.null,null,4);case 102:return this.expect([102,97,108,115,101]),new F(_.false,!1,5);case 116:return this.expect([116,114,117,101]),new F(_.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${Q} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new F(_.break,void 0,1);if(this.ch()!==44)throw new Error(`${Q} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new F(_.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new F(_.break,void 0,1);if(this.ch()!==44)throw new Error(`${Q} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new F(_.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${Q} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${Q} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Mu(r,e){return e=Object.assign({tokenizer:new ws(r,e)},e),kr(r,e)}var P_={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};P_.tags[42]=le.parse;var U5=297;var l$=new TextDecoder;var u$=new TextEncoder;var B_=new TextDecoder;function X0(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Uu(r,e){let t;[t,e]=X0(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function F5(r,e){let t;return[t,e]=X0(r,e),[t&7,t>>3,e]}function M_(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=F5(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Uu(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Uu(r,n),e.Name=B_.decode(i)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=X0(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function V5(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=F5(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=Uu(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Uu(r,t),n.push(M_(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let i={};return s&&(i.Data=s),i.Links=n||[],i}var f$=new TextEncoder,h$=2**32,p$=2**31;var y$=new TextEncoder;function K5(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var $5=112;function H5(r){let e=K5(r),t=V5(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=le.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}var F_={codec:$5,*walk(r){yield*H5(r).Links.map(t=>t.Hash)}},V_={codec:Xc,*walk(){}},q5=42,K_={codec:O5,*walk(r){let e=[],t=[];t[q5]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let o=le.decode(n.subarray(1));return e.push(o),o},kr(r,{tags:t}),yield*e}},Q0=class extends ws{tokenBuffer;constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===_.map){let t=this._next();if(t.type===_.string&&t.value==="/"){let n=this._next();if(n.type===_.string){if(this._next().type!==_.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new F(_.tag,42,0)}if(n.type===_.map){let o=this._next();if(o.type===_.string&&o.value==="bytes"){let s=this._next();if(s.type===_.string){for(let a=0;a<2;a++)if(this._next().type!==_.break)throw new Error("Invalid encoded Bytes form");let i=st.decode(`m${s.value}`);return new F(_.bytes,i,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},$_={codec:U5,*walk(r){let e=[],t=[];t[q5]=n=>{let o=le.parse(n);return e.push(o),o},Mu(r,{tags:t,tokenizer:new Q0(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}},H_={codec:W4,*walk(){}};function G5(r=[]){let e={};return[F_,V_,K_,$_,H_,...r].forEach(t=>{e[t.codec]=t}),e}var j0=new Pe("/version"),W5=1;async function z5(r){if(!await r.has(j0)){await r.put(j0,M(`${W5}`));return}let e=await r.get(j0),t=O(e);if(parseInt(t,10)!==W5)throw new Error("Unknown datastore version, a datastore migration may be required")}function Y5(r=[]){let e={};return[Ne,Eh,Wt,...r].forEach(t=>{e[t.code]=t}),e}var Gn=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:o}of e)await this.put(n,o,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var Ri={};pe(Ri,{abortedError:()=>Y_,closeFailedError:()=>G_,deleteFailedError:()=>Q5,getFailedError:()=>W_,hasFailedError:()=>z_,notFoundError:()=>Xa,openFailedError:()=>q_,putFailedError:()=>X5});var Wn=Qe(Yo(),1);function q_(r){return r=r??new Error("Open failed"),(0,Wn.default)(r,"ERR_OPEN_FAILED")}function G_(r){return r=r??new Error("Close failed"),(0,Wn.default)(r,"ERR_CLOSE_FAILED")}function X5(r){return r=r??new Error("Put failed"),(0,Wn.default)(r,"ERR_PUT_FAILED")}function W_(r){return r=r??new Error("Get failed"),(0,Wn.default)(r,"ERR_GET_FAILED")}function Q5(r){return r=r??new Error("Delete failed"),(0,Wn.default)(r,"ERR_DELETE_FAILED")}function z_(r){return r=r??new Error("Has failed"),(0,Wn.default)(r,"ERR_HAS_FAILED")}function Xa(r){return r=r??new Error("Not Found"),(0,Wn.default)(r,"ERR_NOT_FOUND")}function Y_(r){return r=r??new Error("Aborted"),(0,Wn.default)(r,"ERR_ABORTED")}var Qa=class extends Gn{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(ut.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(ut.encode(e.multihash.bytes));if(t==null)throw Xa();return t}has(e){return this.data.has(ut.encode(e.multihash.bytes))}async delete(e){this.data.delete(ut.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:le.createV1(Xc,Mr(ut.decode(e))),block:t}}};function X_(r){return r[Symbol.asyncIterator]!=null}function Q_(r,e){let t=0;if(X_(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Vs(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var jr=Q_;var eH=ir("blockstore:core:tiered");var j5={...Ri};var Fu=0,Vu=class extends Gn{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===Fu||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===Fu)return e.multihash.digest;if(this.child==null)throw j5.notFoundError();return this.child.get(e)}has(e){return e.multihash.code===Fu?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==Fu&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function j_(r){return r[Symbol.asyncIterator]!=null}function Z5(r){return r?.then!=null}function Z_(r,e){let t=0;if(j_(r))return async function*(){for await(let c of r){let l=e(c,t++);Z5(l)&&await l,yield c}}();let n=Vs(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();if(typeof e(o,t++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=e(c,t++);Z5(l)&&await l,yield c}}();let a=e;return function*(){yield o;for(let c of n)a(c,t++),yield c}()}var ja=Z_;var Ku=class{child;hashers;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Vu(e.blockstore),this.hashers=e.hashers??{}}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new me("blocks:put:duplicate",e)),e):(n.onProgress?.(new me("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new me("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=jr(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new me("blocks:put-many:duplicate",s)),!i}),o=ja(n,async({cid:s,block:i})=>{t.onProgress?.(new me("blocks:put-many:providers:notify",s)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(s,i,t)))});t.onProgress?.(new me("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){t.onProgress?.(new me("blocks:get:providers:get",e));let n=await J5(e,this.components.blockBrokers,this.hashers[e.multihash.code],{...t,log:this.log});return t.onProgress?.(new me("blocks:get:blockstore:put",e)),await this.child.put(e,n,t),t.onProgress?.(new me("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n,t))),n}return t.onProgress?.(new me("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new me("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(ja(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){t.onProgress?.(new me("blocks:get-many:providers:get",n));let o=await J5(n,this.components.blockBrokers,this.hashers[n.multihash.code],{...t,log:this.log});t.onProgress?.(new me("blocks:get-many:blockstore:put",n)),await this.child.put(n,o,t),t.onProgress?.(new me("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,o,t)))}}))}async delete(e,t={}){t.onProgress?.(new me("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new me("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of e)yield n}(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new me("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},$u=class extends Ku{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await cn(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await ln(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new Z0({blockstore:this.child,blockBrokers:n,hashers:this.hashers,logger:this.logger},{root:e})}},Z0=class extends Ku{closeController;constructor(e,t){super(e),this.closeController=new AbortController,H(1/0,this.closeController.signal),this.log=e.logger.forComponent(`helia:session-storage${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=Ae([this.closeController.signal,n.signal]);H(1/0,o);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Ae([this.closeController.signal,e.signal]);H(1/0,t);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function J_(r){return typeof r.retrieve=="function"}var eA=(r,e)=>{if(e==null)throw new g(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`,"ERR_UNKNOWN_HASH_ALG");return async t=>{let n=await e.digest(t);if(!Z(n.digest,r.multihash.digest))throw new g("Hash of downloaded block did not match multihash from passed CID","ERR_HASH_MISMATCH")}};async function J5(r,e,t,n){let o=eA(r,t),s=new AbortController,i=Ae([s.signal,n.signal]);H(1/0,s.signal,i);let a=[];for(let c of e)J_(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,d=await c.retrieve(r,{...n,signal:i,validateFn:async u=>{await o(u),l=!0}});return l||await o(d),d}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{s.abort(),i.clear()}}var eg=1,tg=5;var J0=Qe(s6(),1);var tA=Math.LN2*Math.LN2,Hu=class r{static create(e,t=.005){let n=rA(e,t);return new r(n)}seeds;bits;buffer;constructor(e={}){e.seeds!=null?this.seeds=e.seeds:this.seeds=nA(e.hashes??8),this.bits=e.bits??1024,this.buffer=Ie(Math.ceil(this.bits/8))}add(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.seeds.length;t++){let o=J0.default.x86.hash32(e,this.seeds[t])%this.bits;this.setbit(o)}}has(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.seeds.length;t++){let o=J0.default.x86.hash32(e,this.seeds[t])%this.bits;if(!this.getbit(o))return!1}return!0}clear(){this.buffer.fill(0)}setbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;let o=this.buffer[t];o|=1<<n,this.buffer[t]=o}getbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;return(this.buffer[t]&1<<n)!==0}};function rA(r,e=.005){let t=Math.round(-1*r*Math.log(e)/tA),n=Math.round(t/r*Math.LN2);return{bits:t,hashes:n}}function nA(r){let e,t,n=[];for(let o=0;o<r;o++)for(e=new ce(pt(4)),n[o]=e.getUint32(0,!0),t=0;t<o;t++)if(n[o]===n[t]){o--;break}return n}var Es=class extends ye{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),H(1/0,this),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Hu.create(this.maxProviders)}async retrieve(e,t={}){let n=st.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let s=J();if(this.requests.set(n,s.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",e)}let i=!1,a=new tr({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{i=!0,s.resolve(l.detail.result)}),a.addEventListener("idle",()=>{i||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c",e,l),s.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,d)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(e,l,t),{provider:l}))).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,l)});try{return await s.promise}finally{this.removeEventListener("provider",c),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.providers.some(t=>this.equals(t,e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=J(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let i of this.findNewProviders(e,n)){if(s===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",s,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),s++,s===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",s);break}}if(this.log("found %d/%d new session peers",s,this.maxProviders),s<t)throw new g(`Found ${s} of ${t} ${this.name} providers for ${e}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",e,i.errors??i),o.reject(i)}),o.promise}};var qu=class{blockstore;datastore;pins;logger;routing;dagWalkers;hashers;dns;metrics;log;constructor(e){this.logger=e.logger??So(),this.log=this.logger.forComponent("helia"),this.hashers=Y5(e.hashers),this.dagWalkers=G5(e.dagWalkers),this.dns=e.dns??wu(),this.metrics=e.metrics;let t={blockstore:e.blockstore,datastore:e.datastore,hashers:this.hashers,dagWalkers:this.dagWalkers,logger:this.logger,blockBrokers:[],dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new Ou(t,{routers:(e.routers??[]).flatMap(o=>{let s=[o];return o[on]!=null&&s.push(o[on]),o[sn]!=null&&s.push(o[sn]),s}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new $u(t);this.pins=new Pu(e.datastore,n,this.dagWalkers),this.blockstore=new Bu(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await z5(this.datastore),await cn(this.blockstore,this.datastore,this.routing)}async stop(){await ln(this.blockstore,this.datastore,this.routing)}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await $t(o.deleteMany(async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new me("helia:gc:deleted",s))}catch(i){n.log.error("Error during gc",i),e.onProgress?.(new me("helia:gc:error",i))}}()))}finally{t()}this.log("gc finished")}};var e2=class extends Es{wantList;network;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let o=await this.wantList.wantSessionBlock(e,t,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has&&o.block!=null)return o.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield n.id}toEvictionKey(e){return e.toBytes()}equals(e,t){return e.equals(t)}};function rg(r,e){return new e2(r,e)}var Gu=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var t2=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Wu(r){let{name:e,metrics:t}=r,n;return t!=null?n=new t2({name:e,metrics:t}):n=new Map,n}function oA(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Bt(r);e.push(t),r=r.slice(Se(t))}return e}var ng=oA;var zu=class extends ye{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),H(1/0,this),this.peers=Fa({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=Wu({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=O(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??rt.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,o)),o.wantType===rt.WantHave&&t.wantType===rt.WantBlock&&(o.wantType=rt.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===rt.WantBlock?(await er(this,"block",t?.signal,{filter:a=>Z(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await er(this,"presence",t?.signal,{filter:i=>Z(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=J(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new $n;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o);for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer",s)}})).catch(e=>{this.log.error("error sending messages",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=O(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new $n;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:rt.WantHave,priority:1}),await this.network.sendMessage(t,o),(await er(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Z(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:rt.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new $n;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:rt.WantBlock,priority:1}),await this.network.sendMessage(t,o),(await er(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Z(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=O(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=ng(o.prefix),i=s[0],a=s[1],c=s[2],l=c===Ne.code?Ne:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let d=l.digest(o.data);d.then!=null&&(d=await d);let u=le.create(i===0?0:1,a,d);this.log("received block from %p for %c",e,u),this.safeDispatchEvent("block",{detail:{sender:e,cid:u,block:o.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:u,has:!0,block:o.data}});let h=O(u.multihash.bytes,"base64"),f=this.wants.get(h);f!=null&&(f.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=le.decode(o);this.log("received %s from %p for %c",s,e,i),this.safeDispatchEvent("presence",{detail:{sender:e,cid:i,has:s===xr.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new $n(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:rt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Yu=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.stats=new Gu(e),this.network=new rl(e,t),this.peerWantLists=new du({...e,network:this.network},t),this.wantList=new zu({...e,network:this.network},t)}createSession(e={}){return rg({wantList:this.wantList,network:this.network,logger:this.logger},e)}async want(e,t={}){let n=new AbortController,o=Ae([n.signal,t.signal]);H(1/0,n.signal,o),this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,s)});try{return(await this.wantList.wantBlock(e,{...t,signal:o})).block}finally{n.abort(),o.clear()}}async notify(e,t,n={}){await Promise.all([this.peerWantLists.receivedBlock(e,n),this.wantList.receivedBlock(e,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var og=(r,e={})=>new Yu(r,e);var r2=class{bitswap;started;constructor(e,t={}){let{hashers:n}=e;this.bitswap=og(e,{hashLoader:{getHasher:async o=>{let s;if(typeof o=="string"?s=Object.values(n).find(i=>i.name===o):s=n[o],s!=null)return s;throw new Error(`Could not load hasher for code/name "${o}"`)}},...t}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t,n){await this.bitswap.notify(e,t,n)}async retrieve(e,t={}){return this.bitswap.want(e,t)}createSession(e){let t=this.bitswap.createSession(e);return{announce:async(n,o,s)=>{await this.bitswap.notify(n,o,s)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function n2(r={}){return e=>new r2(e,r)}var Xu=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let d=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let h=Number.parseInt(u,e);if(!Number.isNaN(h))return h});if(d===void 0)break;if(s*=e,s+=d,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var sg=45,sA=15,Si=new Xu;function o2(r){if(!(r.length>sA))return Si.new(r).parseWith(()=>Si.readIPv4Addr())}function s2(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>sg))return Si.new(r).parseWith(()=>Si.readIPv6Addr())}function Qu(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>sg))return Si.new(r).parseWith(()=>Si.readIPAddr())}function _i(r){return!!o2(r)}function Ai(r){return!!s2(r)}function ju(r){return!!Qu(r)}var ag=Qe(ig(),1),iA=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],aA=iA.map(r=>new ag.Netmask(r));function cA(r){for(let e of aA)if(e.contains(r))return!0;return!1}function lA(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Yt(r){return _i(r)?cA(r):Ai(r)?lA(r):void 0}var Vq=parseInt("0xFFFF",16),Kq=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var ug=_i,pA=Ai,i2=function(r){let e=0;if(r=r.toString().trim(),ug(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(pA(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ug(t[n]),i;s&&(i=i2(t[n]),t[n]=O(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,O(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},dg=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Ii={},a2={},gA=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];gA.forEach(r=>{let e=yA(...r);a2[e.code]=e,Ii[e.name]=e});function yA(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function ee(r){if(typeof r=="number"){if(a2[r]!=null)return a2[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Ii[r]!=null)return Ii[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var vG=ee("ip4"),RG=ee("ip6"),SG=ee("ipcidr");function l2(r,e){switch(ee(r).code){case 4:case 41:return EA(e);case 42:return pg(e);case 6:case 273:case 33:case 132:return gg(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return pg(e);case 421:return RA(e);case 444:return mg(e);case 445:return mg(e);case 466:return vA(e);default:return O(e,"base16")}}function u2(r,e){switch(ee(r).code){case 4:return fg(e);case 41:return fg(e);case 42:return hg(e);case 6:case 273:case 33:case 132:return d2(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return hg(e);case 421:return bA(e);case 444:return SA(e);case 445:return _A(e);case 466:return xA(e);default:return M(e,"base16")}}var c2=Object.values(br).map(r=>r.decoder),wA=function(){let r=c2[0].or(c2[1]);return c2.slice(2).forEach(e=>r=r.or(e)),r}();function fg(r){if(!ju(r))throw new Error("invalid ip address");return i2(r)}function EA(r){let e=dg(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!ju(e))throw new Error("invalid ip address");return e}function d2(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function gg(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function hg(r){let e=M(r),t=Uint8Array.from($e(e.length));return ve([t,e],t.length+e.length)}function pg(r){let e=Bt(r);if(r=r.slice(Se(e)),r.length!==e)throw new Error("inconsistent lengths");return O(r)}function bA(r){let e;r[0]==="Q"||r[0]==="1"?e=Mr(Ye.decode(`z${r}`)).bytes:e=le.parse(r).multihash.bytes;let t=Uint8Array.from($e(e.length));return ve([t,e],t.length+e.length)}function xA(r){let e=wA.decode(r),t=Uint8Array.from($e(e.length));return ve([t,e],t.length+e.length)}function vA(r){let e=Bt(r),t=r.slice(Se(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+O(t,"base64url")}function RA(r){let e=Bt(r),t=r.slice(Se(e));if(t.length!==e)throw new Error("inconsistent lengths");return O(t,"base58btc")}function SA(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=ut.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=d2(n);return ve([t,o],t.length+o.length)}function _A(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ut.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=d2(n);return ve([t,o],t.length+o.length)}function mg(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=O(e,"base32"),o=gg(t);return`${n}:${o}`}function yg(r){r=f2(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=ee(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Eg("invalid address: "+r);if(a.path===!0){n=f2(o.slice(s).join("/")),e.push([a.code,u2(a.code,n)]),t.push([a.code,n]);break}let c=u2(a.code,o[s]);e.push([a.code,c]),t.push([a.code,l2(a.code,c)])}return{string:wg(t),bytes:p2(e),tuples:e,stringTuples:t,path:n}}function h2(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=Bt(r,o),i=Se(s),a=ee(s),c=AA(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Eg("Invalid address Uint8Array: "+O(r,"base16"));e.push([s,l]);let d=l2(s,l);if(t.push([s,d]),a.path===!0){n=d;break}}return{bytes:Uint8Array.from(r),string:wg(t),tuples:e,stringTuples:t,path:n}}function wg(r){let e=[];return r.map(t=>{let n=ee(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),f2(e.join("/"))}function p2(r){return ve(r.map(e=>{let t=ee(e[0]),n=Uint8Array.from($e(t.code));return e.length>1&&e[1]!=null&&(n=ve([n,e[1]])),n}))}function AA(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=Bt(e instanceof Uint8Array?e:Uint8Array.from(e));return t+Se(t)}}function f2(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Eg(r){return new Error("Error parsing address: "+r)}var IA=Symbol.for("nodejs.util.inspect.custom"),m2=Symbol.for("@multiformats/js-multiaddr/multiaddr"),DA=[ee("dns").code,ee("dns4").code,ee("dns6").code,ee("dnsaddr").code],Zu=class r{bytes;#e;#t;#r;#o;[m2]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=h2(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=yg(e)}else if(ko(e))t=h2(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#o=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=ee("tcp"),a=ee("udp"),c=ee("ip4"),l=ee("ip6"),d=ee("dns6"),u=ee("ip6zone");for(let[f,p]of this.stringTuples())f===u.code&&(s=`%${p??""}`),DA.includes(f)&&(t=i.name,o=443,n=`${p??""}${s}`,e=f===d.code?6:4),(f===i.code||f===a.code)&&(t=ee(f).name,o=parseInt(p??"")),(f===c.code||f===l.code)&&(t=ee(f).name,n=`${p??""}${s}`,e=f===l.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},ee(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>ee(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(p2(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===Ii.p2p.code&&e.push([n,o]),n===Ii["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?O(Ye.decode(`z${n}`),"base58btc"):O(le.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#o}equals(e){return Z(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=Di.get(t.name);if(n==null)throw new g(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>j(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[IA](){return`Multiaddr(${this.#e})`}};var Di=new Map;function ko(r){return!!r?.[m2]}function j(r){return new Zu(r)}var TA=r=>r.toString().split("/").slice(1),Ja=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),Te=r=>({match:e=>Ja(t=>t===r).match(e),pattern:r}),t1=()=>({match:r=>Ja(e=>typeof e=="string").match(r),pattern:"{string}"}),r1=()=>({match:r=>Ja(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),xt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Ye.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Ju=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{lh.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),vt=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),fr=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Oe=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function nt(...r){function e(o){let s=TA(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var y2=Oe(Te("dns4"),t1()),w2=Oe(Te("dns6"),t1()),E2=Oe(Te("dnsaddr"),t1()),bg=Oe(Te("dns"),t1()),JG=nt(y2),eW=nt(w2),tW=nt(E2),n1=nt(fr(bg,E2,y2,w2)),xg=Oe(Te("ip4"),Ja(_i)),vg=Oe(Te("ip6"),Ja(Ai)),Rg=fr(xg,vg),pn=fr(Rg,bg,y2,w2,E2),Sg=nt(pn),rW=nt(xg),nW=nt(vg),_g=nt(Rg),o1=Oe(pn,Te("tcp"),r1()),ec=Oe(pn,Te("udp"),r1()),kA=fr(o1,ec),oW=nt(o1),sW=nt(ec),b2=Oe(ec,Te("quic")),s1=Oe(ec,Te("quic-v1")),CA=fr(b2,s1),iW=nt(b2),aW=nt(s1),g2=fr(pn,o1,ec,b2,s1),Ag=fr(Oe(g2,Te("ws"),vt(xt()))),cW=nt(Ag),Ig=fr(Oe(g2,Te("wss"),vt(xt())),Oe(g2,Te("tls"),Te("ws"),vt(xt()))),lW=nt(Ig),Dg=Oe(kA,Te("webrtc-direct"),Ju(),vt(Ju()),vt(xt())),Tg=nt(Dg),kg=Oe(s1,Te("webtransport"),vt(Ju()),vt(Ju()),vt(xt())),i1=nt(kg),e1=fr(Ag,Ig,Oe(o1,vt(xt())),Oe(CA,vt(xt())),Oe(pn,vt(xt())),Dg,kg,xt()),uW=nt(e1),NA=Oe(e1,Te("p2p-circuit"),xt()),bs=nt(NA),LA=fr(Oe(e1,Te("p2p-circuit"),Te("webrtc"),xt()),Oe(e1,Te("webrtc"),vt(xt())),Te("webrtc")),Cg=nt(LA),PA=fr(Oe(pn,Te("tcp"),r1(),Te("http"),vt(xt())),Oe(pn,Te("http"),vt(xt()))),Ng=nt(PA),OA=fr(Oe(pn,Te("tcp"),fr(Oe(Te("443"),Te("http")),Oe(r1(),Te("https"))),vt(xt())),Oe(pn,Te("tls"),Te("http"),vt(xt())),Oe(pn,Te("https"),vt(xt()))),Lg=nt(OA);var BA=[ee("tcp").code,ee("dns").code,ee("dnsaddr").code,ee("dns4").code,ee("dns6").code];function Pg(r){let e;try{e=ee("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function Og(r){return r.some(([e,t])=>e===ee("tls").code)}function hr(r,e,t){let n=Bg[ee(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${ee(r).name}`);let o=n(e,t);return r===ee("ip6").code?`[${o}]`:o}var Bg={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${hr(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${hr(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=Og(e),n=Pg(e);if(t&&n!==null)return`https://${n}`;let o=t?"https://":"http://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let i=hr(s[0],s[1]??"",e);return i=i.replace("tcp://",""),`${o}${i}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return hr(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return hr(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=hr(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=Og(e),n=Pg(e);if(t&&n!==null)return`wss://${n}`;let o=t?"wss://":"ws://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let i=hr(s[0],s[1]??"",e);return i=i.replace("tcp://",""),`${o}${i}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=hr(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function a1(r,e){let n=j(r).stringTuples(),o=n.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let s=ee(o[0]),i=Bg[s.name];if(i==null)throw new Error(`No interpreter found for ${s.name}`);let a=i(o[1]??"",n);return e?.assumeHttp!==!1&&BA.includes(o[0])&&(a=a.replace(/^.*:\/\//,""),o[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var c1=class{url;#e=0;#t=0;#r=0;#o=0;#a=new Map;log;constructor(e,t){this.url=e instanceof URL?e:new URL(e),this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#l(e){let t=e.multihash.bytes;return st.encode(t)}async getRawBlock(e,t){let n=new URL(this.url.toString());if(n.pathname=`/ipfs/${e.toString()}`,n.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let o=this.#l(e),s=new AbortController,i=()=>{s.abort()};t?.addEventListener("abort",i);try{let a=this.#a.get(o);return a==null&&(this.#e++,a=fetch(n.toString(),{signal:s.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async c=>{if(this.log("GET %s %d",n,c.status),!c.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);return this.#o++,new Uint8Array(await c.arrayBuffer())}),this.#a.set(o,a)),await a}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",i),this.#a.delete(o)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#o/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#o,pendingResponses:this.#a.size}}};function MA(r,e,t){return r.filter(n=>Lg.matches(n)||e&&Ng.matches(n)?t||n1.matches(n)?!0:Yt(n.toOptions().host)===!1:!1)}async function*l1(r,e,t,n,o,s){for await(let i of e.findProviders(r,s)){let a=MA(i.multiaddrs,n,o);if(a.length===0)continue;let c=a1(a[0]);yield new c1(c,t)}}var x2=class extends Es{routing;allowInsecure;allowLocal;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??u1,this.allowLocal=t.allowLocal??d1}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let o=await t.getRawBlock(e,n.signal);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*l1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}};function Mg(r,e){return new x2(r,e)}var f1=class{allowInsecure;allowLocal;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??u1,this.allowLocal=t.allowLocal??d1}async retrieve(e,t={}){let n=[];for await(let o of l1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)){this.log("getting block for %c from %s",e,o.url);try{let s=await o.getRawBlock(e,t.signal);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s",e,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s",e,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return Mg({logger:this.logger,routing:this.routing},e)}};var u1=!1,d1=!1;function v2(r={}){return e=>new f1(e,r)}async function*h1(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var KA=Qe(Yo(),1);var $A=Qe(p1(),1);var Ug="ERR_IPNS_EXPIRED_RECORD",m1="ERR_UNRECOGNIZED_VALIDITY";var zn="ERR_SIGNATURE_VERIFICATION";var S2="ERR_UNDEFINED_PARAMETER",Fg="ERR_INVALID_RECORD_DATA",Vg="ERR_INVALID_VALUE",Kg="ERR_INVALID_EMBEDDED_KEY";var $g="ERR_RECORD_TOO_LARGE";var Xt;(function(r){let e;(function(o){o.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(o){o[o.EOL=0]="EOL"})(t||(t={})),function(o){o.codec=()=>He(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=ne((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.value!=null&&(s.uint32(10),s.bytes(o.value)),o.signatureV1!=null&&(s.uint32(18),s.bytes(o.signatureV1)),o.validityType!=null&&(s.uint32(24),r.ValidityType.codec().encode(o.validityType,s)),o.validity!=null&&(s.uint32(34),s.bytes(o.validity)),o.sequence!=null&&(s.uint32(40),s.uint64(o.sequence)),o.ttl!=null&&(s.uint32(48),s.uint64(o.ttl)),o.pubKey!=null&&(s.uint32(58),s.bytes(o.pubKey)),o.signatureV2!=null&&(s.uint32(66),s.bytes(o.signatureV2)),o.data!=null&&(s.uint32(74),s.bytes(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.value=o.bytes();break;case 2:i.signatureV1=o.bytes();break;case 3:i.validityType=r.ValidityType.codec().decode(o);break;case 4:i.validity=o.bytes();break;case 5:i.sequence=o.uint64();break;case 6:i.ttl=o.uint64();break;case 7:i.pubKey=o.bytes();break;case 8:i.signatureV2=o.bytes();break;case 9:i.data=o.bytes();break;default:o.skipType(c&7);break}}return i})),n),r.encode=o=>re(o,r.codec()),r.decode=o=>te(o,r.codec())})(Xt||(Xt={}));var pr=Qe(Yo(),1);var qg=ir("ipns:utils"),Gg=M("/ipns/"),UA=114,Wg=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw qg.error(n),(0,pr.default)(n,S2)}let t;if(e.pubKey!=null){try{t=zr(e.pubKey)}catch(o){throw qg.error(o),o}if(!(await dt(e.pubKey)).equals(r))throw(0,pr.default)(new Error("Embedded public key did not match PeerID"),Kg)}else r.publicKey!=null&&(t=zr(r.publicKey));if(t!=null)return t;throw(0,pr.default)(new Error("no public key is available"),S2)};var zg=r=>{let e=M("ipns-signature:");return ve([e,r])},tc=r=>"signatureV1"in r?Xt.encode({value:M(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:M(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):Xt.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data});function mn(r){let e=Xt.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw(0,pr.default)(new Error("missing data or signatureV2"),zn);let t=Xg(e.data),n=FA(t.Value),o=O(t.Validity);if(e.value!=null&&e.signatureV1!=null)return VA(e),{value:n,validityType:Xt.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:Xt.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}var _2=r=>ve([Gg,r.toBytes()]),Yg=r=>Je(r.slice(Gg.length));var Xg=r=>{let e=kr(r);if(e.ValidityType===0)e.ValidityType=Xt.ValidityType.EOL;else throw(0,pr.default)(new Error("Unknown validity type"),m1);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e},FA=r=>{if(r!=null){if(Ms(r))return`/ipns/${r.toCID().toString(so)}`;if(r instanceof Uint8Array){let n=O(r);n.startsWith("/")&&(r=n)}let e=r.toString().trim();if(e.startsWith("/")&&e.length>1)return e;let t=le.asCID(r);if(t!=null)return t.code===UA?`/ipns/${t.toString(so)}`:`/ipfs/${t.toV1().toString()}`;try{return r instanceof Uint8Array?`/ipfs/${le.decode(r).toV1().toString()}`:`/ipfs/${le.parse(e).toV1().toString()}`}catch{}}throw(0,pr.default)(new Error("Value must be a valid content path starting with /"),Vg)},VA=r=>{if(r.data==null)throw(0,pr.default)(new Error("Record data is missing"),Fg);let e=Xg(r.data);if(!Z(e.Value,r.value??new Uint8Array(0)))throw(0,pr.default)(new Error('Field "value" did not match between protobuf and CBOR'),zn);if(!Z(e.Validity,r.validity??new Uint8Array(0)))throw(0,pr.default)(new Error('Field "validity" did not match between protobuf and CBOR'),zn);if(e.ValidityType!==r.validityType)throw(0,pr.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),zn);if(e.Sequence!==r.sequence)throw(0,pr.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),zn);if(e.TTL!==r.ttl)throw(0,pr.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),zn)};var nz=ir("ipns"),oz=Wt.code,sz=60*60*1e9,HA="/ipns/",iz=HA.length;var rc=Qe(Yo(),1),Qg=Qe(p1(),1);var g1=ir("ipns:validator"),qA=1024*10,GA=async(r,e)=>{let t=mn(e),n;try{let o=zg(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw g1.error("record signature verification failed"),(0,rc.default)(new Error("record signature verification failed"),zn);if(t.validityType===Xt.ValidityType.EOL){if(Qg.default.fromString(t.validity).toDate().getTime()<Date.now())throw g1.error("record has expired"),(0,rc.default)(new Error("record has expired"),Ug)}else if(t.validityType!=null)throw g1.error("unrecognized validity type"),(0,rc.default)(new Error("unrecognized validity type"),m1);g1("ipns record for %s is valid",t.value)};async function y1(r,e){if(e.byteLength>qA)throw(0,rc.default)(new Error("record too large"),$g);let t=Yg(r),n=mn(e),o=await Wg(t,n);await GA(o,e)}async function*nc(r){let e=/\r?\n/,t=new TextDecoder("utf8"),n="";for await(let o of r){typeof o=="string"&&(o=new TextEncoder().encode(o)),n+=t.decode(o,{stream:!0});let s=n.split(e);n=s.pop()??"";for(let i=0;i<s.length;i++)yield JSON.parse(s[i])}n+=t.decode(),n!==""&&(yield JSON.parse(n))}function WA(r){return r[Symbol.asyncIterator]!=null}function zA(r){if(WA(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var xs=zA;var A2=M("/ipns/");function jg(r){return Z(r.subarray(0,A2.byteLength),A2)}var Zg=r=>Je(r.slice(A2.length)),w1=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*Gt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async put(e,t,n){if(!jg(e))return;let o=Zg(e),s=mn(t);await this.client.putIPNS(o,s,n)}async get(e,t){if(!jg(e))throw new g("Not found","ERR_NOT_FOUND");let n=Zg(e);try{let o=await this.client.getIPNS(n,t);return tc(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new g("Not found","ERR_NOT_FOUND"):o}}},E1=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await xs(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new g("Not found","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){}};var Qt=ir("delegated-routing-v1-http-api-client"),Jg={concurrentRequests:4,timeout:3e4},b1=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal),this.httpQueue=new Ir({concurrency:t.concurrentRequests??Jg.concurrentRequests}),this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??Jg.timeout,this.contentRouting=new w1(this),this.peerRouting=new E1(this)}get[on](){return this.contentRouting}get[sn](){return this.peerRouting}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.shutDownController.abort(),this.started=!1}async*getProviders(e,t={}){Qt("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ae([this.shutDownController.signal,n,t.signal]);H(1/0,n,o);let s=J(),i=J();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=`${this.clientUrl}routing/v1/providers/${e.toString()}`,l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new g("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new g("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new g("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let h of u.Providers){let f=this.#e(h);f!=null&&(yield f)}}else for await(let u of nc(h1(l.body))){let h=this.#e(u);h!=null&&(yield h)}}catch(a){Qt.error("getProviders errored:",a)}finally{o.clear(),i.resolve(),Qt("getProviders finished: %c",e)}}async*getPeers(e,t={}){Qt("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ae([this.shutDownController.signal,n,t.signal]);H(1/0,n,o);let s=J(),i=J();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`,l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new g("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new g("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new g("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let h of u.Peers){let f=this.#e(h);f!=null&&(yield f)}}else for await(let u of nc(h1(l.body))){let h=this.#e(u);h!=null&&(yield h)}}catch(a){Qt.error("getPeers errored:",a)}finally{o.clear(),i.resolve(),Qt("getPeers finished: %c",e)}}async getIPNS(e,t={}){Qt("getIPNS starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ae([this.shutDownController.signal,n,t.signal]);H(1/0,n,o);let s=J(),i=J();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await s.promise;let l=await fetch(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(Qt("getIPNS GET %s %d",a,l.status),l.status===404)throw new g("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new g("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new g("GET ipns response had no body","ERR_BAD_RESPONSE");let d=await l.arrayBuffer(),u=new Uint8Array(d,0,d.byteLength);return t.validate!==!1&&await y1(_2(e),u),mn(u)}catch(c){throw Qt.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),i.resolve(),Qt("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){Qt("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=Ae([this.shutDownController.signal,o,n.signal]);H(1/0,o,s);let i=J(),a=J();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await i.promise;let l=tc(t),u=await fetch(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:s});if(Qt("putIPNS PUT %s %d",c,u.status),u.status!==200)throw new g("PUT ipns response had status other than 200","ERR_BAD_RESPONSE")}catch(l){throw Qt.error("putIPNS PUT %s error:",c,l.stack),l}finally{s.clear(),a.resolve(),Qt("putIPNS finished: %c",e)}}#e(e){let t=[],n=e.Addrs?.map(j)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:ge(e.ID),Addrs:n,Protocols:t}}};function e7(r,e={}){return new b1(new URL(r),e)}var t7="[a-fA-F\\d:]",Co=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${t7})|(?<=${t7})(?=\\s|$))`:"",Zr="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",ct="[a-fA-F\\d]{1,4}",x1=`
|
|
21
|
+
`)}`:`${t} :`}};im=go;W.Constructed=im;go.NAME="CONSTRUCTED";var Dl=class extends Lt{fromBER(e,t,n){return t}toBER(e){return Gr}};Dl.override="EndOfContentValueBlock";var am,Tl=class extends Et{constructor(e={}){super(e,Dl),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};am=Tl;W.EndOfContent=am;Tl.NAME=Da;var cm,yo=class extends Et{constructor(e={}){super(e,Lt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};cm=yo;W.Null=cm;yo.NAME="NULL";var kl=class extends Fn(Lt){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=we.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=we.BufferSourceConverter.toUint8Array(e);return Un(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,n0.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};kl.NAME="BooleanValueBlock";var lm,Cl=class extends Et{constructor(e={}){super(e,kl),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};lm=Cl;W.Boolean=lm;Cl.NAME="BOOLEAN";var Nl=class extends Fn(un){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=un.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Da){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==rm)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?un.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Nl.NAME="OctetStringValueBlock";var um,Bn=class r extends Et{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Nl),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=iu(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?go.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${we.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return we.BufferSourceConverter.concat(e)}};um=Bn;W.OctetString=um;Bn.NAME=rm;var Ll=class extends Fn(un){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=un.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Da){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==nm)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let s=we.BufferSourceConverter.toUint8Array(e);if(!Un(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=iu(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return un.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Gr;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Ll.NAME="BitStringValueBlock";var dm,ii=class extends Et{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ll),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return go.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};dm=ii;W.BitString=dm;ii.NAME=nm;var fm;function tS(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,d=c<i?i:c,u=0;for(let h=d;h>=0;h--,u++){switch(!0){case u<a.length:l=s[i-u]+a[c-u]+t[0];break;default:l=s[i-u]+t[0]}switch(t[0]=l/10,!0){case u>=s.length:s=xl(new Uint8Array([l%10]),s);break;default:s[i-u]=l%10}}return t[0]>0&&(s=xl(t,s)),s}function tm(r){if(r>=Aa.length)for(let e=Aa.length;e<=r;e++){let t=new Uint8Array([0]),n=Aa[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=xl(t,n)),Aa.push(n)}return Aa[r]}function rS(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,d=0;for(let u=c;u>=0;u--,d++)switch(l=s[i-d]-a[c-d]-t,!0){case l<0:t=1,s[i-d]=l+10;break;default:t=0,s[i-d]=l}if(t>0)for(let u=i-c+1;u>=0;u--,d++)if(l=s[i-d]-t,l<0)t=1,s[i-d]=l+10;else{t=0,s[i-d]=l;break}return s.slice()}var Ta=class extends Fn(Lt){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=n0.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Z8(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=rS(tm(n),t),i="-";break;default:t=tS(t,tm(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=em.charAt(t[c]));return a===!1&&(i+=em.charAt(0)),i}};fm=Ta;Ta.NAME="IntegerValueBlock";Object.defineProperty(fm.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var hm,at=class r extends Et{constructor(e={}){super(e,Ta),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return vl(),BigInt(this.valueBlock.toString())}static fromBigInt(e){vl();let t=BigInt(e),n=new Ia,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(we.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${we.Convert.ToHex(a)}`)+t,d=we.BufferSourceConverter.toUint8Array(we.Convert.FromHex(l.toString(16)));d[0]|=128,n.write(d)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};hm=at;W.Integer=hm;at.NAME="INTEGER";var pm,Pl=class extends at{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};pm=Pl;W.Enumerated=pm;Pl.NAME="ENUMERATED";var ka=class extends Fn(Lt){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=we.BufferSourceConverter.toUint8Array(e);if(!Un(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ls(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){vl();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=mo(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Gr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=we.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};ka.NAME="sidBlock";var Ol=class extends Lt{constructor({value:e=ai,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new ka;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,Gr;t.push(o)}return o0(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new ka;if(o>Number.MAX_SAFE_INTEGER){vl();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Ol.NAME="ObjectIdentifierValueBlock";var mm,qr=class extends Et{constructor(e={}){super(e,Ol),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};mm=qr;W.ObjectIdentifier=mm;qr.NAME="OBJECT IDENTIFIER";var Ca=class extends Fn(On){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=we.BufferSourceConverter.toUint8Array(e);if(!Un(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ls(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=mo(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Gr;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=we.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Ca.NAME="relativeSidBlock";var Bl=class extends Lt{constructor({value:e=ai,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new Ca;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,Gr;n.push(s)}return o0(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new Ca;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Bl.NAME="RelativeObjectIdentifierValueBlock";var gm,Ml=class extends Et{constructor(e={}){super(e,Bl),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};gm=Ml;W.RelativeObjectIdentifier=gm;Ml.NAME="RelativeObjectIdentifier";var ym,mt=class extends go{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};ym=mt;W.Sequence=ym;mt.NAME="SEQUENCE";var wm,Ul=class extends go{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};wm=Ul;W.Set=wm;Ul.NAME="SET";var Fl=class extends Fn(Lt){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ai}toJSON(){return{...super.toJSON(),value:this.value}}};Fl.NAME="StringValueBlock";var Vl=class extends Fl{};Vl.NAME="SimpleStringValueBlock";var Ut=class extends _l{constructor({...e}={}){super(e,Vl)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,we.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Ut.NAME="SIMPLE STRING";var Kl=class extends Ut{fromBuffer(e){this.valueBlock.valueHexView=we.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=we.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=we.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(we.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Kl.NAME="Utf8StringValueBlock";var Em,Mn=class extends Kl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Em=Mn;W.Utf8String=Em;Mn.NAME="UTF8String";var $l=class extends Ut{fromBuffer(e){this.valueBlock.value=we.Convert.ToUtf16String(e),this.valueBlock.valueHexView=we.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(we.Convert.FromUtf16String(e))}};$l.NAME="BmpStringValueBlock";var bm,Hl=class extends $l{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};bm=Hl;W.BmpString=bm;Hl.NAME="BMPString";var ql=class extends Ut{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=mo(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};ql.NAME="UniversalStringValueBlock";var xm,Gl=class extends ql{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};xm=Gl;W.UniversalString=xm;Gl.NAME="UniversalString";var vm,Wl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};vm=Wl;W.NumericString=vm;Wl.NAME="NumericString";var Rm,zl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Rm=zl;W.PrintableString=Rm;zl.NAME="PrintableString";var Sm,Yl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Sm=Yl;W.TeletexString=Sm;Yl.NAME="TeletexString";var _m,Xl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};_m=Xl;W.VideotexString=_m;Xl.NAME="VideotexString";var Am,Ql=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Am=Ql;W.IA5String=Am;Ql.NAME="IA5String";var Im,jl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Im=jl;W.GraphicString=Im;jl.NAME="GraphicString";var Dm,Na=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Dm=Na;W.VisibleString=Dm;Na.NAME="VisibleString";var Tm,Zl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Tm=Zl;W.GeneralString=Tm;Zl.NAME="GeneralString";var km,Jl=class extends Ut{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};km=Jl;W.CharacterString=km;Jl.NAME="CharacterString";var Cm,La=class extends Na{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,we.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=zt(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=zt(this.month,2),t[2]=zt(this.day,2),t[3]=zt(this.hour,2),t[4]=zt(this.minute,2),t[5]=zt(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Cm=La;W.UTCTime=Cm;La.NAME="UTCTime";var Nm,eu=class extends La{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let u=new Number(e[e.length-1]);if(isNaN(u.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let u=1,h=n.indexOf("+"),f="";if(h===-1&&(h=n.indexOf("-"),u=-1),h!==-1){if(f=n.substring(h+1),n=n.substring(0,h),f.length!==2&&f.length!==4)throw new Error("Wrong input string for conversion");let p=parseInt(f.substring(0,2),10);if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");if(a=u*p,f.length===4){if(p=parseInt(f.substring(2,4),10),isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");c=u*p}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let u=new Number(`0${n.substring(l)}`);if(isNaN(u.valueOf()))throw new Error("Wrong input string for conversion");s=u.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=60*s;this.minute=Math.floor(u),u=60*(u-this.minute),this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=60*s;this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=1e3*s;this.millisecond=Math.floor(u)}break;default:throw new Error("Wrong input string for conversion")}let d=i.exec(o);if(d===null)throw new Error("Wrong input string for conversion");for(let u=1;u<d.length;u++)switch(u){case 1:this.year=parseInt(d[u],10);break;case 2:this.month=parseInt(d[u],10);break;case 3:this.day=parseInt(d[u],10);break;case 4:this.hour=parseInt(d[u],10)+a;break;case 5:this.minute=parseInt(d[u],10)+c;break;case 6:this.second=parseInt(d[u],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let u=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=u.getUTCFullYear(),this.month=u.getUTCMonth(),this.day=u.getUTCDay(),this.hour=u.getUTCHours(),this.minute=u.getUTCMinutes(),this.second=u.getUTCSeconds(),this.millisecond=u.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(zt(this.year,4)),t.push(zt(this.month,2)),t.push(zt(this.day,2)),t.push(zt(this.hour,2)),t.push(zt(this.minute,2)),t.push(zt(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(zt(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Nm=eu;W.GeneralizedTime=Nm;eu.NAME="GeneralizedTime";var Lm,tu=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Lm=tu;W.DATE=Lm;tu.NAME="DATE";var Pm,ru=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Pm=ru;W.TimeOfDay=Pm;ru.NAME="TimeOfDay";var Om,nu=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Om=nu;W.DateTime=Om;nu.NAME="DateTime";var Bm,ou=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Bm=ou;W.Duration=Bm;ou.NAME="Duration";var Mm,su=class extends Mn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Mm=su;W.TIME=Mm;su.NAME="TIME";function oS(r){let{result:e}=ci(r),t=e.valueBlock.value;return{n:O(dn(t[1].toBigInt()),"base64url"),e:O(dn(t[2].toBigInt()),"base64url"),d:O(dn(t[3].toBigInt()),"base64url"),p:O(dn(t[4].toBigInt()),"base64url"),q:O(dn(t[5].toBigInt()),"base64url"),dp:O(dn(t[6].toBigInt()),"base64url"),dq:O(dn(t[7].toBigInt()),"base64url"),qi:O(dn(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function sS(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new g("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new mt({value:[new at({value:0}),at.fromBigInt(fn(M(r.n,"base64url"))),at.fromBigInt(fn(M(r.e,"base64url"))),at.fromBigInt(fn(M(r.d,"base64url"))),at.fromBigInt(fn(M(r.p,"base64url"))),at.fromBigInt(fn(M(r.q,"base64url"))),at.fromBigInt(fn(M(r.dp,"base64url"))),at.fromBigInt(fn(M(r.dq,"base64url"))),at.fromBigInt(fn(M(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function iS(r){let{result:e}=ci(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:O(dn(t[0].toBigInt()),"base64url"),e:O(dn(t[1].toBigInt()),"base64url")}}function aS(r){if(r.n==null||r.e==null)throw new g("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new mt({value:[new mt({value:[new qr({value:"1.2.840.113549.1.1.1"}),new yo]}),new ii({valueHex:new mt({value:[at.fromBigInt(fn(M(r.n,"base64url"))),at.fromBigInt(fn(M(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function dn(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,s=0;for(;o<t;)n[o]=parseInt(e.slice(s,s+2),16),o+=1,s+=2;return n}function fn(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}var cS=16,i0=32,a0=1e4;async function lS(r,e){let t=qe.get(),o=new mt({value:[new at({value:0}),new mt({value:[new qr({value:"1.2.840.113549.1.1.1"}),new yo]}),new Bn({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=pt(cS),a=await t0(uo,e,i,{c:a0,dkLen:i0}),c=pt(16),l=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),d=await t.subtle.encrypt({name:"AES-CBC",iv:c},l,s),u=new mt({value:[new Bn({valueHex:i}),new at({value:a0}),new at({value:i0}),new mt({value:[new qr({value:"1.2.840.113549.2.11"}),new yo]})]}),h=new mt({value:[new qr({value:"1.2.840.113549.1.5.13"}),new mt({value:[new mt({value:[new qr({value:"1.2.840.113549.1.5.12"}),u]}),new mt({value:[new qr({value:"2.16.840.1.101.3.4.1.42"}),new Bn({valueHex:c})]})]})]}),p=new mt({value:[h,new Bn({valueHex:d})]}).toBER(),m=new Uint8Array(p,0,p.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...O(m,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
|
22
|
+
`)}async function c0(r,e){let t=qe.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=M(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=ci(o),{iv:i,salt:a,iterations:c,keySize:l,cipherText:d}=uS(s),u=await t0(uo,e,a,{c,dkLen:l}),h=await t.subtle.importKey("raw",u,"AES-CBC",!1,["decrypt"]),f=Pa(await t.subtle.decrypt({name:"AES-CBC",iv:i},h,d)),{result:p}=ci(f);n=Um(p)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=M(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=ci(o);n=Um(s)}else throw new g("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return l0(n)}function uS(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new g("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=e.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new g("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Pa(s.valueBlock.value[0].getValue()),a=a0,c=i0;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new g("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let l=e.valueBlock.value[1].valueBlock.value[1],d=l.valueBlock.value[0].toString();if(d!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(d!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(d!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(d!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(d!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new g("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let u=Pa(l.valueBlock.value[1].getValue());return{cipherText:Pa(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:u}}function Um(r){return Pa(r.valueBlock.value[2].getValue())}function Pa(r){return new Uint8Array(r,0,r.byteLength)}async function Fm(r){let e=await qe.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await $m(e);return{privateKey:t[0],publicKey:t[1]}}async function u0(r){let t=[await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await dS(r)],n=await $m({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Vm(r,e){let t=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await qe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Km(r,e,t){let n=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return qe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function $m(r){if(r.privateKey==null||r.publicKey==null)throw new g("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([qe.get().subtle.exportKey("jwk",r.privateKey),qe.get().subtle.exportKey("jwk",r.publicKey)])}async function dS(r){return qe.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function au(r){if(r.kty!=="RSA")throw new g("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new g("invalid key modulus","ERR_INVALID_KEY_MODULUS");return M(r.n,"base64url").length*8}var ds=8192,us=class{_key;constructor(e){this._key=e}verify(e,t){return Km(this._key,t,e)}marshal(){return wo.jwkToPkix(this._key)}get bytes(){return $r.encode({Type:Ke.RSA,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}},Eo=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return pt(16)}sign(e){return Vm(this._key,e)}get public(){if(this._publicKey==null)throw new g("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new us(this._publicKey)}marshal(){return wo.jwkToPkcs1(this._key)}get bytes(){return Hr.encode({Type:Ke.RSA,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return O(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return wo.exportToPem(this,e);if(t==="libp2p-key")return ri(this.bytes,e);throw new g(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function l0(r){let e=wo.pkcs1ToJwk(r);if(au(e)>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await u0(e);return new Eo(t.privateKey,t.publicKey)}function hS(r){let e=wo.pkixToJwk(r);if(au(e)>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new us(e)}async function pS(r){if(au(r)>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await u0(r);return new Eo(e.privateKey,e.publicKey)}async function mS(r){if(r>ds)throw new g("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Fm(r);return new Eo(e.privateKey,e.publicKey)}var g0={};pe(g0,{Secp256k1PrivateKey:()=>ps,Secp256k1PublicKey:()=>hs,generateKeyPair:()=>DS,unmarshalSecp256k1PrivateKey:()=>AS,unmarshalSecp256k1PublicKey:()=>IS});var gS=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),bo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xo=new Uint32Array(64),f0=class extends ao{constructor(){super(64,32,8,!1),this.A=bo[0]|0,this.B=bo[1]|0,this.C=bo[2]|0,this.D=bo[3]|0,this.E=bo[4]|0,this.F=bo[5]|0,this.G=bo[6]|0,this.H=bo[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)xo[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let h=xo[u-15],f=xo[u-2],p=Ur(h,7)^Ur(h,18)^h>>>3,m=Ur(f,17)^Ur(f,19)^f>>>10;xo[u]=m+xo[u-7]+p+xo[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){let h=Ur(a,6)^Ur(a,11)^Ur(a,25),f=d+h+il(a,c,l)+gS[u]+xo[u]|0,m=(Ur(n,2)^Ur(n,13)^Ur(n,22))+al(n,o,s)|0;d=l,l=c,c=a,a=i+f|0,i=s,s=o,o=n,n=f+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,o,s,i,a,c,l,d)}roundClean(){xo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var vo=Zs(()=>new f0);function yS(r){let e=va(r);Rr(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:wS,hexToBytes:ES}=ul,fs={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=fs;if(r.length<2||r[0]!==2)throw new e("Invalid signature integer tag");let t=r[1],n=r.subarray(2,t+2);if(!t||n.length!==t)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:wS(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=fs,t=typeof r=="string"?ES(r):r;Js(t);let n=t.length;if(n<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:o,l:s}=fs._parseInt(t.subarray(2)),{d:i,l:a}=fs._parseInt(s);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{let d=l.toString(16);return d.length&1?`0${d}`:d},n=e(t(r.s)),o=e(t(r.r)),s=n.length/2,i=o.length/2,a=t(s),c=t(i);return`30${t(i+s+4)}02${c}${o}02${a}${n}`}},Vn=BigInt(0),_r=BigInt(1),mU=BigInt(2),Hm=BigInt(3),gU=BigInt(4);function bS(r){let e=yS(r),{Fp:t}=e,n=e.toBytes||((p,m,y)=>{let w=m.toAffine();return kn(Uint8Array.from([4]),t.toBytes(w.x),t.toBytes(w.y))}),o=e.fromBytes||(p=>{let m=p.subarray(1),y=t.fromBytes(m.subarray(0,t.BYTES)),w=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:y,y:w}});function s(p){let{a:m,b:y}=e,w=t.sqr(p),b=t.mul(w,p);return t.add(t.add(b,t.mul(p,m)),y)}if(!t.eql(t.sqr(e.Gy),s(e.Gx)))throw new Error("bad generator point: equation left != right");function i(p){return typeof p=="bigint"&&Vn<p&&p<e.n}function a(p){if(!i(p))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(p){let{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:w,n:b}=e;if(m&&typeof p!="bigint"){if(fo(p)&&(p=In(p)),typeof p!="string"||!m.includes(p.length))throw new Error("Invalid key");p=p.padStart(y*2,"0")}let E;try{E=typeof p=="bigint"?p:Dn(Fe("private key",p,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof p}`)}return w&&(E=De(E,b)),a(E),E}let l=new Map;function d(p){if(!(p instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(m,y,w){if(this.px=m,this.py=y,this.pz=w,m==null||!t.isValid(m))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(w==null||!t.isValid(w))throw new Error("z required")}static fromAffine(m){let{x:y,y:w}=m||{};if(!m||!t.isValid(y)||!t.isValid(w))throw new Error("invalid affine point");if(m instanceof u)throw new Error("projective point not allowed");let b=E=>t.eql(E,t.ZERO);return b(y)&&b(w)?u.ZERO:new u(y,w,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){let y=t.invertBatch(m.map(w=>w.pz));return m.map((w,b)=>w.toAffine(y[b])).map(u.fromAffine)}static fromHex(m){let y=u.fromAffine(o(Fe("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return u.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:m,y}=this.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not FE");let w=t.sqr(y),b=s(m);if(!t.eql(w,b))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){d(m);let{px:y,py:w,pz:b}=this,{px:E,py:x,pz:v}=m,I=t.eql(t.mul(y,v),t.mul(E,b)),S=t.eql(t.mul(w,v),t.mul(x,b));return I&&S}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){let{a:m,b:y}=e,w=t.mul(y,Hm),{px:b,py:E,pz:x}=this,v=t.ZERO,I=t.ZERO,S=t.ZERO,R=t.mul(b,b),T=t.mul(E,E),P=t.mul(x,x),N=t.mul(b,E);return N=t.add(N,N),S=t.mul(b,x),S=t.add(S,S),v=t.mul(m,S),I=t.mul(w,P),I=t.add(v,I),v=t.sub(T,I),I=t.add(T,I),I=t.mul(v,I),v=t.mul(N,v),S=t.mul(w,S),P=t.mul(m,P),N=t.sub(R,P),N=t.mul(m,N),N=t.add(N,S),S=t.add(R,R),R=t.add(S,R),R=t.add(R,P),R=t.mul(R,N),I=t.add(I,R),P=t.mul(E,x),P=t.add(P,P),R=t.mul(P,N),v=t.sub(v,R),S=t.mul(P,T),S=t.add(S,S),S=t.add(S,S),new u(v,I,S)}add(m){d(m);let{px:y,py:w,pz:b}=this,{px:E,py:x,pz:v}=m,I=t.ZERO,S=t.ZERO,R=t.ZERO,T=e.a,P=t.mul(e.b,Hm),N=t.mul(y,E),B=t.mul(w,x),k=t.mul(b,v),X=t.add(y,w),D=t.add(E,x);X=t.mul(X,D),D=t.add(N,B),X=t.sub(X,D),D=t.add(y,b);let L=t.add(E,v);return D=t.mul(D,L),L=t.add(N,k),D=t.sub(D,L),L=t.add(w,b),I=t.add(x,v),L=t.mul(L,I),I=t.add(B,k),L=t.sub(L,I),R=t.mul(T,D),I=t.mul(P,k),R=t.add(I,R),I=t.sub(B,R),R=t.add(B,R),S=t.mul(I,R),B=t.add(N,N),B=t.add(B,N),k=t.mul(T,k),D=t.mul(P,D),B=t.add(B,k),k=t.sub(N,k),k=t.mul(T,k),D=t.add(D,k),N=t.mul(B,D),S=t.add(S,N),N=t.mul(L,D),I=t.mul(X,I),I=t.sub(I,N),N=t.mul(X,B),R=t.mul(L,R),R=t.add(R,N),new u(I,S,R)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return f.wNAFCached(this,l,m,y=>{let w=t.invertBatch(y.map(b=>b.pz));return y.map((b,E)=>b.toAffine(w[E])).map(u.fromAffine)})}multiplyUnsafe(m){let y=u.ZERO;if(m===Vn)return y;if(a(m),m===_r)return this;let{endo:w}=e;if(!w)return f.unsafeLadder(this,m);let{k1neg:b,k1:E,k2neg:x,k2:v}=w.splitScalar(m),I=y,S=y,R=this;for(;E>Vn||v>Vn;)E&_r&&(I=I.add(R)),v&_r&&(S=S.add(R)),R=R.double(),E>>=_r,v>>=_r;return b&&(I=I.negate()),x&&(S=S.negate()),S=new u(t.mul(S.px,w.beta),S.py,S.pz),I.add(S)}multiply(m){a(m);let y=m,w,b,{endo:E}=e;if(E){let{k1neg:x,k1:v,k2neg:I,k2:S}=E.splitScalar(y),{p:R,f:T}=this.wNAF(v),{p:P,f:N}=this.wNAF(S);R=f.constTimeNegate(x,R),P=f.constTimeNegate(I,P),P=new u(t.mul(P.px,E.beta),P.py,P.pz),w=R.add(P),b=T.add(N)}else{let{p:x,f:v}=this.wNAF(y);w=x,b=v}return u.normalizeZ([w,b])[0]}multiplyAndAddUnsafe(m,y,w){let b=u.BASE,E=(v,I)=>I===Vn||I===_r||!v.equals(b)?v.multiplyUnsafe(I):v.multiply(I),x=E(this,y).add(E(m,w));return x.is0()?void 0:x}toAffine(m){let{px:y,py:w,pz:b}=this,E=this.is0();m==null&&(m=E?t.ONE:t.inv(b));let x=t.mul(y,m),v=t.mul(w,m),I=t.mul(b,m);if(E)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x,y:v}}isTorsionFree(){let{h:m,isTorsionFree:y}=e;if(m===_r)return!0;if(y)return y(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:m,clearCofactor:y}=e;return m===_r?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),n(u,this,m)}toHex(m=!0){return In(this.toRawBytes(m))}}u.BASE=new u(e.Gx,e.Gy,t.ONE),u.ZERO=new u(t.ZERO,t.ONE,t.ZERO);let h=e.nBitLength,f=hl(u,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function xS(r){let e=va(r);return Rr(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function qm(r){let e=xS(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(D){return Vn<D&&D<t.ORDER}function a(D){return De(D,n)}function c(D){return dl(D,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:d,weierstrassEquation:u,isWithinCurveOrder:h}=bS({...e,toBytes(D,L,$){let C=L.toAffine(),A=t.toBytes(C.x),U=kn;return $?U(Uint8Array.from([L.hasEvenY()?2:3]),A):U(Uint8Array.from([4]),A,t.toBytes(C.y))},fromBytes(D){let L=D.length,$=D[0],C=D.subarray(1);if(L===o&&($===2||$===3)){let A=Dn(C);if(!i(A))throw new Error("Point is not on curve");let U=u(A),V;try{V=t.sqrt(U)}catch(ie){let de=ie instanceof Error?": "+ie.message:"";throw new Error("Point is not on curve"+de)}let q=(V&_r)===_r;return($&1)===1!==q&&(V=t.neg(V)),{x:A,y:V}}else if(L===s&&$===4){let A=t.fromBytes(C.subarray(0,t.BYTES)),U=t.fromBytes(C.subarray(t.BYTES,2*t.BYTES));return{x:A,y:U}}else throw new Error(`Point of length ${L} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),f=D=>In(ho(D,e.nByteLength));function p(D){let L=n>>_r;return D>L}function m(D){return p(D)?a(-D):D}let y=(D,L,$)=>Dn(D.slice(L,$));class w{constructor(L,$,C){this.r=L,this.s=$,this.recovery=C,this.assertValidity()}static fromCompact(L){let $=e.nByteLength;return L=Fe("compactSignature",L,$*2),new w(y(L,0,$),y(L,$,2*$))}static fromDER(L){let{r:$,s:C}=fs.toSig(Fe("DER",L));return new w($,C)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(L){return new w(this.r,this.s,L)}recoverPublicKey(L){let{r:$,s:C,recovery:A}=this,U=S(Fe("msgHash",L));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let V=A===2||A===3?$+e.n:$;if(V>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let q=A&1?"03":"02",se=l.fromHex(q+f(V)),ie=c(V),de=a(-U*ie),ae=a(C*ie),ue=l.BASE.multiplyAndAddUnsafe(se,de,ae);if(!ue)throw new Error("point at infinify");return ue.assertValidity(),ue}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return is(this.toDERHex())}toDERHex(){return fs.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return is(this.toCompactHex())}toCompactHex(){return f(this.r)+f(this.s)}}let b={isValidPrivateKey(D){try{return d(D),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let D=Gh(e.n);return A8(e.randomBytes(D),e.n)},precompute(D=8,L=l.BASE){return L._setWindowSize(D),L.multiply(BigInt(3)),L}};function E(D,L=!0){return l.fromPrivateKey(D).toRawBytes(L)}function x(D){let L=fo(D),$=typeof D=="string",C=(L||$)&&D.length;return L?C===o||C===s:$?C===2*o||C===2*s:D instanceof l}function v(D,L,$=!0){if(x(D))throw new Error("first arg must be private key");if(!x(L))throw new Error("second arg must be public key");return l.fromHex(L).multiply(d(D)).toRawBytes($)}let I=e.bits2int||function(D){let L=Dn(D),$=D.length*8-e.nBitLength;return $>0?L>>BigInt($):L},S=e.bits2int_modN||function(D){return a(I(D))},R=xa(e.nBitLength);function T(D){if(typeof D!="bigint")throw new Error("bigint expected");if(!(Vn<=D&&D<R))throw new Error(`bigint expected < 2^${e.nBitLength}`);return ho(D,e.nByteLength)}function P(D,L,$=N){if(["recovered","canonical"].some(Le=>Le in $))throw new Error("sign() legacy options not supported");let{hash:C,randomBytes:A}=e,{lowS:U,prehash:V,extraEntropy:q}=$;U==null&&(U=!0),D=Fe("msgHash",D),V&&(D=Fe("prehashed msgHash",C(D)));let se=S(D),ie=d(L),de=[T(ie),T(se)];if(q!=null&&q!==!1){let Le=q===!0?A(t.BYTES):q;de.push(Fe("extraEntropy",Le))}let ae=kn(...de),ue=se;function Me(Le){let yt=I(Le);if(!h(yt))return;let wt=c(yt),lt=l.BASE.multiply(yt).toAffine(),Tt=a(lt.x);if(Tt===Vn)return;let xn=a(wt*a(ue+Tt*ie));if(xn===Vn)return;let Go=(lt.x===Tt?0:2)|Number(lt.y&_r),fa=xn;return U&&p(xn)&&(fa=m(xn),Go^=1),new w(Tt,fa,Go)}return{seed:ae,k2sig:Me}}let N={lowS:e.lowS,prehash:!1},B={lowS:e.lowS,prehash:!1};function k(D,L,$=N){let{seed:C,k2sig:A}=P(D,L,$),U=e;return Vh(U.hash.outputLen,U.nByteLength,U.hmac)(C,A)}l.BASE._setWindowSize(8);function X(D,L,$,C=B){let A=D;if(L=Fe("msgHash",L),$=Fe("publicKey",$),"strict"in C)throw new Error("options.strict was renamed to lowS");let{lowS:U,prehash:V}=C,q,se;try{if(typeof A=="string"||fo(A))try{q=w.fromDER(A)}catch(lt){if(!(lt instanceof fs.Err))throw lt;q=w.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){let{r:lt,s:Tt}=A;q=new w(lt,Tt)}else throw new Error("PARSE");se=l.fromHex($)}catch(lt){if(lt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(U&&q.hasHighS())return!1;V&&(L=e.hash(L));let{r:ie,s:de}=q,ae=S(L),ue=c(de),Me=a(ae*ue),Le=a(ie*ue),yt=l.BASE.multiplyAndAddUnsafe(se,Me,Le)?.toAffine();return yt?a(yt.x)===ie:!1}return{CURVE:e,getPublicKey:E,getSharedSecret:v,sign:k,verify:X,ProjectivePoint:l,Signature:w,utils:b}}function vS(r){return{hash:r,hmac:(e,...t)=>po(r,e,sl(...t)),randomBytes:ss}}function Gm(r,e){let t=n=>qm({...r,...vS(n)});return Object.freeze({...t(e),create:t})}var Ym=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Wm=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),RS=BigInt(1),h0=BigInt(2),zm=(r,e)=>(r+e/h0)/e;function SS(r){let e=Ym,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,u=Ve(d,t,e)*d%e,h=Ve(u,t,e)*d%e,f=Ve(h,h0,e)*l%e,p=Ve(f,o,e)*f%e,m=Ve(p,s,e)*p%e,y=Ve(m,a,e)*m%e,w=Ve(y,c,e)*y%e,b=Ve(w,a,e)*m%e,E=Ve(b,t,e)*d%e,x=Ve(E,i,e)*p%e,v=Ve(x,n,e)*l%e,I=Ve(v,h0,e);if(!p0.eql(p0.sqr(I),r))throw new Error("Cannot find square root");return I}var p0=fl(Ym,void 0,void 0,{sqrt:SS}),Wr=Gm({a:BigInt(0),b:BigInt(7),Fp:p0,n:Wm,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Wm,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-RS*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=zm(s*r,e),c=zm(-n*r,e),l=De(r-a*t-c*o,e),d=De(-a*n-c*s,e),u=l>i,h=d>i;if(u&&(l=e-l),h&&(d=e-d),l>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:h,k2:d}}}},vo),_U=BigInt(0);var AU=Wr.ProjectivePoint;function Xm(){return Wr.utils.randomPrivateKey()}function Qm(r,e){let t=Ne.digest(e instanceof Uint8Array?e:e.subarray());if(vr(t))return t.then(({digest:n})=>Wr.sign(n,r).toDERRawBytes()).catch(n=>{throw new g(String(n),"ERR_INVALID_INPUT")});try{return Wr.sign(t.digest,r).toDERRawBytes()}catch(n){throw new g(String(n),"ERR_INVALID_INPUT")}}function jm(r,e,t){let n=Ne.digest(t instanceof Uint8Array?t:t.subarray());if(vr(n))return n.then(({digest:o})=>Wr.verify(e,o,r)).catch(o=>{throw new g(String(o),"ERR_INVALID_INPUT")});try{return Wr.verify(e,n.digest,r)}catch(o){throw new g(String(o),"ERR_INVALID_INPUT")}}function Zm(r){return Wr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Jm(r){try{Wr.getPublicKey(r,!0)}catch(e){throw new g(String(e),"ERR_INVALID_PRIVATE_KEY")}}function m0(r){try{Wr.ProjectivePoint.fromHex(r)}catch(e){throw new g(String(e),"ERR_INVALID_PUBLIC_KEY")}}function e6(r){try{return Wr.getPublicKey(r,!0)}catch(e){throw new g(String(e),"ERR_INVALID_PRIVATE_KEY")}}var hs=class{_key;constructor(e){m0(e),this._key=e}verify(e,t){return jm(this._key,t,e)}marshal(){return Zm(this._key)}get bytes(){return $r.encode({Type:Ke.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}async hash(){let e=Ne.digest(this.bytes),t;return vr(e)?{bytes:t}=await e:t=e.bytes,t}},ps=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??e6(e),Jm(this._key),m0(this._publicKey)}sign(e){return Qm(this._key,e)}get public(){return new hs(this._publicKey)}marshal(){return this._key}get bytes(){return Hr.encode({Type:Ke.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Z(this.bytes,e.bytes)}hash(){let e=Ne.digest(this.bytes);return vr(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return O(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return ri(this.bytes,e);throw new g(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function AS(r){return new ps(r)}function IS(r){return new hs(r)}async function DS(){let r=Xm();return new ps(r)}var Kn={rsa:d0,ed25519:Jh,secp256k1:g0};function y0(r){let e=Object.keys(Kn).join(" / ");return new g(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function w0(r){if(r=r.toLowerCase(),r==="rsa"||r==="ed25519"||r==="secp256k1")return Kn[r];throw y0(r)}async function Oa(r,e){return w0(r).generateKeyPair(e??2048)}async function TS(r,e,t){if(r.toLowerCase()!=="ed25519")throw new g("Seed key derivation is unimplemented for RSA or secp256k1","ERR_UNSUPPORTED_KEY_DERIVATION_TYPE");return Zh(e)}function zr(r){let e=$r.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Ke.RSA:return Kn.rsa.unmarshalRsaPublicKey(t);case Ke.Ed25519:return Kn.ed25519.unmarshalEd25519PublicKey(t);case Ke.Secp256k1:return Kn.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw y0(e.Type??"unknown")}}function E0(r,e){return e=(e??"rsa").toLowerCase(),w0(e),r.bytes}async function Ar(r){let e=Hr.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case Ke.RSA:return Kn.rsa.unmarshalRsaPrivateKey(t);case Ke.Ed25519:return Kn.ed25519.unmarshalEd25519PrivateKey(t);case Ke.Secp256k1:return Kn.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw y0(e.Type??"RSA")}}function b0(r,e){return e=(e??"rsa").toLowerCase(),w0(e),r.bytes}async function li(r,e){try{let t=await G8(r,e);return await Ar(t)}catch{}if(!r.includes("BEGIN"))throw new g("Encrypted key was not a libp2p-key or a PEM file","ERR_INVALID_IMPORT_FORMAT");return c0(r,e)}var Ba=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),Ro=new Uint32Array(80),x0=class extends ao{constructor(){super(64,20,8,!1),this.A=Ba[0]|0,this.B=Ba[1]|0,this.C=Ba[2]|0,this.D=Ba[3]|0,this.E=Ba[4]|0}get(){let{A:e,B:t,C:n,D:o,E:s}=this;return[e,t,n,o,s]}set(e,t,n,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0}process(e,t){for(let c=0;c<16;c++,t+=4)Ro[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Ro[c]=ol(Ro[c-3]^Ro[c-8]^Ro[c-14]^Ro[c-16],1);let{A:n,B:o,C:s,D:i,E:a}=this;for(let c=0;c<80;c++){let l,d;c<20?(l=il(o,s,i),d=1518500249):c<40?(l=o^s^i,d=1859775393):c<60?(l=al(o,s,i),d=2400959708):(l=o^s^i,d=3395469782);let u=ol(n,5)+l+a+d+Ro[c]|0;a=i,i=s,s=ol(o,30),o=n,n=u}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,this.set(n,o,s,i,a)}roundClean(){Ro.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}},t6=Zs(()=>new x0);var r6={sha1:t6,"sha2-256":vo,"sha2-512":uo};function Ma(r,e,t,n,o){if(o!=="sha1"&&o!=="sha2-256"&&o!=="sha2-512"){let a=Object.keys(r6).join(" / ");throw new g(`Hash '${o}' is unknown or not supported. Must be ${a}`,"ERR_UNSUPPORTED_HASH_TYPE")}let s=r6[o],i=Q8(s,r,e,{c:t,dkLen:n});return st.encode(i).substring(1)}var v0=class extends it{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Fa(r){let{name:e,metrics:t}=r,n;return t!=null?n=new v0({name:e,metrics:t}):n=new it,n}var $n=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=st.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=st.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=st.encode(e.multihash.bytes);this.blocks.set(n,t)}};function kS(r){let e=new Uint8Array(r.reduce((n,o)=>n+Se(o),0)),t=0;for(let n of r)e=$e(n,e,t),t+=Se(n);return e}var i6=kS;function R0(r){return i6([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var uu=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t=new $n,n=new Set;for(let[o,s]of this.wants.entries())try{let i=await this.blockstore.get(s.cid,e);s.wantType===rt.WantHave?i.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",s.cid),n.add(o),t.addBlock(s.cid,{data:i,prefix:R0(s.cid)})):(this.log("sending have for %c",s.cid),t.addBlockPresence(s.cid,{cid:s.cid.bytes,type:xr.HaveBlock})):(this.log("sending block for %c",s.cid),n.add(o),t.addBlock(s.cid,{data:i,prefix:R0(s.cid)}))}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i;if(this.log("do not have block for %c",s.cid),!s.sendDontHave||s.sentDontHave===!0)continue;s.sentDontHave=!0,t.addBlockPresence(s.cid,{cid:s.cid.bytes,type:xr.DontHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((o,s)=>o+s.data.byteLength,0));for(let o of n)this.wants.delete(o)}}};var du=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=Fa({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new uu({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((o,s)=>o+s.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let o of t.wantlist.entries){let s=le.decode(o.cid),i=O(s.multihash.bytes,"base64");o.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,s),n.wants.delete(i)):(o.wantType===rt.WantHave?this.log("peer %p wanted block presence for %c",e,s):this.log("peer %p wanted block for %c",e,s),n.wants.set(i,{cid:s,priority:o.priority,wantType:o.wantType??rt.WantBlock,sendDontHave:o.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=O(e.multihash.bytes,"base64"),o=[];for(let s of this.ledgerMap.values())s.wants.has(n)&&o.push(s);await Promise.all(o.map(async s=>s.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};var sr=Qe(d6(),1);sr.default.formatters.b=r=>r==null?"undefined":Ye.baseEncode(r);sr.default.formatters.t=r=>r==null?"undefined":ut.baseEncode(r);sr.default.formatters.m=r=>r==null?"undefined":st.baseEncode(r);sr.default.formatters.p=r=>r==null?"undefined":r.toString();sr.default.formatters.c=r=>r==null?"undefined":r.toString();sr.default.formatters.k=r=>r==null?"undefined":r.toString();sr.default.formatters.a=r=>r==null?"undefined":r.toString();function HS(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function So(){return{forComponent(r){return ir(r)}}}function ir(r){let e=HS(`${r}:trace`);return sr.default.enabled(`${r}:trace`)&&sr.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,sr.default)(`${r}:trace`)),Object.assign((0,sr.default)(r),{error:(0,sr.default)(`${r}:error`),trace:e})}var _0=Qe(h6(),1);var _o=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},A0=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},p6=r=>globalThis.DOMException===void 0?new A0(r):new DOMException(r),m6=r=>{let e=r.reason===void 0?p6("This operation was aborted."):r.reason;return e instanceof Error?e:p6(e)};function Yr(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,c=new Promise((l,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&d(m6(h)),h.addEventListener("abort",()=>{d(m6(h))})}if(t===Number.POSITIVE_INFINITY){r.then(l,d);return}let u=new _o;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(h){d(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?d(o):(u.message=o??`Promise timed out after ${t} milliseconds`,d(u))},t),(async()=>{try{l(await r)}catch(h){d(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}function I0(r,e,t){let n=0,o=r.length;for(;o>0;){let s=Math.trunc(o/2),i=n+s;t(r[i],e)<=0?(n=++i,o-=s+1):o=s}return n}var Ka=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,run:e};if(this.size&&this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let o=I0(this.#e,n,(s,i)=>i.priority-s.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var Ir=class extends _0.default{#e;#t;#r=0;#o;#a;#l=0;#s;#u;#n;#m;#i=0;#d;#c;#g;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ka,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#o=e.intervalCap,this.#a=e.interval,this.#n=new e.queueClass,this.#m=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#g=e.throwOnTimeout===!0,this.#c=e.autoStart===!1}get#E(){return this.#t||this.#r<this.#o}get#b(){return this.#i<this.#d}#x(){this.#i--,this.#f(),this.emit("next")}#v(){this.#w(),this.#y(),this.#u=void 0}get#R(){let e=Date.now();if(this.#s===void 0){let t=this.#l-e;if(t<0)this.#r=this.#e?this.#i:0;else return this.#u===void 0&&(this.#u=setTimeout(()=>{this.#v()},t)),!0}return!1}#f(){if(this.#n.size===0)return this.#s&&clearInterval(this.#s),this.#s=void 0,this.emit("empty"),this.#i===0&&this.emit("idle"),!1;if(!this.#c){let e=!this.#R;if(this.#E&&this.#b){let t=this.#n.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#s!==void 0||(this.#s=setInterval(()=>{this.#w()},this.#a),this.#l=Date.now()+this.#a)}#w(){this.#r===0&&this.#i===0&&this.#s&&(clearInterval(this.#s),this.#s=void 0),this.#r=this.#e?this.#i:0,this.#h()}#h(){for(;this.#f(););}get concurrency(){return this.#d}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#d=e,this.#h()}async#S(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#g,...t},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#i++,this.#r++;try{t.signal?.throwIfAborted();let s=e({signal:t.signal});t.timeout&&(s=Yr(Promise.resolve(s),{milliseconds:t.timeout})),t.signal&&(s=Promise.race([s,this.#S(t.signal)]));let i=await s;n(i),this.emit("completed",i)}catch(s){if(s instanceof _o&&!t.throwOnTimeout){n();return}o(s),this.emit("error",s)}finally{this.#x()}},t),this.emit("add"),this.#f()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#c?(this.#c=!1,this.#h(),this):this}pause(){this.#c=!0}clear(){this.#n=new this.#m}async onEmpty(){this.#n.size!==0&&await this.#p("empty")}async onSizeLessThan(e){this.#n.size<e||await this.#p("next",()=>this.#n.size<e)}async onIdle(){this.#i===0&&this.#n.size===0||await this.#p("idle")}async#p(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#n.size}sizeBy(e){return this.#n.filter(e).length}get pending(){return this.#i}get isPaused(){return this.#c}};function mu(r){let e=[ar.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var D0=60;function gu(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:ar[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:ar[e.type],TTL:e.TTL??e.ttl??D0,data:e.data instanceof Uint8Array?O(e.data):e.data}))}}var WS=4;function T0(r,e={}){let t=new Ir({concurrency:e.queryConcurrency??WS});return async(n,o={})=>{let s=new URLSearchParams;s.set("name",n),mu(o.types).forEach(a=>{s.append("type",ar[a])}),o.onProgress?.(new me("dns:query",{detail:n}));let i=await t.add(async()=>{let a=await fetch(`${r}?${s}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=gu(await a.json());return o.onProgress?.(new me("dns:response",{detail:c})),c},{signal:o.signal});if(i==null)throw new Error("No DNS response received");return i}}function g6(){return[T0("https://cloudflare-dns.com/dns-query"),T0("https://dns.google/resolve")]}var w6=Qe(k0(),1);var C0=class{lru;constructor(e){this.lru=(0,w6.default)(e)}get(e,t){let n=!0,o=[];for(let s of t){let i=this.getAnswers(e,s);if(i.length===0){n=!1;break}o.push(...i)}if(n)return gu({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let s=o.filter(i=>i.expires>Date.now()).map(({expires:i,value:a})=>({...a,TTL:Math.round((i-Date.now())/1e3),type:ar[a.type]}));return s.length===0&&this.lru.remove(n),s}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??D0)*1e3,value:t}),this.lru.set(n,o)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function E6(r){return new C0(r)}var zS=1e3,yu=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=E6(e.cacheSize??zS),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=g6())}async query(e,t={}){let n=mu(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new me("dns:cache",{detail:o})),o;let s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of i){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let d of l.Answer)this.cache.add(e,d);return l}catch(l){a.push(l),t.onProgress?.(new me("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var ar;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(ar||(ar={}));function wu(r={}){return new yu(r)}var YS=["string","number","bigint","symbol"],XS=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function b6(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(YS.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(QS(r))return"Buffer";let t=jS(r);return t||"Object"}function QS(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function jS(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(XS.includes(e))return e}var _=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};_.uint=new _(0,"uint",!0);_.negint=new _(1,"negint",!0);_.bytes=new _(2,"bytes",!0);_.string=new _(3,"string",!0);_.array=new _(4,"array",!1);_.map=new _(5,"map",!1);_.tag=new _(6,"tag",!1);_.float=new _(7,"float",!0);_.false=new _(7,"false",!0);_.true=new _(7,"true",!0);_.null=new _(7,"null",!0);_.undefined=new _(7,"undefined",!0);_.break=new _(7,"break",!0);var F=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var hi=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ZS=new TextDecoder,JS=new TextEncoder;function Eu(r){return hi&&globalThis.Buffer.isBuffer(r)}function $a(r){return r instanceof Uint8Array?Eu(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var S6=hi?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):v6(r,e,t):(r,e,t)=>t-e>64?ZS.decode(r.subarray(e,t)):v6(r,e,t),bu=hi?r=>r.length>64?globalThis.Buffer.from(r):x6(r):r=>r.length>64?JS.encode(r):x6(r),hn=r=>Uint8Array.from(r),pi=hi?(r,e,t)=>Eu(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),_6=hi?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),$a(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},A6=hi?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function I6(r,e){if(Eu(r)&&Eu(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function x6(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}function v6(r,e,t){let n=[];for(;e<t;){let o=r[e],s=null,i=o>239?4:o>223?3:o>191?2:1;if(e+i<=t){let a,c,l,d;switch(i){case 1:o<128&&(s=o);break;case 2:a=r[e+1],(a&192)===128&&(d=(o&31)<<6|a&63,d>127&&(s=d));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(d=(o&15)<<12|(a&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(d=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,d>65535&&d<1114112&&(s=d))}}s===null?(s=65533,i=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),e+=i}return N0(n)}var R6=4096;function N0(r){let e=r.length;if(e<=R6)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=R6));return t}var e_=256,Ha=class{constructor(e=e_){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=A6(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=pi(n,0,this.cursor)}else t=_6(this.chunks,this.cursor);return e&&this.reset(),t}};var Q="CBOR decode error:",mi="CBOR encode error:",qa=[];qa[23]=1;qa[24]=2;qa[25]=3;qa[26]=5;qa[27]=9;function Hn(r,e,t){if(r.length-e<t)throw new Error(`${Q} not enough data for type`)}var gt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function cr(r,e,t){Hn(r,e,1);let n=r[e];if(t.strict===!0&&n<gt[0])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);return n}function lr(r,e,t){Hn(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<gt[1])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);return n}function ur(r,e,t){Hn(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<gt[2])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);return n}function dr(r,e,t){Hn(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],s=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&s<gt[3])throw new Error(`${Q} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${Q} integers outside of the safe integer range are not supported`)}function D6(r,e,t,n){return new F(_.uint,cr(r,e+1,n),2)}function T6(r,e,t,n){return new F(_.uint,lr(r,e+1,n),3)}function k6(r,e,t,n){return new F(_.uint,ur(r,e+1,n),5)}function C6(r,e,t,n){return new F(_.uint,dr(r,e+1,n),9)}function Dr(r,e){return bt(r,0,e.value)}function bt(r,e,t){if(t<gt[0]){let n=Number(t);r.push([e|n])}else if(t<gt[1]){let n=Number(t);r.push([e|24,n])}else if(t<gt[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<gt[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<gt[4]){let o=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=s&255,s=s>>8,o[7]=s&255,s=s>>8,o[6]=s&255,s=s>>8,o[5]=s&255,o[4]=i&255,i=i>>8,o[3]=i&255,i=i>>8,o[2]=i&255,i=i>>8,o[1]=i&255,r.push(o)}else throw new Error(`${Q} encountered BigInt larger than allowable range`)}}Dr.encodedSize=function(e){return bt.encodedSize(e.value)};bt.encodedSize=function(e){return e<gt[0]?1:e<gt[1]?2:e<gt[2]?3:e<gt[3]?5:9};Dr.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function N6(r,e,t,n){return new F(_.negint,-1-cr(r,e+1,n),2)}function L6(r,e,t,n){return new F(_.negint,-1-lr(r,e+1,n),3)}function P6(r,e,t,n){return new F(_.negint,-1-ur(r,e+1,n),5)}var L0=BigInt(-1),O6=BigInt(1);function B6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o!="bigint"){let s=-1-o;if(s>=Number.MIN_SAFE_INTEGER)return new F(_.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${Q} integers outside of the safe integer range are not supported`);return new F(_.negint,L0-BigInt(o),9)}function xu(r,e){let t=e.value,n=typeof t=="bigint"?t*L0-O6:t*-1-1;bt(r,e.type.majorEncoded,n)}xu.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*L0-O6:t*-1-1;return n<gt[0]?1:n<gt[1]?2:n<gt[2]?3:n<gt[3]?5:9};xu.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Ga(r,e,t,n){Hn(r,e,t+n);let o=pi(r,e+t,e+t+n);return new F(_.bytes,o,t+n)}function M6(r,e,t,n){return Ga(r,e,1,t)}function U6(r,e,t,n){return Ga(r,e,2,cr(r,e+1,n))}function F6(r,e,t,n){return Ga(r,e,3,lr(r,e+1,n))}function V6(r,e,t,n){return Ga(r,e,5,ur(r,e+1,n))}function K6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer bytes lengths not supported`);return Ga(r,e,9,o)}function vu(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===_.string?bu(r.value):r.value),r.encodedBytes}function gi(r,e){let t=vu(e);bt(r,e.type.majorEncoded,t.length),r.push(t)}gi.encodedSize=function(e){let t=vu(e);return bt.encodedSize(t.length)+t.length};gi.compareTokens=function(e,t){return r_(vu(e),vu(t))};function r_(r,e){return r.length<e.length?-1:r.length>e.length?1:I6(r,e)}function Wa(r,e,t,n,o){let s=t+n;Hn(r,e,s);let i=new F(_.string,S6(r,e+t,e+s),s);return o.retainStringBytes===!0&&(i.byteValue=pi(r,e+t,e+s)),i}function $6(r,e,t,n){return Wa(r,e,1,t,n)}function H6(r,e,t,n){return Wa(r,e,2,cr(r,e+1,n),n)}function q6(r,e,t,n){return Wa(r,e,3,lr(r,e+1,n),n)}function G6(r,e,t,n){return Wa(r,e,5,ur(r,e+1,n),n)}function W6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer string lengths not supported`);return Wa(r,e,9,o,n)}var z6=gi;function yi(r,e,t,n){return new F(_.array,n,t)}function Y6(r,e,t,n){return yi(r,e,1,t)}function X6(r,e,t,n){return yi(r,e,2,cr(r,e+1,n))}function Q6(r,e,t,n){return yi(r,e,3,lr(r,e+1,n))}function j6(r,e,t,n){return yi(r,e,5,ur(r,e+1,n))}function Z6(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer array lengths not supported`);return yi(r,e,9,o)}function J6(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Q} indefinite length items not allowed`);return yi(r,e,1,1/0)}function Ru(r,e){bt(r,_.array.majorEncoded,e.value)}Ru.compareTokens=Dr.compareTokens;Ru.encodedSize=function(e){return bt.encodedSize(e.value)};function wi(r,e,t,n){return new F(_.map,n,t)}function e5(r,e,t,n){return wi(r,e,1,t)}function t5(r,e,t,n){return wi(r,e,2,cr(r,e+1,n))}function r5(r,e,t,n){return wi(r,e,3,lr(r,e+1,n))}function n5(r,e,t,n){return wi(r,e,5,ur(r,e+1,n))}function o5(r,e,t,n){let o=dr(r,e+1,n);if(typeof o=="bigint")throw new Error(`${Q} 64-bit integer map lengths not supported`);return wi(r,e,9,o)}function s5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Q} indefinite length items not allowed`);return wi(r,e,1,1/0)}function Su(r,e){bt(r,_.map.majorEncoded,e.value)}Su.compareTokens=Dr.compareTokens;Su.encodedSize=function(e){return bt.encodedSize(e.value)};function i5(r,e,t,n){return new F(_.tag,t,1)}function a5(r,e,t,n){return new F(_.tag,cr(r,e+1,n),2)}function c5(r,e,t,n){return new F(_.tag,lr(r,e+1,n),3)}function l5(r,e,t,n){return new F(_.tag,ur(r,e+1,n),5)}function u5(r,e,t,n){return new F(_.tag,dr(r,e+1,n),9)}function _u(r,e){bt(r,_.tag.majorEncoded,e.value)}_u.compareTokens=Dr.compareTokens;_u.encodedSize=function(e){return bt.encodedSize(e.value)};var c_=20,l_=21,u_=22,d_=23;function d5(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${Q} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new F(_.null,null,1):new F(_.undefined,void 0,1)}function f5(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${Q} indefinite length items not allowed`);return new F(_.break,void 0,1)}function P0(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${Q} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${Q} Infinity values are not supported`)}return new F(_.float,r,e)}function h5(r,e,t,n){return P0(O0(r,e+1),3,n)}function p5(r,e,t,n){return P0(B0(r,e+1),5,n)}function m5(r,e,t,n){return P0(E5(r,e+1),9,n)}function Au(r,e,t){let n=e.value;if(n===!1)r.push([_.float.majorEncoded|c_]);else if(n===!0)r.push([_.float.majorEncoded|l_]);else if(n===null)r.push([_.float.majorEncoded|u_]);else if(n===void 0)r.push([_.float.majorEncoded|d_]);else{let o,s=!1;(!t||t.float64!==!0)&&(y5(n),o=O0(Xr,1),n===o||Number.isNaN(n)?(Xr[0]=249,r.push(Xr.slice(0,3)),s=!0):(w5(n),o=B0(Xr,1),n===o&&(Xr[0]=250,r.push(Xr.slice(0,5)),s=!0))),s||(f_(n),o=E5(Xr,1),Xr[0]=251,r.push(Xr.slice(0,9)))}}Au.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){y5(n);let o=O0(Xr,1);if(n===o||Number.isNaN(n))return 3;if(w5(n),o=B0(Xr,1),n===o)return 5}return 9};var g5=new ArrayBuffer(9),Tr=new DataView(g5,1),Xr=new Uint8Array(g5,0);function y5(r){if(r===1/0)Tr.setUint16(0,31744,!1);else if(r===-1/0)Tr.setUint16(0,64512,!1);else if(Number.isNaN(r))Tr.setUint16(0,32256,!1);else{Tr.setFloat32(0,r);let e=Tr.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Tr.setUint16(0,31744,!1);else if(t===0)Tr.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Tr.setUint16(0,0):o<-14?Tr.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Tr.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function O0(r,e){if(r.length-e<2)throw new Error(`${Q} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,s;return n===0?s=o*2**-24:n!==31?s=(o+1024)*2**(n-25):s=o===0?1/0:NaN,t&32768?-s:s}function w5(r){Tr.setFloat32(0,r,!1)}function B0(r,e){if(r.length-e<4)throw new Error(`${Q} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function f_(r){Tr.setFloat64(0,r,!1)}function E5(r,e){if(r.length-e<8)throw new Error(`${Q} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Au.compareTokens=Dr.compareTokens;function _e(r,e,t){throw new Error(`${Q} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Iu(r){return()=>{throw new Error(`${Q} ${r}`)}}var K=[];for(let r=0;r<=23;r++)K[r]=_e;K[24]=D6;K[25]=T6;K[26]=k6;K[27]=C6;K[28]=_e;K[29]=_e;K[30]=_e;K[31]=_e;for(let r=32;r<=55;r++)K[r]=_e;K[56]=N6;K[57]=L6;K[58]=P6;K[59]=B6;K[60]=_e;K[61]=_e;K[62]=_e;K[63]=_e;for(let r=64;r<=87;r++)K[r]=M6;K[88]=U6;K[89]=F6;K[90]=V6;K[91]=K6;K[92]=_e;K[93]=_e;K[94]=_e;K[95]=Iu("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)K[r]=$6;K[120]=H6;K[121]=q6;K[122]=G6;K[123]=W6;K[124]=_e;K[125]=_e;K[126]=_e;K[127]=Iu("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)K[r]=Y6;K[152]=X6;K[153]=Q6;K[154]=j6;K[155]=Z6;K[156]=_e;K[157]=_e;K[158]=_e;K[159]=J6;for(let r=160;r<=183;r++)K[r]=e5;K[184]=t5;K[185]=r5;K[186]=n5;K[187]=o5;K[188]=_e;K[189]=_e;K[190]=_e;K[191]=s5;for(let r=192;r<=215;r++)K[r]=i5;K[216]=a5;K[217]=c5;K[218]=l5;K[219]=u5;K[220]=_e;K[221]=_e;K[222]=_e;K[223]=_e;for(let r=224;r<=243;r++)K[r]=Iu("simple values are not supported");K[244]=_e;K[245]=_e;K[246]=_e;K[247]=d5;K[248]=Iu("simple values are not supported");K[249]=h5;K[250]=p5;K[251]=m5;K[252]=_e;K[253]=_e;K[254]=_e;K[255]=f5;var Qr=[];for(let r=0;r<24;r++)Qr[r]=new F(_.uint,r,1);for(let r=-1;r>=-24;r--)Qr[31-r]=new F(_.negint,r,1);Qr[64]=new F(_.bytes,new Uint8Array(0),1);Qr[96]=new F(_.string,"",1);Qr[128]=new F(_.array,0,1);Qr[160]=new F(_.map,0,1);Qr[244]=new F(_.false,!1,1);Qr[245]=new F(_.true,!0,1);Qr[246]=new F(_.null,null,1);function b5(r){switch(r.type){case _.false:return hn([244]);case _.true:return hn([245]);case _.null:return hn([246]);case _.bytes:return r.value.length?void 0:hn([64]);case _.string:return r.value===""?hn([96]):void 0;case _.array:return r.value===0?hn([128]):void 0;case _.map:return r.value===0?hn([160]):void 0;case _.uint:return r.value<24?hn([Number(r.value)]):void 0;case _.negint:if(r.value>=-24)return hn([31-Number(r.value)])}}var p_={float64:!1,mapSorter:y_,quickEncodeToken:b5};function m_(){let r=[];return r[_.uint.major]=Dr,r[_.negint.major]=xu,r[_.bytes.major]=gi,r[_.string.major]=z6,r[_.array.major]=Ru,r[_.map.major]=Su,r[_.tag.major]=_u,r[_.float.major]=Au,r}var x5=m_(),M0=new Ha,Tu=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${mi} object contains circular references`);return new r(t,e)}},Ao={null:new F(_.null,null),undefined:new F(_.undefined,void 0),true:new F(_.true,!0),false:new F(_.false,!1),emptyArray:new F(_.array,0),emptyMap:new F(_.map,0)},Io={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new F(_.float,r):r>=0?new F(_.uint,r):new F(_.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new F(_.uint,r):new F(_.negint,r)},Uint8Array(r,e,t,n){return new F(_.bytes,r)},string(r,e,t,n){return new F(_.string,r)},boolean(r,e,t,n){return r?Ao.true:Ao.false},null(r,e,t,n){return Ao.null},undefined(r,e,t,n){return Ao.undefined},ArrayBuffer(r,e,t,n){return new F(_.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new F(_.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Ao.emptyArray,new F(_.break)]:Ao.emptyArray;n=Tu.createCheck(n,r);let o=[],s=0;for(let i of r)o[s++]=Du(i,t,n);return t.addBreakTokens?[new F(_.array,r.length),o,new F(_.break)]:[new F(_.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",s=o?r.keys():Object.keys(r),i=o?r.size:s.length;if(!i)return t.addBreakTokens===!0?[Ao.emptyMap,new F(_.break)]:Ao.emptyMap;n=Tu.createCheck(n,r);let a=[],c=0;for(let l of s)a[c++]=[Du(l,t,n),Du(o?r.get(l):r[l],t,n)];return g_(a,t),t.addBreakTokens?[new F(_.map,i),a,new F(_.break)]:[new F(_.map,i),a]}};Io.Map=Io.Object;Io.Buffer=Io.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Io[`${r}Array`]=Io.DataView;function Du(r,e={},t){let n=b6(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||Io[n];if(typeof o=="function"){let i=o(r,n,e,t);if(i!=null)return i}let s=Io[n];if(!s)throw new Error(`${mi} unsupported type: ${n}`);return s(r,n,e,t)}function g_(r,e){e.mapSorter&&r.sort(e.mapSorter)}function y_(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,s=x5[o].compareTokens(t,n);return s===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),s}function v5(r,e,t,n){if(Array.isArray(e))for(let o of e)v5(r,o,t,n);else t[e.type.major](r,e,n)}function R5(r,e,t){let n=Du(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let s=e[n.type.major];if(s.encodedSize){let i=s.encodedSize(n,t),a=new Ha(i);if(s(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return $a(a.chunks[0])}}return M0.reset(),v5(M0,n,e,t),M0.toBytes(!0)}function Ei(r,e){return e=Object.assign({},p_,e),R5(r,x5,e)}var w_={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},ku=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=Qr[e];if(t===void 0){let n=K[e];if(!n)throw new Error(`${Q} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let o=e&31;t=n(this.data,this._pos,o,this.options)}return this._pos+=t.encodedLength,t}},za=Symbol.for("DONE"),Cu=Symbol.for("BREAK");function E_(r,e,t){let n=[];for(let o=0;o<r.value;o++){let s=bi(e,t);if(s===Cu){if(r.value===1/0)break;throw new Error(`${Q} got unexpected break to lengthed array`)}if(s===za)throw new Error(`${Q} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=s}return n}function b_(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},s=n?new Map:void 0;for(let i=0;i<r.value;i++){let a=bi(e,t);if(a===Cu){if(r.value===1/0)break;throw new Error(`${Q} got unexpected break to lengthed map`)}if(a===za)throw new Error(`${Q} found map but not enough entries (got ${i} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${Q} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&s.has(a)||!n&&a in o))throw new Error(`${Q} found repeat map key "${a}"`);let c=bi(e,t);if(c===za)throw new Error(`${Q} found map but not enough entries (got ${i} [no value], expected ${r.value})`);n?s.set(a,c):o[a]=c}return n?s:o}function bi(r,e){if(r.done())return za;let t=r.next();if(t.type===_.break)return Cu;if(t.type.terminal)return t.value;if(t.type===_.array)return E_(t,r,e);if(t.type===_.map)return b_(t,r,e);if(t.type===_.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=bi(r,e);return e.tags[t.value](n)}throw new Error(`${Q} tag not supported (${t.value})`)}throw new Error("unsupported")}function U0(r,e){if(!(r instanceof Uint8Array))throw new Error(`${Q} data to decode must be a Uint8Array`);e=Object.assign({},w_,e);let t=e.tokenizer||new ku(r,e),n=bi(t,e);if(n===za)throw new Error(`${Q} did not find any content to decode`);if(n===Cu)throw new Error(`${Q} got unexpected break`);return[n,r.subarray(t.pos())]}function kr(r,e){let[t,n]=U0(r,e);if(n.length>0)throw new Error(`${Q} too many terminals, data makes no sense`);return t}var qn="/",S5=new TextEncoder().encode(qn),Lu=S5[0],Pe=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=M(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Lu)throw new Error("Invalid key")}toString(e="utf8"){return O(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(qn))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=S5),this._buf[0]!==Lu){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Lu,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Lu;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let s=t[o],i=n[o];if(s<i)return!0;if(s>i)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(qn).slice(1)}type(){return x_(this.baseNamespace())}name(){return v_(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(qn)||(e+=qn),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(qn):new r(e.slice(0,-1).join(qn))}child(e){return this.toString()===qn?e:e.toString()===qn?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...R_(e.map(t=>t.namespaces()))])}};function x_(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function v_(r){let e=r.split(":");return e[e.length-1]}function R_(r){return[].concat(...r)}var D5="/pin/",_5="/pinned-block/",F0=so,A5=1;function I5(r){return r.version===0&&(r=r.toV1()),new Pe(`${D5}${r.toString(F0)}`)}var Pu=class{datastore;blockstore;dagWalkers;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.dagWalkers=n}async*add(e,t={}){let n=I5(e);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let s=new tr({concurrency:A5});for await(let a of this.#e(e,s,{...t,depth:o}))await this.#t(a,c=>c.pinnedBy.find(l=>Z(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let i={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,Ei(i),t)}async*#e(e,t,n){if(n.depth===-1)return;let o=this.dagWalkers[e.code];if(o==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let s=await this.blockstore.get(e,n);yield e;for await(let i of o.walk(s))yield*await t.add(async()=>this.#e(i,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let o=new Pe(`${_5}${F0.encode(e.multihash.bytes)}`),s={pinCount:0,pinnedBy:[]};try{s=kr(await this.datastore.get(o,n))}catch(a){if(a.code!=="ERR_NOT_FOUND")throw a}if(t(s)){if(s.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,Ei(s),n),n.onProgress?.(new me("helia:pin:add",e))}}async*rm(e,t={}){let n=I5(e),o=await this.datastore.get(n,t),s=kr(o);await this.datastore.delete(n,t);let i=new tr({concurrency:A5});for await(let a of this.#e(e,i,{...t,depth:s.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>Z(l,e.bytes)),!0),{...t,depth:s.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:D5+(e.cid!=null?`${e.cid.toString(so)}`:"")},e)){let o=le.parse(t.toString().substring(5),so),s=kr(n);yield{cid:o,...s}}}async isPinned(e,t={}){let n=new Pe(`${_5}${F0.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}};var S_=5,Ou=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??S_}async start(){await cn(...this.routers)}async stop(){await ln(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new g("No content routers available","ERR_NO_ROUTERS_AVAILABLE");let n=new wr({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of Mt(n.toGenerator(),...xi(this.routers,"findProviders").map(s=>s.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let s=await this.findPeer(o.id,t);return s.multiaddrs.length===0?null:s}catch(s){return this.log.error("could not load multiaddrs for peer %p",o.id,s),null}},{peerId:o.id,signal:t.signal}).catch(s=>{this.log.error("could not load multiaddrs for peer %p",o.id,s)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new g("No content routers available","ERR_NO_ROUTERS_AVAILABLE");await Promise.all(xi(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async put(e,t,n){await Promise.all(xi(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(xi(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new g("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");let n=this,o=Mt(...xi(this.routers,"findPeer").map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s;throw new g("Could not find peer in routing","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new g("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");for await(let n of Mt(...xi(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function xi(r,e){return r.filter(t=>t[e]!=null)}var Do={},vi=r=>{r.addEventListener("message",e=>{vi.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{vi.dispatchEvent("message",r,e)})};vi.addEventListener=(r,e)=>{Do[r]==null&&(Do[r]=[]),Do[r].push(e)};vi.removeEventListener=(r,e)=>{Do[r]!=null&&(Do[r]=Do[r].filter(t=>t===e))};vi.dispatchEvent=function(r,e,t){Do[r]!=null&&Do[r].forEach(n=>n(e,t))};var V0=vi;var K0="lock:worker:request-read",$0="lock:worker:release-read",H0="lock:master:grant-read",q0="lock:worker:request-write",G0="lock:worker:release-write",W0="lock:master:grant-write";var T5=(r=21)=>Math.random().toString().substring(2);var k5=(r,e,t,n,o)=>(s,i)=>{if(i.data.type!==t)return;let a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=d=>{if(d==null||d.data==null)return;let u={type:d.data.type,name:d.data.name,identifier:d.data.identifier};u.type===n&&u.identifier===a.identifier&&(s.removeEventListener("message",l),c())};s.addEventListener("message",l)})}}}))},C5=(r,e,t,n)=>async()=>{let o=T5();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(s=>{let i=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===t&&c.identifier===o&&(globalThis.removeEventListener("message",i),s(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",i)})},__={singleProcess:!1},N5=r=>{if(r=Object.assign({},__,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return V0.addEventListener("message",k5(t,"requestReadLock",K0,$0,H0)),V0.addEventListener("message",k5(t,"requestWriteLock",q0,G0,W0)),t}return{isWorker:!0,readLock:t=>C5(t,K0,H0,$0),writeLock:t=>C5(t,q0,W0,G0)}};var ys={},To;async function z0(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>Yr((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var A_=(r,e)=>{if(To.isWorker===!0)return{readLock:To.readLock(r,e),writeLock:To.writeLock(r,e)};let t=new Ir({concurrency:1}),n;return{async readLock(){if(n!=null)return z0(n,e);n=new Ir({concurrency:e.concurrency,autoStart:!1});let o=n,s=z0(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),s},async writeLock(){return n=null,z0(t,e)}}},I_={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Ya(r){let e=Object.assign({},I_,r);return To==null&&(To=N5(e),To.isWorker!==!0&&(To.addEventListener("requestReadLock",t=>{ys[t.data.name]!=null&&ys[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),To.addEventListener("requestWriteLock",async t=>{ys[t.data.name]!=null&&ys[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),ys[e.name]==null&&(ys[e.name]=A_(e.name,e)),ys[e.name]}var Bu=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=Ya({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await cn(this.child),this.started=!0}async stop(){await ln(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let s of e){if(await o.pins.isPinned(s))throw new Error("CID was pinned");yield s}}(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var P5=42;function D_(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=le.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new F(_.tag,P5),new F(_.bytes,t)]}function T_(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function k_(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var L5={float64:!0,typeEncoders:{Object:D_,undefined:T_,number:k_}},GK={...L5,typeEncoders:{...L5.typeEncoders}};function C_(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return le.decode(r.subarray(1))}var Y0={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Y0.tags[P5]=C_;var WK={...Y0,tags:Y0.tags.slice()};var O5=113;var B5=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===_.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===_.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[_.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s);e.push(o)}[_.negint.major](e,t){this[_.uint.major](e,t)}[_.bytes.major](e,t){throw new Error(`${mi} unsupported type: Uint8Array`)}[_.string.major](e,t){this.prefix(e);let n=bu(JSON.stringify(t.value));e.push(n.length>32?$a(n):n)}[_.array.major](e,t){this.prefix(e),this.inRecursive.push({type:_.array,elements:0}),e.push([91])}[_.map.major](e,t){this.prefix(e),this.inRecursive.push({type:_.map,elements:0}),e.push([123])}[_.tag.major](e,t){}[_.float.major](e,t){if(t.type.name==="break"){let i=this.inRecursive.pop();if(i){if(i.type===_.array)e.push([93]);else if(i.type===_.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${mi} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],s=!1;for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i),!s&&(o[i]===46||o[i]===101||o[i]===69)&&(s=!0);s||(o.push(46),o.push(48)),e.push(o)}};var ws=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${Q} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${Q} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new F(_.uint,0,this._pos-e);if(o([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${Q} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${Q} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let s=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),i=parseFloat(s);return n?new F(_.float,i,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(i)?new F(i>=0?_.uint:_.negint,i,this._pos-e):new F(i>=0?_.uint:_.negint,BigInt(s),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${Q} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let s=this._pos,i=0;s<this.data.length&&i<65536;s++,i++){let a=this.data[s];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,s));return this._pos=s+1,new F(_.string,c,i)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${Q} unexpected end of unicode escape sequence at position ${this._pos}`);let s=0;for(let i=0;i<4;i++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${Q} unexpected unicode escape character at position ${this._pos}`);s=s*16+a,this._pos++}return s},o=()=>{let s=this.ch(),i=null,a=s>239?4:s>223?3:s>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${Q} unexpected unicode sequence at position ${this._pos}`);let c,l,d,u;switch(a){case 1:s<128&&(i=s);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(u=(s&31)<<6|c&63,u>127&&(i=u));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(u=(s&15)<<12|(c&63)<<6|l&63,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],d=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(d&192)===128&&(u=(s&15)<<18|(c&63)<<12|(l&63)<<6|d&63,u>65535&&u<1114112&&(i=u))}i===null?(i=65533,a=1):i>65535&&(i-=65536,t.push(i>>>10&1023|55296),i=56320|i&1023),t.push(i),this._pos+=a};for(;!this.done();){let s=this.ch(),i;switch(s){case 92:if(this._pos++,this.done())throw new Error(`${Q} unexpected string termination at position ${this._pos}`);switch(i=this.ch(),this._pos++,i){case 34:case 39:case 92:case 47:t.push(i);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${Q} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new F(_.string,N0(t),this._pos-e);default:if(s<32)throw new Error(`${Q} invalid control character at position ${this._pos}`);s<128?(t.push(s),this._pos++):o()}}throw new Error(`${Q} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new F(_.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new F(_.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new F(_.null,null,4);case 102:return this.expect([102,97,108,115,101]),new F(_.false,!1,5);case 116:return this.expect([116,114,117,101]),new F(_.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${Q} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new F(_.break,void 0,1);if(this.ch()!==44)throw new Error(`${Q} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new F(_.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new F(_.break,void 0,1);if(this.ch()!==44)throw new Error(`${Q} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new F(_.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${Q} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${Q} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Mu(r,e){return e=Object.assign({tokenizer:new ws(r,e)},e),kr(r,e)}var P_={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};P_.tags[42]=le.parse;var U5=297;var l$=new TextDecoder;var u$=new TextEncoder;var B_=new TextDecoder;function X0(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[e++];if(t+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[t,e]}function Uu(r,e){let t;[t,e]=X0(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function F5(r,e){let t;return[t,e]=X0(r,e),[t&7,t>>3,e]}function M_(r){let e={},t=r.length,n=0;for(;n<t;){let o,s;if([o,s,n]=F5(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Uu(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let i;[i,n]=Uu(r,n),e.Name=B_.decode(i)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=X0(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function V5(r){let e=r.length,t=0,n,o=!1,s;for(;t<e;){let a,c;if([a,c,t]=F5(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=Uu(r,t),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=Uu(r,t),n.push(M_(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let i={};return s&&(i.Data=s),i.Links=n||[],i}var f$=new TextEncoder,h$=2**32,p$=2**31;var y$=new TextEncoder;function K5(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var $5=112;function H5(r){let e=K5(r),t=V5(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let s={};try{s.Hash=le.decode(o.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(s.Name=o.Name),o.Tsize!==void 0&&(s.Tsize=o.Tsize),s})),n}var F_={codec:$5,*walk(r){yield*H5(r).Links.map(t=>t.Hash)}},V_={codec:Xc,*walk(){}},q5=42,K_={codec:O5,*walk(r){let e=[],t=[];t[q5]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let o=le.decode(n.subarray(1));return e.push(o),o},kr(r,{tags:t}),yield*e}},Q0=class extends ws{tokenBuffer;constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===_.map){let t=this._next();if(t.type===_.string&&t.value==="/"){let n=this._next();if(n.type===_.string){if(this._next().type!==_.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new F(_.tag,42,0)}if(n.type===_.map){let o=this._next();if(o.type===_.string&&o.value==="bytes"){let s=this._next();if(s.type===_.string){for(let a=0;a<2;a++)if(this._next().type!==_.break)throw new Error("Invalid encoded Bytes form");let i=st.decode(`m${s.value}`);return new F(_.bytes,i,s.value.length)}this.tokenBuffer.push(s)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},$_={codec:U5,*walk(r){let e=[],t=[];t[q5]=n=>{let o=le.parse(n);return e.push(o),o},Mu(r,{tags:t,tokenizer:new Q0(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}},H_={codec:W4,*walk(){}};function G5(r=[]){let e={};return[F_,V_,K_,$_,H_,...r].forEach(t=>{e[t.codec]=t}),e}var j0=new Pe("/version"),W5=1;async function z5(r){if(!await r.has(j0)){await r.put(j0,M(`${W5}`));return}let e=await r.get(j0),t=O(e);if(parseInt(t,10)!==W5)throw new Error("Unknown datastore version, a datastore migration may be required")}function Y5(r=[]){let e={};return[Ne,Eh,Wt,...r].forEach(t=>{e[t.code]=t}),e}var Gn=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:o}of e)await this.put(n,o,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var Ri={};pe(Ri,{abortedError:()=>Y_,closeFailedError:()=>G_,deleteFailedError:()=>Q5,getFailedError:()=>W_,hasFailedError:()=>z_,notFoundError:()=>Xa,openFailedError:()=>q_,putFailedError:()=>X5});var Wn=Qe(Yo(),1);function q_(r){return r=r??new Error("Open failed"),(0,Wn.default)(r,"ERR_OPEN_FAILED")}function G_(r){return r=r??new Error("Close failed"),(0,Wn.default)(r,"ERR_CLOSE_FAILED")}function X5(r){return r=r??new Error("Put failed"),(0,Wn.default)(r,"ERR_PUT_FAILED")}function W_(r){return r=r??new Error("Get failed"),(0,Wn.default)(r,"ERR_GET_FAILED")}function Q5(r){return r=r??new Error("Delete failed"),(0,Wn.default)(r,"ERR_DELETE_FAILED")}function z_(r){return r=r??new Error("Has failed"),(0,Wn.default)(r,"ERR_HAS_FAILED")}function Xa(r){return r=r??new Error("Not Found"),(0,Wn.default)(r,"ERR_NOT_FOUND")}function Y_(r){return r=r??new Error("Aborted"),(0,Wn.default)(r,"ERR_ABORTED")}var Qa=class extends Gn{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(ut.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(ut.encode(e.multihash.bytes));if(t==null)throw Xa();return t}has(e){return this.data.has(ut.encode(e.multihash.bytes))}async delete(e){this.data.delete(ut.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:le.createV1(Xc,Mr(ut.decode(e))),block:t}}};function X_(r){return r[Symbol.asyncIterator]!=null}function Q_(r,e){let t=0;if(X_(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=Vs(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();let i=e(o,t++);if(typeof i.then=="function")return async function*(){await i&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){i===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var jr=Q_;var eH=ir("blockstore:core:tiered");var j5={...Ri};var Fu=0,Vu=class extends Gn{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===Fu||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===Fu)return e.multihash.digest;if(this.child==null)throw j5.notFoundError();return this.child.get(e)}has(e){return e.multihash.code===Fu?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==Fu&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function j_(r){return r[Symbol.asyncIterator]!=null}function Z5(r){return r?.then!=null}function Z_(r,e){let t=0;if(j_(r))return async function*(){for await(let c of r){let l=e(c,t++);Z5(l)&&await l,yield c}}();let n=Vs(r),{value:o,done:s}=n.next();if(s===!0)return function*(){}();if(typeof e(o,t++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=e(c,t++);Z5(l)&&await l,yield c}}();let a=e;return function*(){yield o;for(let c of n)a(c,t++),yield c}()}var ja=Z_;var Ku=class{child;hashers;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new Vu(e.blockstore),this.hashers=e.hashers??{}}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new me("blocks:put:duplicate",e)),e):(n.onProgress?.(new me("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new me("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=jr(e,async({cid:s})=>{let i=await this.child.has(s,t);return i&&t.onProgress?.(new me("blocks:put-many:duplicate",s)),!i}),o=ja(n,async({cid:s,block:i})=>{t.onProgress?.(new me("blocks:put-many:providers:notify",s)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(s,i,t)))});t.onProgress?.(new me("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,t)}async get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){t.onProgress?.(new me("blocks:get:providers:get",e));let n=await J5(e,this.components.blockBrokers,this.hashers[e.multihash.code],{...t,log:this.log});return t.onProgress?.(new me("blocks:get:blockstore:put",e)),await this.child.put(e,n,t),t.onProgress?.(new me("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n,t))),n}return t.onProgress?.(new me("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new me("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(ja(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){t.onProgress?.(new me("blocks:get-many:providers:get",n));let o=await J5(n,this.components.blockBrokers,this.hashers[n.multihash.code],{...t,log:this.log});t.onProgress?.(new me("blocks:get-many:blockstore:put",n)),await this.child.put(n,o,t),t.onProgress?.(new me("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,o,t)))}}))}async delete(e,t={}){t.onProgress?.(new me("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new me("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of e)yield n}(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new me("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},$u=class extends Ku{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await cn(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await ln(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new Z0({blockstore:this.child,blockBrokers:n,hashers:this.hashers,logger:this.logger},{root:e})}},Z0=class extends Ku{closeController;constructor(e,t){super(e),this.closeController=new AbortController,H(1/0,this.closeController.signal),this.log=e.logger.forComponent(`helia:session-storage${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let o=Ae([this.closeController.signal,n.signal]);H(1/0,o);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Ae([this.closeController.signal,t.signal]);H(1/0,n);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Ae([this.closeController.signal,e.signal]);H(1/0,t);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function J_(r){return typeof r.retrieve=="function"}var eA=(r,e)=>{if(e==null)throw new g(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`,"ERR_UNKNOWN_HASH_ALG");return async t=>{let n=await e.digest(t);if(!Z(n.digest,r.multihash.digest))throw new g("Hash of downloaded block did not match multihash from passed CID","ERR_HASH_MISMATCH")}};async function J5(r,e,t,n){let o=eA(r,t),s=new AbortController,i=Ae([s.signal,n.signal]);H(1/0,s.signal,i);let a=[];for(let c of e)J_(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,d=await c.retrieve(r,{...n,signal:i,validateFn:async u=>{await o(u),l=!0}});return l||await o(d),d}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{s.abort(),i.clear()}}var eg=1,tg=5;var J0=Qe(s6(),1);var tA=Math.LN2*Math.LN2,Hu=class r{static create(e,t=.005){let n=rA(e,t);return new r(n)}seeds;bits;buffer;constructor(e={}){e.seeds!=null?this.seeds=e.seeds:this.seeds=nA(e.hashes??8),this.bits=e.bits??1024,this.buffer=Ie(Math.ceil(this.bits/8))}add(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.seeds.length;t++){let o=J0.default.x86.hash32(e,this.seeds[t])%this.bits;this.setbit(o)}}has(e){typeof e=="string"&&(e=M(e));for(let t=0;t<this.seeds.length;t++){let o=J0.default.x86.hash32(e,this.seeds[t])%this.bits;if(!this.getbit(o))return!1}return!0}clear(){this.buffer.fill(0)}setbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;let o=this.buffer[t];o|=1<<n,this.buffer[t]=o}getbit(e){let t=0,n=e;for(;n>7;)t++,n-=8;return(this.buffer[t]&1<<n)!==0}};function rA(r,e=.005){let t=Math.round(-1*r*Math.log(e)/tA),n=Math.round(t/r*Math.LN2);return{bits:t,hashes:n}}function nA(r){let e,t,n=[];for(let o=0;o<r;o++)for(e=new ce(pt(4)),n[o]=e.getUint32(0,!0),t=0;t<o;t++)if(n[o]===n[t]){o--;break}return n}var Es=class extends ye{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),H(1/0,this),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=Hu.create(this.maxProviders)}async retrieve(e,t={}){let n=st.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let s=J();if(this.requests.set(n,s.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",e)}let i=!1,a=new tr({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{i=!0,s.resolve(l.detail.result)}),a.addEventListener("idle",()=>{i||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let d=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(d)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),s.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c",e,l),s.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(d=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,d)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(e,l,t),{provider:l}))).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,l)});try{return await s.promise}finally{this.removeEventListener("provider",c),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=J(),s=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let i of this.findNewProviders(e,n)){if(s===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(i)&&(this.log("found %d/%d new providers",s,this.maxProviders),this.providers.push(i),this.safeDispatchEvent("provider",{detail:i}),s++,s===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",s);break}}if(this.log("found %d/%d new session peers",s,this.maxProviders),s<t)throw new g(`Found ${s} of ${t} ${this.name} providers for ${e}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(i=>{this.log.error("error searching routing for potential session peers for %c",e,i.errors??i),o.reject(i)}),o.promise}};var qu=class{blockstore;datastore;pins;logger;routing;dagWalkers;hashers;dns;metrics;log;constructor(e){this.logger=e.logger??So(),this.log=this.logger.forComponent("helia"),this.hashers=Y5(e.hashers),this.dagWalkers=G5(e.dagWalkers),this.dns=e.dns??wu(),this.metrics=e.metrics;let t={blockstore:e.blockstore,datastore:e.datastore,hashers:this.hashers,dagWalkers:this.dagWalkers,logger:this.logger,blockBrokers:[],dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new Ou(t,{routers:(e.routers??[]).flatMap(o=>{let s=[o];return o[on]!=null&&s.push(o[on]),o[sn]!=null&&s.push(o[sn]),s}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new $u(t);this.pins=new Pu(e.datastore,n,this.dagWalkers),this.blockstore=new Bu(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await z5(this.datastore),await cn(this.blockstore,this.datastore,this.routing)}async stop(){await ln(this.blockstore,this.datastore,this.routing)}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await $t(o.deleteMany(async function*(){for await(let{cid:s}of o.getAll())try{if(await n.pins.isPinned(s,e))continue;yield s,e.onProgress?.(new me("helia:gc:deleted",s))}catch(i){n.log.error("Error during gc",i),e.onProgress?.(new me("helia:gc:error",i))}}()))}finally{t()}this.log("gc finished")}};var e2=class extends Es{wantList;network;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let o=await this.wantList.wantSessionBlock(e,t,n);if(this.log("%p %s %c",t,o.has?"has":"does not have",e),o.has&&o.block!=null)return o.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield n.id}toEvictionKey(e){return e.toBytes()}equals(e,t){return e.equals(t)}};function rg(r,e){return new e2(r,e)}var Gu=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var t2=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function Wu(r){let{name:e,metrics:t}=r,n;return t!=null?n=new t2({name:e,metrics:t}):n=new Map,n}function oA(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=Bt(r);e.push(t),r=r.slice(Se(t))}return e}var ng=oA;var zu=class extends ye{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),H(1/0,this),this.peers=Fa({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=Wu({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(o=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,o)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(o=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,o)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=O(e.multihash.bytes,"base64"),o=this.wants.get(n);o==null&&(o={cid:e,priority:t.priority??1,wantType:t.wantType??rt.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,o)),o.wantType===rt.WantHave&&t.wantType===rt.WantBlock&&(o.wantType=rt.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===rt.WantBlock?(await er(this,"block",t?.signal,{filter:a=>Z(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await er(this,"presence",t?.signal,{filter:i=>Z(e.multihash.digest,i.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),o.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=J(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,o=new $n;for(let[s,i]of this.wants.entries())t.has(s)||i.cancel||(n.add(s),o.addWantlistEntry(i.cid,{cid:i.cid.bytes,priority:i.priority,wantType:i.wantType,cancel:i.cancel,sendDontHave:i.sendDontHave}));if(o.wantlist.size!==0)try{await this.network.sendMessage(e,o);for(let s of n)t.add(s)}catch(s){this.log.error("error sending full wantlist to new peer",s)}})).catch(e=>{this.log.error("error sending messages",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=O(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let o=new $n;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:rt.WantHave,priority:1}),await this.network.sendMessage(t,o),(await er(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Z(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:rt.WantBlock})}async wantSessionBlock(e,t,n={}){let o=new $n;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:rt.WantBlock,priority:1}),await this.network.sendMessage(t,o),(await er(this,"presence",n.signal,{filter:i=>t.equals(i.detail.sender)&&Z(e.multihash.digest,i.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=O(e.multihash.bytes,"base64"),o=this.wants.get(n);o!=null&&(o.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let o of t.blocks){if(o.prefix==null||o.data==null)continue;let s=ng(o.prefix),i=s[0],a=s[1],c=s[2],l=c===Ne.code?Ne:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let d=l.digest(o.data);d.then!=null&&(d=await d);let u=le.create(i===0?0:1,a,d);this.log("received block from %p for %c",e,u),this.safeDispatchEvent("block",{detail:{sender:e,cid:u,block:o.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:u,has:!0,block:o.data}});let h=O(u.multihash.bytes,"base64"),f=this.wants.get(h);f!=null&&(f.cancel=!0,n=!0)}for(let{cid:o,type:s}of t.blockPresences){let i=le.decode(o);this.log("received %s from %p for %c",s,e,i),this.safeDispatchEvent("presence",{detail:{sender:e,cid:i,has:s===xr.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new $n(!0);for(let[o,s]of this.wants.entries())s.cancel||(t.add(o),n.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:1,wantType:rt.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(o){this.log.error("error sending full wantlist to new peer %p",e,o)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var Yu=class{log;logger;stats;network;blockstore;peerWantLists;wantList;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.stats=new Gu(e),this.network=new rl(e,t),this.peerWantLists=new du({...e,network:this.network},t),this.wantList=new zu({...e,network:this.network},t)}createSession(e={}){return rg({wantList:this.wantList,network:this.network,logger:this.logger},e)}async want(e,t={}){let n=new AbortController,o=Ae([n.signal,t.signal]);H(1/0,n.signal,o),this.network.findAndConnect(e,{...t,signal:o}).catch(s=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,s)});try{return(await this.wantList.wantBlock(e,{...t,signal:o})).block}finally{n.abort(),o.clear()}}async notify(e,t,n={}){await Promise.all([this.peerWantLists.receivedBlock(e,n),this.wantList.receivedBlock(e,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var og=(r,e={})=>new Yu(r,e);var r2=class{bitswap;started;constructor(e,t={}){let{hashers:n}=e;this.bitswap=og(e,{hashLoader:{getHasher:async o=>{let s;if(typeof o=="string"?s=Object.values(n).find(i=>i.name===o):s=n[o],s!=null)return s;throw new Error(`Could not load hasher for code/name "${o}"`)}},...t}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t,n){await this.bitswap.notify(e,t,n)}async retrieve(e,t={}){return this.bitswap.want(e,t)}createSession(e){let t=this.bitswap.createSession(e);return{announce:async(n,o,s)=>{await this.bitswap.notify(n,o,s)},retrieve:async(n,o)=>t.retrieve(n,o)}}};function n2(r={}){return e=>new r2(e,r)}var Xu=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let d=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let h=Number.parseInt(u,e);if(!Number.isNaN(h))return h});if(d===void 0)break;if(s*=e,s+=d,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var sg=45,sA=15,Si=new Xu;function o2(r){if(!(r.length>sA))return Si.new(r).parseWith(()=>Si.readIPv4Addr())}function s2(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>sg))return Si.new(r).parseWith(()=>Si.readIPv6Addr())}function Qu(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>sg))return Si.new(r).parseWith(()=>Si.readIPAddr())}function _i(r){return!!o2(r)}function Ai(r){return!!s2(r)}function ju(r){return!!Qu(r)}var ag=Qe(ig(),1),iA=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],aA=iA.map(r=>new ag.Netmask(r));function cA(r){for(let e of aA)if(e.contains(r))return!0;return!1}function lA(r){return/^::$/.test(r)||/^::1$/.test(r)||/^::f{4}:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^::f{4}:0.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Yt(r){return _i(r)?cA(r):Ai(r)?lA(r):void 0}var Vq=parseInt("0xFFFF",16),Kq=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var ug=_i,pA=Ai,i2=function(r){let e=0;if(r=r.toString().trim(),ug(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(pA(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=ug(t[n]),i;s&&(i=i2(t[n]),t[n]=O(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,O(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},dg=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Ii={},a2={},gA=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[777,-1,"memory"]];gA.forEach(r=>{let e=yA(...r);a2[e.code]=e,Ii[e.name]=e});function yA(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function ee(r){if(typeof r=="number"){if(a2[r]!=null)return a2[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Ii[r]!=null)return Ii[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var vG=ee("ip4"),RG=ee("ip6"),SG=ee("ipcidr");function l2(r,e){switch(ee(r).code){case 4:case 41:return EA(e);case 42:return pg(e);case 6:case 273:case 33:case 132:return gg(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return pg(e);case 421:return RA(e);case 444:return mg(e);case 445:return mg(e);case 466:return vA(e);default:return O(e,"base16")}}function u2(r,e){switch(ee(r).code){case 4:return fg(e);case 41:return fg(e);case 42:return hg(e);case 6:case 273:case 33:case 132:return d2(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return hg(e);case 421:return bA(e);case 444:return SA(e);case 445:return _A(e);case 466:return xA(e);default:return M(e,"base16")}}var c2=Object.values(br).map(r=>r.decoder),wA=function(){let r=c2[0].or(c2[1]);return c2.slice(2).forEach(e=>r=r.or(e)),r}();function fg(r){if(!ju(r))throw new Error("invalid ip address");return i2(r)}function EA(r){let e=dg(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!ju(e))throw new Error("invalid ip address");return e}function d2(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function gg(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function hg(r){let e=M(r),t=Uint8Array.from($e(e.length));return ve([t,e],t.length+e.length)}function pg(r){let e=Bt(r);if(r=r.slice(Se(e)),r.length!==e)throw new Error("inconsistent lengths");return O(r)}function bA(r){let e;r[0]==="Q"||r[0]==="1"?e=Mr(Ye.decode(`z${r}`)).bytes:e=le.parse(r).multihash.bytes;let t=Uint8Array.from($e(e.length));return ve([t,e],t.length+e.length)}function xA(r){let e=wA.decode(r),t=Uint8Array.from($e(e.length));return ve([t,e],t.length+e.length)}function vA(r){let e=Bt(r),t=r.slice(Se(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+O(t,"base64url")}function RA(r){let e=Bt(r),t=r.slice(Se(e));if(t.length!==e)throw new Error("inconsistent lengths");return O(t,"base58btc")}function SA(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=ut.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=d2(n);return ve([t,o],t.length+o.length)}function _A(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=ut.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=d2(n);return ve([t,o],t.length+o.length)}function mg(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=O(e,"base32"),o=gg(t);return`${n}:${o}`}function yg(r){r=f2(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=ee(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw Eg("invalid address: "+r);if(a.path===!0){n=f2(o.slice(s).join("/")),e.push([a.code,u2(a.code,n)]),t.push([a.code,n]);break}let c=u2(a.code,o[s]);e.push([a.code,c]),t.push([a.code,l2(a.code,c)])}return{string:wg(t),bytes:p2(e),tuples:e,stringTuples:t,path:n}}function h2(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=Bt(r,o),i=Se(s),a=ee(s),c=AA(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Eg("Invalid address Uint8Array: "+O(r,"base16"));e.push([s,l]);let d=l2(s,l);if(t.push([s,d]),a.path===!0){n=d;break}}return{bytes:Uint8Array.from(r),string:wg(t),tuples:e,stringTuples:t,path:n}}function wg(r){let e=[];return r.map(t=>{let n=ee(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),f2(e.join("/"))}function p2(r){return ve(r.map(e=>{let t=ee(e[0]),n=Uint8Array.from($e(t.code));return e.length>1&&e[1]!=null&&(n=ve([n,e[1]])),n}))}function AA(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=Bt(e instanceof Uint8Array?e:Uint8Array.from(e));return t+Se(t)}}function f2(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function Eg(r){return new Error("Error parsing address: "+r)}var IA=Symbol.for("nodejs.util.inspect.custom"),m2=Symbol.for("@multiformats/js-multiaddr/multiaddr"),DA=[ee("dns").code,ee("dns4").code,ee("dns6").code,ee("dnsaddr").code],Zu=class r{bytes;#e;#t;#r;#o;[m2]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=h2(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=yg(e)}else if(ko(e))t=h2(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#o=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=ee("tcp"),a=ee("udp"),c=ee("ip4"),l=ee("ip6"),d=ee("dns6"),u=ee("ip6zone");for(let[f,p]of this.stringTuples())f===u.code&&(s=`%${p??""}`),DA.includes(f)&&(t=i.name,o=443,n=`${p??""}${s}`,e=f===d.code?6:4),(f===i.code||f===a.code)&&(t=ee(f).name,o=parseInt(p??"")),(f===c.code||f===l.code)&&(t=ee(f).name,n=`${p??""}${s}`,e=f===l.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},ee(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>ee(e).name)}tuples(){return this.#t}stringTuples(){return this.#r}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(p2(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===Ii.p2p.code&&e.push([n,o]),n===Ii["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?O(Ye.decode(`z${n}`),"base58btc"):O(le.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#o}equals(e){return Z(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=Di.get(t.name);if(n==null)throw new g(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>j(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[IA](){return`Multiaddr(${this.#e})`}};var Di=new Map;function ko(r){return!!r?.[m2]}function j(r){return new Zu(r)}var TA=r=>r.toString().split("/").slice(1),Ja=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),Te=r=>({match:e=>Ja(t=>t===r).match(e),pattern:r}),t1=()=>({match:r=>Ja(e=>typeof e=="string").match(r),pattern:"{string}"}),r1=()=>({match:r=>Ja(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),xt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Ye.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Ju=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{lh.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),vt=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),fr=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),Oe=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function nt(...r){function e(o){let s=TA(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matches:t,exactMatch:n}}var y2=Oe(Te("dns4"),t1()),w2=Oe(Te("dns6"),t1()),E2=Oe(Te("dnsaddr"),t1()),bg=Oe(Te("dns"),t1()),JG=nt(y2),eW=nt(w2),tW=nt(E2),n1=nt(fr(bg,E2,y2,w2)),xg=Oe(Te("ip4"),Ja(_i)),vg=Oe(Te("ip6"),Ja(Ai)),Rg=fr(xg,vg),pn=fr(Rg,bg,y2,w2,E2),Sg=nt(pn),rW=nt(xg),nW=nt(vg),_g=nt(Rg),o1=Oe(pn,Te("tcp"),r1()),ec=Oe(pn,Te("udp"),r1()),kA=fr(o1,ec),oW=nt(o1),sW=nt(ec),b2=Oe(ec,Te("quic")),s1=Oe(ec,Te("quic-v1")),CA=fr(b2,s1),iW=nt(b2),aW=nt(s1),g2=fr(pn,o1,ec,b2,s1),Ag=fr(Oe(g2,Te("ws"),vt(xt()))),cW=nt(Ag),Ig=fr(Oe(g2,Te("wss"),vt(xt())),Oe(g2,Te("tls"),Te("ws"),vt(xt()))),lW=nt(Ig),Dg=Oe(kA,Te("webrtc-direct"),Ju(),vt(Ju()),vt(xt())),Tg=nt(Dg),kg=Oe(s1,Te("webtransport"),vt(Ju()),vt(Ju()),vt(xt())),i1=nt(kg),e1=fr(Ag,Ig,Oe(o1,vt(xt())),Oe(CA,vt(xt())),Oe(pn,vt(xt())),Dg,kg,xt()),uW=nt(e1),NA=Oe(e1,Te("p2p-circuit"),xt()),bs=nt(NA),LA=fr(Oe(e1,Te("p2p-circuit"),Te("webrtc"),xt()),Oe(e1,Te("webrtc"),vt(xt())),Te("webrtc")),Cg=nt(LA),PA=fr(Oe(pn,Te("tcp"),r1(),Te("http"),vt(xt())),Oe(pn,Te("http"),vt(xt()))),Ng=nt(PA),OA=fr(Oe(pn,Te("tcp"),fr(Oe(Te("443"),Te("http")),Oe(r1(),Te("https"))),vt(xt())),Oe(pn,Te("tls"),Te("http"),vt(xt())),Oe(pn,Te("https"),vt(xt()))),Lg=nt(OA);var BA=[ee("tcp").code,ee("dns").code,ee("dnsaddr").code,ee("dns4").code,ee("dns6").code];function Pg(r){let e;try{e=ee("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function Og(r){return r.some(([e,t])=>e===ee("tls").code)}function hr(r,e,t){let n=Bg[ee(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${ee(r).name}`);let o=n(e,t);return r===ee("ip6").code?`[${o}]`:o}var Bg={ip4:(r,e)=>r,ip6:(r,e)=>e.length===0?r:`[${r}]`,tcp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${hr(t[0],t[1]??"",e)}:${r}`},udp:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${hr(t[0],t[1]??"",e)}:${r}`},dnsaddr:(r,e)=>r,dns4:(r,e)=>r,dns6:(r,e)=>r,dns:(r,e)=>r,ipfs:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/ipfs/${r}`},p2p:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=Og(e),n=Pg(e);if(t&&n!==null)return`https://${n}`;let o=t?"https://":"http://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let i=hr(s[0],s[1]??"",e);return i=i.replace("tcp://",""),`${o}${i}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return hr(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return hr(t[0],t[1]??"",e)},https:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=hr(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=Og(e),n=Pg(e);if(t&&n!==null)return`wss://${n}`;let o=t?"wss://":"ws://",s=e.pop();if(s===void 0)throw new Error("Unexpected end of multiaddr");let i=hr(s[0],s[1]??"",e);return i=i.replace("tcp://",""),`${o}${i}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=hr(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p-websocket-star`},"p2p-webrtc-star":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return`${hr(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function a1(r,e){let n=j(r).stringTuples(),o=n.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let s=ee(o[0]),i=Bg[s.name];if(i==null)throw new Error(`No interpreter found for ${s.name}`);let a=i(o[1]??"",n);return e?.assumeHttp!==!1&&BA.includes(o[0])&&(a=a.replace(/^.*:\/\//,""),o[1]==="443"?a=`https://${a}`:a=`http://${a}`),(a.startsWith("http://")||a.startsWith("https://"))&&(a=new URL(a).toString(),a.endsWith("/")&&(a=a.substring(0,a.length-1))),a}var c1=class{url;#e=0;#t=0;#r=0;#o=0;#a=new Map;log;constructor(e,t){this.url=e instanceof URL?e:new URL(e),this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#l(e){let t=e.multihash.bytes;return st.encode(t)}async getRawBlock(e,t){let n=new URL(this.url.toString());if(n.pathname=`/ipfs/${e.toString()}`,n.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let o=this.#l(e),s=new AbortController,i=()=>{s.abort()};t?.addEventListener("abort",i);try{let a=this.#a.get(o);return a==null&&(this.#e++,a=fetch(n.toString(),{signal:s.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async c=>{if(this.log("GET %s %d",n,c.status),!c.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);return this.#o++,new Uint8Array(await c.arrayBuffer())}),this.#a.set(o,a)),await a}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",i),this.#a.delete(o)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#o/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#o,pendingResponses:this.#a.size}}};function MA(r,e,t){return r.filter(n=>Lg.matches(n)||e&&Ng.matches(n)?t||n1.matches(n)?!0:Yt(n.toOptions().host)===!1:!1)}async function*l1(r,e,t,n,o,s){for await(let i of e.findProviders(r,s)){let a=MA(i.multiaddrs,n,o);if(a.length===0)continue;let c=a1(a[0]);yield new c1(c,t)}}var x2=class extends Es{routing;allowInsecure;allowLocal;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??u1,this.allowLocal=t.allowLocal??d1}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let o=await t.getRawBlock(e,n.signal);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(o),o}async*findNewProviders(e,t={}){yield*l1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}};function Mg(r,e){return new x2(r,e)}var f1=class{allowInsecure;allowLocal;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??u1,this.allowLocal=t.allowLocal??d1}async retrieve(e,t={}){let n=[];for await(let o of l1(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)){this.log("getting block for %c from %s",e,o.url);try{let s=await o.getRawBlock(e,t.signal);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(s)}catch(i){this.log.error("failed to validate block for %c from %s",e,o.url,i);continue}return s}catch(s){if(this.log.error("failed to get block for %c from %s",e,o.url,s),s instanceof Error?n.push(s):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return Mg({logger:this.logger,routing:this.routing},e)}};var u1=!1,d1=!1;function v2(r={}){return e=>new f1(e,r)}async function*h1(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var KA=Qe(Yo(),1);var $A=Qe(p1(),1);var Ug="ERR_IPNS_EXPIRED_RECORD",m1="ERR_UNRECOGNIZED_VALIDITY";var zn="ERR_SIGNATURE_VERIFICATION";var S2="ERR_UNDEFINED_PARAMETER",Fg="ERR_INVALID_RECORD_DATA",Vg="ERR_INVALID_VALUE",Kg="ERR_INVALID_EMBEDDED_KEY";var $g="ERR_RECORD_TOO_LARGE";var Xt;(function(r){let e;(function(o){o.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(o){o[o.EOL=0]="EOL"})(t||(t={})),function(o){o.codec=()=>He(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=ne((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.value!=null&&(s.uint32(10),s.bytes(o.value)),o.signatureV1!=null&&(s.uint32(18),s.bytes(o.signatureV1)),o.validityType!=null&&(s.uint32(24),r.ValidityType.codec().encode(o.validityType,s)),o.validity!=null&&(s.uint32(34),s.bytes(o.validity)),o.sequence!=null&&(s.uint32(40),s.uint64(o.sequence)),o.ttl!=null&&(s.uint32(48),s.uint64(o.ttl)),o.pubKey!=null&&(s.uint32(58),s.bytes(o.pubKey)),o.signatureV2!=null&&(s.uint32(66),s.bytes(o.signatureV2)),o.data!=null&&(s.uint32(74),s.bytes(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.value=o.bytes();break;case 2:i.signatureV1=o.bytes();break;case 3:i.validityType=r.ValidityType.codec().decode(o);break;case 4:i.validity=o.bytes();break;case 5:i.sequence=o.uint64();break;case 6:i.ttl=o.uint64();break;case 7:i.pubKey=o.bytes();break;case 8:i.signatureV2=o.bytes();break;case 9:i.data=o.bytes();break;default:o.skipType(c&7);break}}return i})),n),r.encode=o=>re(o,r.codec()),r.decode=o=>te(o,r.codec())})(Xt||(Xt={}));var pr=Qe(Yo(),1);var qg=ir("ipns:utils"),Gg=M("/ipns/"),UA=114,Wg=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw qg.error(n),(0,pr.default)(n,S2)}let t;if(e.pubKey!=null){try{t=zr(e.pubKey)}catch(o){throw qg.error(o),o}if(!(await dt(e.pubKey)).equals(r))throw(0,pr.default)(new Error("Embedded public key did not match PeerID"),Kg)}else r.publicKey!=null&&(t=zr(r.publicKey));if(t!=null)return t;throw(0,pr.default)(new Error("no public key is available"),S2)};var zg=r=>{let e=M("ipns-signature:");return ve([e,r])},tc=r=>"signatureV1"in r?Xt.encode({value:M(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:M(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):Xt.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data});function mn(r){let e=Xt.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw(0,pr.default)(new Error("missing data or signatureV2"),zn);let t=Xg(e.data),n=FA(t.Value),o=O(t.Validity);if(e.value!=null&&e.signatureV1!=null)return VA(e),{value:n,validityType:Xt.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:Xt.ValidityType.EOL,validity:o,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}var _2=r=>ve([Gg,r.toBytes()]),Yg=r=>Je(r.slice(Gg.length));var Xg=r=>{let e=kr(r);if(e.ValidityType===0)e.ValidityType=Xt.ValidityType.EOL;else throw(0,pr.default)(new Error("Unknown validity type"),m1);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e},FA=r=>{if(r!=null){if(Ms(r))return`/ipns/${r.toCID().toString(so)}`;if(r instanceof Uint8Array){let n=O(r);n.startsWith("/")&&(r=n)}let e=r.toString().trim();if(e.startsWith("/")&&e.length>1)return e;let t=le.asCID(r);if(t!=null)return t.code===UA?`/ipns/${t.toString(so)}`:`/ipfs/${t.toV1().toString()}`;try{return r instanceof Uint8Array?`/ipfs/${le.decode(r).toV1().toString()}`:`/ipfs/${le.parse(e).toV1().toString()}`}catch{}}throw(0,pr.default)(new Error("Value must be a valid content path starting with /"),Vg)},VA=r=>{if(r.data==null)throw(0,pr.default)(new Error("Record data is missing"),Fg);let e=Xg(r.data);if(!Z(e.Value,r.value??new Uint8Array(0)))throw(0,pr.default)(new Error('Field "value" did not match between protobuf and CBOR'),zn);if(!Z(e.Validity,r.validity??new Uint8Array(0)))throw(0,pr.default)(new Error('Field "validity" did not match between protobuf and CBOR'),zn);if(e.ValidityType!==r.validityType)throw(0,pr.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),zn);if(e.Sequence!==r.sequence)throw(0,pr.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),zn);if(e.TTL!==r.ttl)throw(0,pr.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),zn)};var nz=ir("ipns"),oz=Wt.code,sz=60*60*1e9,HA="/ipns/",iz=HA.length;var rc=Qe(Yo(),1),Qg=Qe(p1(),1);var g1=ir("ipns:validator"),qA=1024*10,GA=async(r,e)=>{let t=mn(e),n;try{let o=zg(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw g1.error("record signature verification failed"),(0,rc.default)(new Error("record signature verification failed"),zn);if(t.validityType===Xt.ValidityType.EOL){if(Qg.default.fromString(t.validity).toDate().getTime()<Date.now())throw g1.error("record has expired"),(0,rc.default)(new Error("record has expired"),Ug)}else if(t.validityType!=null)throw g1.error("unrecognized validity type"),(0,rc.default)(new Error("unrecognized validity type"),m1);g1("ipns record for %s is valid",t.value)};async function y1(r,e){if(e.byteLength>qA)throw(0,rc.default)(new Error("record too large"),$g);let t=Yg(r),n=mn(e),o=await Wg(t,n);await GA(o,e)}async function*nc(r){let e=/\r?\n/,t=new TextDecoder("utf8"),n="";for await(let o of r){typeof o=="string"&&(o=new TextEncoder().encode(o)),n+=t.decode(o,{stream:!0});let s=n.split(e);n=s.pop()??"";for(let i=0;i<s.length;i++)yield JSON.parse(s[i])}n+=t.decode(),n!==""&&(yield JSON.parse(n))}function WA(r){return r[Symbol.asyncIterator]!=null}function zA(r){if(WA(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var xs=zA;var A2=M("/ipns/");function jg(r){return Z(r.subarray(0,A2.byteLength),A2)}var Zg=r=>Je(r.slice(A2.length)),w1=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*Gt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async put(e,t,n){if(!jg(e))return;let o=Zg(e),s=mn(t);await this.client.putIPNS(o,s,n)}async get(e,t){if(!jg(e))throw new g("Not found","ERR_NOT_FOUND");let n=Zg(e);try{let o=await this.client.getIPNS(n,t);return tc(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new g("Not found","ERR_NOT_FOUND"):o}}},E1=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await xs(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new g("Not found","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){}};var Qt=ir("delegated-routing-v1-http-api-client"),Jg={concurrentRequests:4,timeout:3e4},b1=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal),this.httpQueue=new Ir({concurrency:t.concurrentRequests??Jg.concurrentRequests}),this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??Jg.timeout,this.contentRouting=new w1(this),this.peerRouting=new E1(this)}get[on](){return this.contentRouting}get[sn](){return this.peerRouting}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.shutDownController.abort(),this.started=!1}async*getProviders(e,t={}){Qt("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ae([this.shutDownController.signal,n,t.signal]);H(1/0,n,o);let s=J(),i=J();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=`${this.clientUrl}routing/v1/providers/${e.toString()}`,l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new g("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new g("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new g("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let h of u.Providers){let f=this.#e(h);f!=null&&(yield f)}}else for await(let u of nc(h1(l.body))){let h=this.#e(u);h!=null&&(yield h)}}catch(a){Qt.error("getProviders errored:",a)}finally{o.clear(),i.resolve(),Qt("getProviders finished: %c",e)}}async*getPeers(e,t={}){Qt("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ae([this.shutDownController.signal,n,t.signal]);H(1/0,n,o);let s=J(),i=J();this.httpQueue.add(async()=>(s.resolve(),i.promise));try{await s.promise;let a=`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`,l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new g("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new g("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new g("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let h of u.Peers){let f=this.#e(h);f!=null&&(yield f)}}else for await(let u of nc(h1(l.body))){let h=this.#e(u);h!=null&&(yield h)}}catch(a){Qt.error("getPeers errored:",a)}finally{o.clear(),i.resolve(),Qt("getPeers finished: %c",e)}}async getIPNS(e,t={}){Qt("getIPNS starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ae([this.shutDownController.signal,n,t.signal]);H(1/0,n,o);let s=J(),i=J();this.httpQueue.add(async()=>(s.resolve(),i.promise));let a=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await s.promise;let l=await fetch(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(Qt("getIPNS GET %s %d",a,l.status),l.status===404)throw new g("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new g("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new g("GET ipns response had no body","ERR_BAD_RESPONSE");let d=await l.arrayBuffer(),u=new Uint8Array(d,0,d.byteLength);return t.validate!==!1&&await y1(_2(e),u),mn(u)}catch(c){throw Qt.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),i.resolve(),Qt("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){Qt("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),s=Ae([this.shutDownController.signal,o,n.signal]);H(1/0,o,s);let i=J(),a=J();this.httpQueue.add(async()=>(i.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await i.promise;let l=tc(t),u=await fetch(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:s});if(Qt("putIPNS PUT %s %d",c,u.status),u.status!==200)throw new g("PUT ipns response had status other than 200","ERR_BAD_RESPONSE")}catch(l){throw Qt.error("putIPNS PUT %s error:",c,l.stack),l}finally{s.clear(),a.resolve(),Qt("putIPNS finished: %c",e)}}#e(e){let t=[],n=e.Addrs?.map(j)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:ge(e.ID),Addrs:n,Protocols:t}}};function e7(r,e={}){return new b1(new URL(r),e)}var t7="[a-fA-F\\d:]",Co=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${t7})|(?<=${t7})(?=\\s|$))`:"",Zr="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",ct="[a-fA-F\\d]{1,4}",x1=`
|
|
23
23
|
(?:
|
|
24
24
|
(?:${ct}:){7}(?:${ct}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
25
25
|
(?:${ct}:){6}(?:${Zr}|:${ct}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
|
|
@@ -49,7 +49,7 @@ a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host\r
|
|
|
49
49
|
a=ice-ufrag:`+e+`
|
|
50
50
|
`).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
51
51
|
a=ice-pwd:`+e+`
|
|
52
|
-
`),r}var LE=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),PE=r=>[...Array(r)].map(()=>LE.at(Math.floor(Math.random()*LE.length))).join("");var iN=1e4,Ace=ee("webrtc-direct").code,NE=ee("certhash").code,rf=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){throw Wy("WebRTCTransport.createListener")}listenFilter(e){return e.filter(Tg.exactMatch)}dialFilter(e){return this.listenFilter(e)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[an]=!0;async _connect(e,t){let n=new AbortController,o=n.signal,s=e.getPeerId();if(s===null)throw Bd("we need to have the remote's PeerId");let i=ge(s),a=F3(tf(e)),c=await Zi.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:V3(a.name)}),l=new Zi({certificates:[c]});try{let d=new Promise((R,T)=>{let P=l.createDataChannel("",{negotiated:!0,id:0}),N=setTimeout(()=>{let B=`Data channel was never opened: state: ${P.readyState}`;this.log.error(B),this.metrics?.dialerEvents.increment({open_error:!0}),T(o3("data",B))},iN);P.onopen=B=>{clearTimeout(N),R(P)},P.onerror=B=>{clearTimeout(N);let X=`Error opening a data channel for handshaking: ${B.target?.toString()??"not specified"}`;this.log.error(X),this.metrics?.dialerEvents.increment({unknown_error:!0}),T(o3("data",X))}}),u="libp2p+webrtc+v1/"+PE(32),h=await l.createOffer(),f=CE(h,u);await l.setLocalDescription(f);let p=kE(e,u);await l.setRemoteDescription(p);let m=await d,y=this.components.peerId,w=this.generateNoisePrologue(l,a.code,e),b=Pi({prologueBytes:w})(this.components),E=ji({channel:m,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),x={...E,sink:E.sink.bind(E),source:async function*(){for await(let R of E.source)for(let T of R)yield T}()},v=new ks(this.components,{peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),I=Sc?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(I,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":v.close().catch(R=>{this.log.error("error closing connection",R)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let S=new Cs(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(y,x,i),await t.upgrader.upgradeOutbound(v,{skipProtection:!0,skipEncryption:!0,muxerFactory:S})}catch(d){throw l.close(),d}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw Rc("no local certificate");let o=TE(e,{log:this.log});if(o==null)throw Rc("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=M(s,"hex"),a=OE.encode(i,t),c=U3.decode(tf(n)),l=M("libp2p-webrtc-noise:");return ve([l,a,c])}};function BE(r){return e=>new rf(e,r)}function ME(r){return e=>new Hd(e,r)}var UE=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",o),r.removeEventListener("error",s)}function o(){n(),e()}function s(i){n(),t(i.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",o),r.addEventListener("error",s)})};var FE=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let o of n){try{await UE(r)}catch(s){if(s.message==="socket closed")break;throw s}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(o)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((o,s)=>{r.addEventListener("close",i=>{if(i.wasClean||i.code===1006)o();else{let a=Object.assign(new Error("ws error"),{event:i});s(a)}}),setTimeout(()=>{r.close()})})});var HE=Qe(KE(),1);function $E(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var qE=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,i)=>{if(n){s();return}if(o!=null){i(o);return}let a=d=>{r.removeEventListener("open",c),r.removeEventListener("error",l),d()},c=()=>{a(s)},l=d=>{a(()=>{i(d.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let s=new HE.EventIterator(({push:i,stop:a,fail:c})=>{let l=u=>{let h=null;typeof u.data=="string"&&(h=M(u.data)),$E(u.data)&&(h=new Uint8Array(u.data)),u.data instanceof Uint8Array&&(h=u.data),h!=null&&i(h)},d=u=>{c(u.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",d),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",d),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let i of s)yield $E(i)?new Uint8Array(i):i}(),n=r.readyState===1,o;return r.addEventListener("open",()=>{n=!0,o=null}),r.addEventListener("close",()=>{n=!1,o=null}),r.addEventListener("error",s=>{n||(o=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var GE=(r,e)=>{e=e??{};let t=qE(r),n=e.remoteAddress,o=e.remotePort;if(r.url!=null)try{let i=new URL(r.url);n=i.hostname,o=parseInt(i.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:FE(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(i=>{r.addEventListener("close",()=>{i()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:o,socket:r}};var WE=WebSocket;var cN={"http:":"ws:","https:":"wss:"},zE="ws:",YE=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??zE}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??zE,o=e.host,s=e.port!=null&&o?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${o}${s}${r}`}let t=new URL(r);for(let[n,o]of Object.entries(cN))t.protocol===n&&(t.protocol=o);return t};function XE(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=YE(r,t),o=new WE(n.toString(),e.websocket);return GE(o,e)}function QE(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Mi.matches(t)||_s.matches(t)})}function jE(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return _s.matches(t)})}function ZE(){throw new Error("WebSocket Servers can not be created in the browser!")}function JE(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),o={log:n,async sink(s){try{await r.sink(async function*(){for await(let i of s)i instanceof Uint8Array?yield i:yield i.subarray()}())}catch(i){i.type!=="aborted"&&n.error(i)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(s={}){let i=Date.now();if(s.signal==null){let c=AbortSignal.timeout(500);s={...s,signal:c}}let a=()=>{let{host:c,port:l}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",c,l,Date.now()-i),this.abort(new g("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};s.signal?.addEventListener("abort",a);try{await r.close()}catch(c){n.error("error closing WebSocket gracefully",c),this.abort(c)}finally{s.signal?.removeEventListener("abort",a),o.timeline.close=Date.now()}},abort(s){let{host:i,port:a}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",i,a,s),r.destroy(),o.timeline.close=Date.now()}};return r.socket.addEventListener("close",()=>{o.timeline.close==null&&(o.timeline.close=Date.now())},{once:!0}),o}var H3=class{log;init;logger;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.init=t}[Symbol.toStringTag]="@libp2p/websockets";[an]=!0;async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),o=JE(n,e,{logger:this.logger});this.log("new outbound connection %s",o.remoteAddr);let s=await t.upgrader.upgradeOutbound(o);return this.log("outbound connection %s upgraded",o.remoteAddr),s}async _connect(e,t){if(t?.signal?.aborted===!0)throw new Kt;let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let o=J(),s=XE(a1(e),this.init);if(s.socket.addEventListener("error",()=>{let c=new g(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",c),o.reject(c)}),t.signal==null)return await Promise.race([s.connected(),o.promise]),this.log("connected %s",e),s;let i,a=new Promise((c,l)=>{if(i=()=>{l(new Kt),s.close().catch(d=>{this.log.error("error closing raw socket",d)})},t?.signal?.aborted===!0){i();return}t?.signal?.addEventListener("abort",i)});try{await Promise.race([a,o.promise,s.connected()])}finally{i!=null&&t?.signal?.removeEventListener("abort",i)}return this.log("connected %s",e),s}createListener(e){return ZE({logger:this.logger},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):ed||td?jE(e):QE(e)}dialFilter(e){return this.listenFilter(e)}};function eb(r={}){return e=>new H3(e,r)}function q3(r){throw new Error("Not implemented")}var G3=class extends yn{writer;reader;constructor(e){super(e),this.writer=e.bidiStream.writable.getWriter(),this.reader=e.bidiStream.readable.getReader(),Promise.resolve().then(async()=>{for(;;){let t=await this.reader.read();if(t.done){e.log("remote closed write");return}t.value!=null&&this.sourcePush(new ce(t.value))}}).catch(t=>{e.log.error("error reading from stream",t),this.abort(t)}).finally(()=>{this.remoteCloseWrite()}),this.writer.closed.then(()=>{e.log("writer closed")}).catch(t=>{e.log("writer close promise rejected",t)}).finally(()=>{this.remoteCloseRead()})}sendNewStream(e){}async sendData(e,t){for await(let n of e)this.log("sendData waiting for writer to be ready"),await Ue(this.writer.ready,t?.signal),this.writer.write(n).catch(o=>{this.log.error("error sending stream data",o)})}async sendReset(e){this.log("sendReset aborting writer"),await Ue(this.writer.abort(),e?.signal),this.log("sendReset aborted writer")}async sendCloseWrite(e){this.log("sendCloseWrite closing writer"),await Ue(this.writer.close(),e?.signal),this.log("sendCloseWrite closed writer")}async sendCloseRead(e){this.log("sendCloseRead cancelling reader"),await Ue(this.reader.cancel(),e?.signal),this.log("sendCloseRead cancelled reader")}};async function W3(r,e,t,n,o,s){let i=s.forComponent(`libp2p:webtransport:stream:${t}:${e}`),a=new G3({bidiStream:r,id:e,direction:t,log:i,onEnd:()=>{let c=n.findIndex(l=>l===a);c!==-1&&n.splice(c,1),o?.(a)}});return a}function sf(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}function tb(r,e,t,n){let o=0,s=t.forComponent("libp2p:webtransport:muxer");return{protocol:"webtransport",createStreamMuxer:i=>{typeof i=="function"&&(i={onIncomingStream:i});let a=[];return Promise.resolve().then(async()=>{for(;;){let{done:l,value:d}=await e.read();if(l)break;if(a.length>=n.maxInboundStreams)s(`too many inbound streams open - ${a.length}/${n.maxInboundStreams}, closing new incoming stream`),d.writable.close().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),d.readable.cancel().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await W3(d,String(o++),"inbound",a,i?.onStreamEnd,t);a.push(u),i?.onIncomingStream?.(u)}}}),{protocol:"webtransport",streams:a,newStream:async l=>{s("new outgoing stream",l);let d=await r.createBidirectionalStream(),u=await W3(d,String(o++),i?.direction??"outbound",a,i?.onStreamEnd,t);return a.push(u),u},close:async()=>{s("closing webtransport muxer gracefully"),r.close()},abort:l=>{s("closing webtransport muxer with err:",l),r.close()},...sf()}}}}function rb(r,e){return e.filter(n=>!!r.find(o=>Z(n,o))).length===e.length}var fN=Object.values(br).map(r=>r.decoder).reduce((r,e)=>r.or(e));function hN(r){return Er.decode(fN.decode(r))}function z3(r){if(!i1.matches(r))throw new g("Invalid multiaddr, was not a WebTransport address","ERR_INVALID_MULTIADDR");let e=r.stringTuples(),t=e.filter(([i,a])=>i===ee("certhash").code).map(([i,a])=>hN(a??"")),n=e.filter(([i,a])=>i===ee("p2p").code).map(([i,a])=>ge(a??""))[0],o=r.toOptions(),s=o.host;return o.family===6&&s?.includes(":")&&(s=`[${s}]`),{url:`https://${s}:${o.port}`,certhashes:t,remotePeer:n}}var nb=WebTransport;var Y3=class{log;components;config;metrics;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webtransport"),this.components=e,this.config={...t,maxInboundStreams:t.maxInboundStreams??1e3,certificates:t.certificates??[]},e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webtransport_dialer_events_total",{label:"event",help:"Total count of WebTransport dialer events by type"})})}[Symbol.toStringTag]="@libp2p/webtransport";[an]=!0;async dial(e,t){if(t?.signal?.aborted===!0)throw new Kt;this.log("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new g("Need a local peerid","ERR_INVALID_PARAMETERS");t=t??{};let{url:o,certhashes:s,remotePeer:i}=z3(e);if(i==null)throw new g("Need a target peerid","ERR_INVALID_PARAMETERS");if(s.length===0)throw new g("Expected multiaddr to contain certhashes","ERR_INVALID_PARAMETERS");let a,c,l=()=>{},d=!1,u=!1,h=!1;try{this.metrics?.dialerEvents.increment({pending:!0});let f=new nb(`${o}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(p=>({algorithm:"sha-256",value:p.digest}))});if(l=p=>{if(!d)try{this.metrics?.dialerEvents.increment({[p]:!0}),f.close()}catch(m){this.log.error("error closing wt session",m)}finally{c!=null&&(c.timeline.close=Date.now()),d=!0}},a=()=>{l(u?"noise_timeout":"ready_timeout")},t.signal?.addEventListener("abort",a,{once:!0}),this.log("wait for session to be ready"),await Promise.race([f.closed,f.ready]),this.log("session became ready"),u=!0,this.metrics?.dialerEvents.increment({ready:!0}),f.closed.catch(p=>{this.log.error("error on remote wt session close",p)}).finally(()=>{l("remote_close")}),h=await Ue(this.authenticateWebTransport(f,n,i,s),t.signal),!h)throw new g("Failed to authenticate webtransport","ERR_AUTHENTICATION_FAILED");return this.metrics?.dialerEvents.increment({open:!0}),c={close:async()=>{this.log("closing webtransport"),l("close")},abort:p=>{this.log("aborting webtransport due to passed err",p),l("abort")},remoteAddr:e,timeline:{open:Date.now()},log:this.components.logger.forComponent("libp2p:webtransport:maconn"),...sf()},await t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:tb(f,f.incomingBidirectionalStreams.getReader(),this.components.logger,this.config),skipProtection:!0})}catch(f){throw this.log.error("caught wt session err",f),l(h?"upgrade_error":u?"noise_error":"ready_error"),f}finally{a!=null&&t.signal?.removeEventListener("abort",a)}}async authenticateWebTransport(e,t,n,o,s){if(s?.aborted===!0)throw new Kt;let i=await e.createBidirectionalStream(),a=i.writable.getWriter(),c=i.readable.getReader(),l={source:async function*(){for(;;){let h=await c.read();if(h.value!=null&&(yield h.value),h.done)break}}(),sink:async h=>{for await(let f of h){await Ue(a.ready,s);let p=f instanceof Uint8Array?f:f.subarray();a.write(p).catch(m=>{this.log.error("could not write chunk during authentication of WebTransport stream",m)})}}},d=Pi()(this.components),{remoteExtensions:u}=await d.secureOutbound(t,l,n);if(a.close().catch(h=>{this.log.error(`Failed to close authentication stream writer: ${h.message}`)}),c.cancel().catch(h=>{this.log.error(`Failed to close authentication stream reader: ${h.message}`)}),!rb(u?.webtransportCerthashes??[],o.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}createListener(e){return q3(this.components,{...e,certificates:this.config.certificates,maxInboundStreams:this.config.maxInboundStreams})}listenFilter(){return[]}dialFilter(e){return e.filter(t=>{if(!i1.exactMatch(t))return!1;let{url:n,certhashes:o,remotePeer:s}=z3(t);return n!=null&&s!=null&&o.length>0})}};function ob(r={}){return e=>new Y3(e,r)}var X3=Qe(p1(),1);function sb(r,e){let t=e.map((n,o)=>({record:mn(n),index:o}));return t.sort((n,o)=>{let s=n.record.sequence,i=o.record.sequence;if(s>i)return-1;if(s<i)return 1;if(n.record.validityType===Xt.ValidityType.EOL&&o.record.validityType===Xt.ValidityType.EOL){let a=X3.default.fromString(n.record.validity).toDate(),c=X3.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var af="1.5.2",cf="libp2p";var ab="4.2.1-e6b976a",cb="helia";var lb={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function lf(r={}){let e=`${cb}/${ab} ${cf}/${af} UserAgent=${globalThis.navigator.userAgent}`;return{peerId:r.peerId,dns:r.dns,addresses:{listen:["/webrtc"]},transports:[kp({discoverRelays:1}),ME(),BE(),ob(),eb()],connectionEncryption:[Pi()],streamMuxers:[j7(),Ky()],peerDiscovery:[h9(lb)],services:{autoNAT:t9(),dcutr:D9(),delegatedRouting:()=>e7("https://delegated-ipfs.dev"),dht:py({clientMode:!0,validators:{ipns:y1},selectors:{ipns:sb}}),identify:$9({agentVersion:e}),identifyPush:H9({agentVersion:e}),keychain:Nd(r.keychain),ping:Gy()}}}var It={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var ca;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>re(i,o.codec()),o.decode=i=>te(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),df.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=df.codec().decode(i,i.uint32());break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>re(i,o.codec()),o.decode=i=>te(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ne((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),uf.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(uf.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let l=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(l.key,l.value);break}case 7:{let l=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(l.key,l.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>re(o,r.codec()),r.decode=o=>te(o,r.codec())})(ca||(ca={}));var uf;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(uf||(uf={}));var df;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(df||(df={}));function la(r,e){let t=ca.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=um({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:j(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Q3="/peers/";function ua(r){if(!Ms(r)||r.type==null)throw new g("Invalid PeerId",It.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Pe(`${Q3}${e}`)}async function ub(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=j(o.multiaddr)),!ko(o.multiaddr))throw new g("Multiaddr was invalid",It.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function hf(r,e,t,n){if(e==null)throw new g("Invalid PeerData",It.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!Z(e.publicKey,r.publicKey))throw new g("publicKey bytes do not match peer id publicKey bytes",It.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new g("peer id did not match existing peer id",It.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=ff(u,{validate:db})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ff(u,{validate:fb,map:hb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,f]of u)f==null?a.delete(h):a.set(h,f);a=ff([...a.entries()],{validate:db})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[f,p]of u)p==null?h.delete(f):h.set(f,p);c=ff([...h.entries()],{validate:fb,map:hb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let d={addresses:await ub(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((u,h)=>u.localeCompare(h)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:l};return r.type!=="RSA"&&delete d.publicKey,d}function ff(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function db(r,e){if(typeof r!="string")throw new g("Metadata key must be a string",It.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new g("Metadata value must be a Uint8Array",It.ERR_INVALID_PARAMETERS)}function fb(r,e){if(typeof r!="string")throw new g("Tag name must be a string",It.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new g("Tag value must be an integer",It.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new g("Tag value must be between 0-100",It.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new g("Tag ttl must be an integer",It.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new g("Tag ttl must be between greater than 0",It.ERR_INVALID_PARAMETERS)}}function hb(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function pf(r,e,t){let n=r.toString().split("/")[2],o=ut.decode(n),s=Je(o),i=t.get(s);if(i!=null)return i;let a=la(s,e);return t.set(s,a),a}function pN(r,e){return r==null?{}:{prefix:Q3,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(pf(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(pf(n.key,n.value,e),pf(o.key,o.value,e)))}}var mf=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Ya({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(ua(e))}async delete(e){if(this.peerId.equals(e))throw new g("Cannot delete self peer",It.ERR_INVALID_PARAMETERS);await this.datastore.delete(ua(e))}async load(e){let t=await this.datastore.get(ua(e));return la(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new it;for await(let{key:n,value:o}of this.datastore.query(pN(e??{},t))){let s=pf(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(ua(e)),n=la(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=ca.encode(t);return n!=null&&Z(s,n)?{peer:la(e,s),previous:o,updated:!1}:(await this.datastore.put(ua(e),s),{peer:la(e,s),previous:o,updated:!0})}};var gf=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new mf(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await sc(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mr.openAndCertify(e,Vt.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Vt.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await mr.createFromProtobuf(s.peerRecordEnvelope),a=Vt.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function pb(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var mN=r=>r;function j3(r,e){let t=r.getPeerId();return t!=null&&ge(t).equals(e)&&(r=r.decapsulate(j(`/p2p/${e.toString()}`))),r}var yf=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??mN,this._updatePeerStoreAddresses=pb(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>j(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>j(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>j(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>j(e))}addObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>j(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var Z3=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=So())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Fc(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},gN=["metrics","connectionProtector","dns"],yN=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function mb(r={}){let e=new Z3(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!yN.includes(o)){let i=e.components[o];if(i==null&&!gN.includes(o))throw new g(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function gb(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Yt(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function J3(r){try{let{address:e}=r.nodeAddress();return!!Yt(e)}catch{return!0}}function wN(r,e){let t=J3(r.multiaddr),n=J3(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function EN(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function bN(r,e){let t=bs.exactMatch(r.multiaddr),n=bs.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function da(r,e){let t=wN(r,e);if(t!==0)return t;let n=bN(r,e);return n!==0?n:EN(r,e)}var xN=32,{code:vN}=ee("dnsaddr"),Ps=async function(e,t={}){let n=t.maxRecursiveDepth??xN;if(n===0)throw new g("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([l])=>l===vN)??[],i=await(t?.dns??wu()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[ar.TXT]}),a=e.getPeerId(),c=[];for(let l of i.Answer){let d=l.data.split("=")[1];if(d==null||a!=null&&!d.includes(a))continue;let u=j(d);if(d.startsWith("/dnsaddr")){let h=await u.resolve({...t,maxRecursiveDepth:n-1});c.push(...h.map(f=>f.toString()))}else c.push(u.toString())}return c};var Jn;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Jn||(Jn={}));var z;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(z||(z={}));var RN={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ps},addressSorter:da},transportManager:{faultTolerance:to.FATAL_ALL}};async function yb(r){let e=Xi(RN,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new g(Jn.ERR_PROTECTOR_REQUIRED,z.ERR_PROTECTOR_REQUIRED);if(!(await dt(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new g("Private key doesn't match peer id",z.ERR_INVALID_KEY);return e}function wf(r){if(Ms(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:ge(t),r.forEach(n=>{if(!ko(n))throw new g("Invalid Multiaddr",z.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new g("Multiaddrs must all have the same peer id or have no peer id",z.ERR_INVALID_PARAMETERS)}else{let s=ge(o);if(e==null||!e.equals(s))throw new g("Multiaddrs must all have the same peer id or have no peer id",z.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}var Ef="last-dial-failure";var bf=5,xf=100,vf=50,Rf=1e3*60*7;var Os={minConnections:bf,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Rf,autoDialDiscoveredPeersDebounce:10},Sf=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Os.minConnections,this.autoDialPriority=t.autoDialPriority??Os.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Os.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Os.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Os.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Os.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new wr({concurrency:t.autoDialConcurrency??Os.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new ht(this.connectionManager.getDialQueue().map(l=>l.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[l=>l.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",l.id),!1):e.has(l.id)?(this.log.trace("not autodialing %p because they are already connected",l.id),!1):n.has(l.id)?(this.log.trace("not autodialing %p because they are already being dialed",l.id),!1):this.queue.has(l.id)?(this.log.trace("not autodialing %p because they are already being autodialed",l.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new it;for(let l of s)i.has(l.id)||i.set(l.id,[...l.tags.values()].reduce((d,u)=>d+u.value,0));let c=s.sort((l,d)=>{let u=i.get(l.id)??0,h=i.get(d.id)??0;return u>h?-1:u<h?1:0}).filter(l=>{let d=l.metadata.get(Ef);if(d==null)return!0;let u=parseInt(O(d));return isNaN(u)?!0:Date.now()-u>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let l of c)this.queue.add(async()=>{let d=this.connectionManager.getConnectionsMap().size;if(d>=this.minConnections){this.log("got enough connections now %d/%d",d,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",l.id),await this.connectionManager.openConnection(l.id,{priority:this.autoDialPriority})},{peerId:l.id}).catch(d=>{this.log.error("could not connect to peerStore stored peer",d)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var _N=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function wb(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??_N;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Eb={maxConnections:xf,allow:[]},_f=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Eb.maxConnections,this.allow=t.allow??Eb.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new it;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((d,u)=>d+u.value,0))}catch(l){l.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>a.remoteAddr.toString().startsWith(l.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await wb(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Af=class extends tr{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};async function bb(r,e){let t=!1;for(let o of Di.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var Lc={addressSorter:da,maxParallelDials:vf,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Ps}},If=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Lc.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Lc.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Lc.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Lc.dialTimeout,this.connections=t.connections??new it,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))Di.set(n,o);this.queue=new Af({concurrency:t.maxParallelDials??Lc.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=wf(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new g("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),this.queue.add(async a=>{let c=this.createDialAbortController(a?.signal),l;try{l=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),l.map(({multiaddr:d})=>d.toString()).forEach(d=>{a?.multiaddrs.add(d)})}catch(d){throw c.clear(),d}try{let d=0,u=[];for(let h of l){if(d===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",d,n),new g("Peer had more than maxPeerAddrsToDial",z.ERR_TOO_MANY_ADDRESSES);d++;try{let f=await this.components.transportManager.dial(h.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",h.multiaddr),f}catch(f){if(this.log.error("dial failed to %a",h.multiaddr,f),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[Ef]:M(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new g(f.message,vn);u.push(f)}}throw u.length===1?u[0]:new Uc(u,"All multiaddr dials failed",z.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??a4,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=Ae([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return H(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:j(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new g("Tried to dial self",z.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new g("The dial request is blocked by gater.allowDialPeer",z.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:h})=>h.toString()))}catch(u){if(u.code!==z.ERR_NOT_FOUND)throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:h})=>h.toString())),o.push(...u.multiaddrs.map(h=>({multiaddr:h,isCertified:!1})))}catch(u){u.code!==z.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,u)}}}let s=(await Promise.all(o.map(async u=>{let h=await bb(u.multiaddr,{dns:this.components.dns,...n,log:this.log});return h.length===1&&h[0].equals(u.multiaddr)?u:h.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;s=s.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(u),isCertified:h.isCertified}:h)}let i=s.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let h=u.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),a=new Map;for(let u of i){let h=u.multiaddr.toString(),f=a.get(h);if(f!=null){f.isCertified=f.isCertified||u.isCertified||!1;continue}a.set(h,u)}let c=[...a.values()];if(c.length===0)throw new g("The dial request has no valid addresses",z.ERR_NO_VALID_ADDRESSES);let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let d=l.sort(this.addressSorter);if(d.length===0)throw new g("The connection gater denied all addresses in the dial request",z.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",d.map(({multiaddr:u})=>u.toString())),d}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!bs.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var a4=50,eo={minConnections:bf,maxConnections:xf,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Rf,autoDialDiscoveredPeersDebounce:10},Df=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??eo.maxConnections;let n=t.minConnections??eo.minConnections;if(this.maxConnections<n)throw new g("Connection Manager maxConnections must be greater than minConnections",z.ERR_INVALID_PARAMETERS);this.connections=new it,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(o=>j(o)),this.deny=(t.deny??[]).map(o=>j(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??eo.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Qi({points:t.inboundConnectionThreshold??eo.inboundConnectionThreshold,duration:1}),this.autoDial=new Sf({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??eo.autoDialConcurrency,autoDialPriority:t.autoDialPriority??eo.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??eo.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??eo.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??eo.autoDialMaxQueueLength}),this.connectionPruner=new _f({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new If(e,{addressSorter:t.addressSorter??da,maxParallelDials:t.maxParallelDials??vf,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Ps},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(R4)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new g("Not started",z.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=wf(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??a4}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>j(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Tf=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new g("No content routers available",z.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ht;for await(let s of Mt(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new g("No content routers available",z.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new g(Jn.NOT_STARTED_YET,z.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new g(Jn.NOT_STARTED_YET,z.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var kf=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}async findPeer(e,t){if(this.routers.length===0)throw new g("No peer routers available",z.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new g("Should not try to find self",z.ERR_FIND_SELF);let n=this,o=Mt(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new g(Jn.NOT_FOUND,z.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new g("No peer routers available",z.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ht;for await(let s of en(async function*(){let i=Mt(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}};var Cf=class extends ye{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,H(1/0,this.shutdownController.signal)}start(){this.shutdownController=new AbortController,H(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ae([this.shutdownController.signal,e?.signal]);H(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=J(),yield(await er(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,H(1/0,this.walkController.signal);let e=Ae([this.walkController.signal,this.shutdownController.signal]);H(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{for await(let o of this.peerRouting.getClosestPeers(pt(32),{signal:e}))e.throwIfAborted(),this.log("found peer %p",o.id),n++,this.safeDispatchEvent("walk:peer",{detail:o}),this.walkers===1&&this.needNext!=null&&await Ue(this.needNext.promise,e)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var c4=32,l4=64,Nf=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new g(`No handler registered for protocol ${e}`,z.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new g(`Handler already registered for protocol ${e}`,z.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=Xi.bind({ignoreUndefined:!0})({maxInboundStreams:c4,maxOutboundStreams:l4},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new g("invalid topology",z.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.onDisconnect?.(t)}}).catch(n=>{n.code!==z.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.onDisconnect?.(t.id)}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.onConnect?.(o,n)}}};var Lf=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Wu({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??to.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new g("Transport must have a valid tag",z.ERR_INVALID_KEY);if(this.transports.has(t))throw new g(`There is already a transport with the tag ${t}`,z.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new g(`No transport available for address ${String(e)}`,z.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=z.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new g("Not started",z.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let l of s){this.log("creating listener for %s on %a",n,l);let d=o.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(n)??[];u==null&&(u=[],this.listeners.set(n,u)),u.push(d),d.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:d})}),d.addEventListener("close",()=>{let h=u.findIndex(f=>f===d);u.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:d})}),i.push(d.listen(l))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(l=>l.status==="fulfilled")==null&&this.faultTolerance!==to.NO_FATAL)throw new g(`Transport (${n}) could not listen on any available address`,z.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===to.FATAL_ALL)throw new g(n,z.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Dt="/multistream/1.0.0";var DN=M(`
|
|
52
|
+
`),r}var LE=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),PE=r=>[...Array(r)].map(()=>LE.at(Math.floor(Math.random()*LE.length))).join("");var iN=1e4,Ace=ee("webrtc-direct").code,NE=ee("certhash").code,rf=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}async dial(e,t){let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){throw Wy("WebRTCTransport.createListener")}listenFilter(e){return e.filter(Tg.exactMatch)}dialFilter(e){return this.listenFilter(e)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[an]=!0;async _connect(e,t){let n=new AbortController,o=n.signal,s=e.getPeerId();if(s===null)throw Bd("we need to have the remote's PeerId");let i=ge(s),a=F3(tf(e)),c=await Zi.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:V3(a.name)}),l=new Zi({certificates:[c]});try{let d=new Promise((R,T)=>{let P=l.createDataChannel("",{negotiated:!0,id:0}),N=setTimeout(()=>{let B=`Data channel was never opened: state: ${P.readyState}`;this.log.error(B),this.metrics?.dialerEvents.increment({open_error:!0}),T(o3("data",B))},iN);P.onopen=B=>{clearTimeout(N),R(P)},P.onerror=B=>{clearTimeout(N);let X=`Error opening a data channel for handshaking: ${B.target?.toString()??"not specified"}`;this.log.error(X),this.metrics?.dialerEvents.increment({unknown_error:!0}),T(o3("data",X))}}),u="libp2p+webrtc+v1/"+PE(32),h=await l.createOffer(),f=CE(h,u);await l.setLocalDescription(f);let p=kE(e,u);await l.setRemoteDescription(p);let m=await d,y=this.components.peerId,w=this.generateNoisePrologue(l,a.code,e),b=Pi({prologueBytes:w})(this.components),E=ji({channel:m,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),x={...E,sink:E.sink.bind(E),source:async function*(){for await(let R of E.source)for(let T of R)yield T}()},v=new ks(this.components,{peerConnection:l,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),I=Sc?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(I,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":v.close().catch(R=>{this.log.error("error closing connection",R)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let S=new Cs(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await b.secureInbound(y,x,i),await t.upgrader.upgradeOutbound(v,{skipProtection:!0,skipEncryption:!0,muxerFactory:S})}catch(d){throw l.close(),d}}generateNoisePrologue(e,t,n){if(e.getConfiguration().certificates?.length===0)throw Rc("no local certificate");let o=TE(e,{log:this.log});if(o==null)throw Rc("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=M(s,"hex"),a=OE.encode(i,t),c=U3.decode(tf(n)),l=M("libp2p-webrtc-noise:");return ve([l,a,c])}};function BE(r){return e=>new rf(e,r)}function ME(r){return e=>new Hd(e,r)}var UE=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",o),r.removeEventListener("error",s)}function o(){n(),e()}function s(i){n(),t(i.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",o),r.addEventListener("error",s)})};var FE=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let o of n){try{await UE(r)}catch(s){if(s.message==="socket closed")break;throw s}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(o)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((o,s)=>{r.addEventListener("close",i=>{if(i.wasClean||i.code===1006)o();else{let a=Object.assign(new Error("ws error"),{event:i});s(a)}}),setTimeout(()=>{r.close()})})});var HE=Qe(KE(),1);function $E(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var qE=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((s,i)=>{if(n){s();return}if(o!=null){i(o);return}let a=d=>{r.removeEventListener("open",c),r.removeEventListener("error",l),d()},c=()=>{a(s)},l=d=>{a(()=>{i(d.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=async function*(){let s=new HE.EventIterator(({push:i,stop:a,fail:c})=>{let l=u=>{let h=null;typeof u.data=="string"&&(h=M(u.data)),$E(u.data)&&(h=new Uint8Array(u.data)),u.data instanceof Uint8Array&&(h=u.data),h!=null&&i(h)},d=u=>{c(u.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",d),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",d),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let i of s)yield $E(i)?new Uint8Array(i):i}(),n=r.readyState===1,o;return r.addEventListener("open",()=>{n=!0,o=null}),r.addEventListener("close",()=>{n=!1,o=null}),r.addEventListener("error",s=>{n||(o=s.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var GE=(r,e)=>{e=e??{};let t=qE(r),n=e.remoteAddress,o=e.remotePort;if(r.url!=null)try{let i=new URL(r.url);n=i.hostname,o=parseInt(i.port,10)}catch{}if(n==null||o==null)throw new Error("Remote connection did not have address and/or port");return{sink:FE(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(i=>{r.addEventListener("close",()=>{i()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:o,socket:r}};var WE=WebSocket;var cN={"http:":"ws:","https:":"wss:"},zE="ws:",YE=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??zE}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??zE,o=e.host,s=e.port!=null&&o?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${o}${s}${r}`}let t=new URL(r);for(let[n,o]of Object.entries(cN))t.protocol===n&&(t.protocol=o);return t};function XE(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=YE(r,t),o=new WE(n.toString(),e.websocket);return GE(o,e)}function QE(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return Mi.matches(t)||_s.matches(t)})}function jE(r){return r.filter(e=>{if(e.protoCodes().includes(290))return!1;let t=e.decapsulateCode(421);return _s.matches(t)})}function ZE(){throw new Error("WebSocket Servers can not be created in the browser!")}function JE(r,e,t){let n=t.logger.forComponent("libp2p:websockets:maconn"),o={log:n,async sink(s){try{await r.sink(async function*(){for await(let i of s)i instanceof Uint8Array?yield i:yield i.subarray()}())}catch(i){i.type!=="aborted"&&n.error(i)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(s={}){let i=Date.now();if(s.signal==null){let c=AbortSignal.timeout(500);s={...s,signal:c}}let a=()=>{let{host:c,port:l}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",c,l,Date.now()-i),this.abort(new g("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};s.signal?.addEventListener("abort",a);try{await r.close()}catch(c){n.error("error closing WebSocket gracefully",c),this.abort(c)}finally{s.signal?.removeEventListener("abort",a),o.timeline.close=Date.now()}},abort(s){let{host:i,port:a}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",i,a,s),r.destroy(),o.timeline.close=Date.now()}};return r.socket.addEventListener("close",()=>{o.timeline.close==null&&(o.timeline.close=Date.now())},{once:!0}),o}var H3=class{log;init;logger;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.init=t}[Symbol.toStringTag]="@libp2p/websockets";[an]=!0;async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),o=JE(n,e,{logger:this.logger});this.log("new outbound connection %s",o.remoteAddr);let s=await t.upgrader.upgradeOutbound(o);return this.log("outbound connection %s upgraded",o.remoteAddr),s}async _connect(e,t){if(t?.signal?.aborted===!0)throw new Kt;let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let o=J(),s=XE(a1(e),this.init);if(s.socket.addEventListener("error",()=>{let c=new g(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",c),o.reject(c)}),t.signal==null)return await Promise.race([s.connected(),o.promise]),this.log("connected %s",e),s;let i,a=new Promise((c,l)=>{if(i=()=>{l(new Kt),s.close().catch(d=>{this.log.error("error closing raw socket",d)})},t?.signal?.aborted===!0){i();return}t?.signal?.addEventListener("abort",i)});try{await Promise.race([a,o.promise,s.connected()])}finally{i!=null&&t?.signal?.removeEventListener("abort",i)}return this.log("connected %s",e),s}createListener(e){return ZE({logger:this.logger},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):ed||td?jE(e):QE(e)}dialFilter(e){return this.listenFilter(e)}};function eb(r={}){return e=>new H3(e,r)}function q3(r){throw new Error("Not implemented")}var G3=class extends yn{writer;reader;constructor(e){super(e),this.writer=e.bidiStream.writable.getWriter(),this.reader=e.bidiStream.readable.getReader(),Promise.resolve().then(async()=>{for(;;){let t=await this.reader.read();if(t.done){e.log("remote closed write");return}t.value!=null&&this.sourcePush(new ce(t.value))}}).catch(t=>{e.log.error("error reading from stream",t),this.abort(t)}).finally(()=>{this.remoteCloseWrite()}),this.writer.closed.then(()=>{e.log("writer closed")}).catch(t=>{e.log("writer close promise rejected",t)}).finally(()=>{this.remoteCloseRead()})}sendNewStream(e){}async sendData(e,t){for await(let n of e)this.log("sendData waiting for writer to be ready"),await Ue(this.writer.ready,t?.signal),this.writer.write(n).catch(o=>{this.log.error("error sending stream data",o)})}async sendReset(e){this.log("sendReset aborting writer"),await Ue(this.writer.abort(),e?.signal),this.log("sendReset aborted writer")}async sendCloseWrite(e){this.log("sendCloseWrite closing writer"),await Ue(this.writer.close(),e?.signal),this.log("sendCloseWrite closed writer")}async sendCloseRead(e){this.log("sendCloseRead cancelling reader"),await Ue(this.reader.cancel(),e?.signal),this.log("sendCloseRead cancelled reader")}};async function W3(r,e,t,n,o,s){let i=s.forComponent(`libp2p:webtransport:stream:${t}:${e}`),a=new G3({bidiStream:r,id:e,direction:t,log:i,onEnd:()=>{let c=n.findIndex(l=>l===a);c!==-1&&n.splice(c,1),o?.(a)}});return a}function sf(){return{source:{[Symbol.asyncIterator](){return{async next(){return new Promise(()=>{})}}}},sink:async r=>new Promise(()=>{})}}function tb(r,e,t,n){let o=0,s=t.forComponent("libp2p:webtransport:muxer");return{protocol:"webtransport",createStreamMuxer:i=>{typeof i=="function"&&(i={onIncomingStream:i});let a=[];return Promise.resolve().then(async()=>{for(;;){let{done:l,value:d}=await e.read();if(l)break;if(a.length>=n.maxInboundStreams)s(`too many inbound streams open - ${a.length}/${n.maxInboundStreams}, closing new incoming stream`),d.writable.close().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)}),d.readable.cancel().catch(u=>{s.error(`failed to close inbound stream that crossed our maxInboundStream limit: ${u.message}`)});else{let u=await W3(d,String(o++),"inbound",a,i?.onStreamEnd,t);a.push(u),i?.onIncomingStream?.(u)}}}),{protocol:"webtransport",streams:a,newStream:async l=>{s("new outgoing stream",l);let d=await r.createBidirectionalStream(),u=await W3(d,String(o++),i?.direction??"outbound",a,i?.onStreamEnd,t);return a.push(u),u},close:async()=>{s("closing webtransport muxer gracefully"),r.close()},abort:l=>{s("closing webtransport muxer with err:",l),r.close()},...sf()}}}}function rb(r,e){return e.filter(n=>!!r.find(o=>Z(n,o))).length===e.length}var fN=Object.values(br).map(r=>r.decoder).reduce((r,e)=>r.or(e));function hN(r){return Er.decode(fN.decode(r))}function z3(r){if(!i1.matches(r))throw new g("Invalid multiaddr, was not a WebTransport address","ERR_INVALID_MULTIADDR");let e=r.stringTuples(),t=e.filter(([i,a])=>i===ee("certhash").code).map(([i,a])=>hN(a??"")),n=e.filter(([i,a])=>i===ee("p2p").code).map(([i,a])=>ge(a??""))[0],o=r.toOptions(),s=o.host;return o.family===6&&s?.includes(":")&&(s=`[${s}]`),{url:`https://${s}:${o.port}`,certhashes:t,remotePeer:n}}var nb=WebTransport;var Y3=class{log;components;config;metrics;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webtransport"),this.components=e,this.config={...t,maxInboundStreams:t.maxInboundStreams??1e3,certificates:t.certificates??[]},e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webtransport_dialer_events_total",{label:"event",help:"Total count of WebTransport dialer events by type"})})}[Symbol.toStringTag]="@libp2p/webtransport";[an]=!0;async dial(e,t){if(t?.signal?.aborted===!0)throw new Kt;this.log("dialing %s",e);let n=this.components.peerId;if(n===void 0)throw new g("Need a local peerid","ERR_INVALID_PARAMETERS");t=t??{};let{url:o,certhashes:s,remotePeer:i}=z3(e),a,c,l=()=>{},d=!1,u=!1,h=!1;try{this.metrics?.dialerEvents.increment({pending:!0});let f=new nb(`${o}/.well-known/libp2p-webtransport?type=noise`,{serverCertificateHashes:s.map(p=>({algorithm:"sha-256",value:p.digest}))});if(l=p=>{if(!d)try{this.metrics?.dialerEvents.increment({[p]:!0}),f.close()}catch(m){this.log.error("error closing wt session",m)}finally{c!=null&&(c.timeline.close=Date.now()),d=!0}},a=()=>{l(u?"noise_timeout":"ready_timeout")},t.signal?.addEventListener("abort",a,{once:!0}),this.log("wait for session to be ready"),await Promise.race([f.closed,f.ready]),this.log("session became ready"),u=!0,this.metrics?.dialerEvents.increment({ready:!0}),f.closed.catch(p=>{this.log.error("error on remote wt session close",p)}).finally(()=>{l("remote_close")}),h=await Ue(this.authenticateWebTransport(f,n,i,s),t.signal),!h)throw new g("Failed to authenticate webtransport","ERR_AUTHENTICATION_FAILED");return this.metrics?.dialerEvents.increment({open:!0}),c={close:async()=>{this.log("closing webtransport"),l("close")},abort:p=>{this.log("aborting webtransport due to passed err",p),l("abort")},remoteAddr:e,timeline:{open:Date.now()},log:this.components.logger.forComponent("libp2p:webtransport:maconn"),...sf()},await t.upgrader.upgradeOutbound(c,{skipEncryption:!0,muxerFactory:tb(f,f.incomingBidirectionalStreams.getReader(),this.components.logger,this.config),skipProtection:!0})}catch(f){throw this.log.error("caught wt session err",f),l(h?"upgrade_error":u?"noise_error":"ready_error"),f}finally{a!=null&&t.signal?.removeEventListener("abort",a)}}async authenticateWebTransport(e,t,n,o=[],s){if(s?.aborted===!0)throw new Kt;let i=await e.createBidirectionalStream(),a=i.writable.getWriter(),c=i.readable.getReader(),l={source:async function*(){for(;;){let h=await c.read();if(h.value!=null&&(yield h.value),h.done)break}}(),sink:async h=>{for await(let f of h){await Ue(a.ready,s);let p=f instanceof Uint8Array?f:f.subarray();a.write(p).catch(m=>{this.log.error("could not write chunk during authentication of WebTransport stream",m)})}}},d=Pi()(this.components),{remoteExtensions:u}=await d.secureOutbound(t,l,n);if(a.close().catch(h=>{this.log.error(`Failed to close authentication stream writer: ${h.message}`)}),c.cancel().catch(h=>{this.log.error(`Failed to close authentication stream reader: ${h.message}`)}),!rb(u?.webtransportCerthashes??[],o.map(h=>h.bytes)))throw new Error("Our certhashes are not a subset of the remote's reported certhashes");return!0}createListener(e){return q3(this.components,{...e,certificates:this.config.certificates,maxInboundStreams:this.config.maxInboundStreams})}listenFilter(){return[]}dialFilter(e){return e.filter(t=>{if(!i1.exactMatch(t))return!1;let{url:n,certhashes:o}=z3(t);return n!=null&&o.length>0})}};function ob(r={}){return e=>new Y3(e,r)}var X3=Qe(p1(),1);function sb(r,e){let t=e.map((n,o)=>({record:mn(n),index:o}));return t.sort((n,o)=>{let s=n.record.sequence,i=o.record.sequence;if(s>i)return-1;if(s<i)return 1;if(n.record.validityType===Xt.ValidityType.EOL&&o.record.validityType===Xt.ValidityType.EOL){let a=X3.default.fromString(n.record.validity).toDate(),c=X3.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var af="1.6.0",cf="libp2p";var ab="4.2.1-f46700f",cb="helia";var lb={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function lf(r={}){let e=`${cb}/${ab} ${cf}/${af} UserAgent=${globalThis.navigator.userAgent}`;return{peerId:r.peerId,dns:r.dns,addresses:{listen:["/webrtc"]},transports:[kp({discoverRelays:1}),ME(),BE(),ob(),eb()],connectionEncryption:[Pi()],streamMuxers:[j7(),Ky()],peerDiscovery:[h9(lb)],services:{autoNAT:t9(),dcutr:D9(),delegatedRouting:()=>e7("https://delegated-ipfs.dev"),dht:py({clientMode:!0,validators:{ipns:y1},selectors:{ipns:sb}}),identify:$9({agentVersion:e}),identifyPush:H9({agentVersion:e}),keychain:Nd(r.keychain),ping:Gy()}}}var It={ERR_INVALID_PARAMETERS:"ERR_INVALID_PARAMETERS"};var ca;(function(r){let e;(function(o){let s;o.codec=()=>(s==null&&(s=ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&i.value.byteLength>0&&(a.uint32(18),a.bytes(i.value)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:"",value:new Uint8Array(0)},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=i.bytes();break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>re(i,o.codec()),o.decode=i=>te(i,o.codec())})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(o){let s;o.codec=()=>(s==null&&(s=ne((i,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),i.key!=null&&i.key!==""&&(a.uint32(10),a.string(i.key)),i.value!=null&&(a.uint32(18),df.codec().encode(i.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(i,a)=>{let c={key:""},l=a==null?i.len:i.pos+a;for(;i.pos<l;){let d=i.uint32();switch(d>>>3){case 1:c.key=i.string();break;case 2:c.value=df.codec().decode(i,i.uint32());break;default:i.skipType(d&7);break}}return c})),s),o.encode=i=>re(i,o.codec()),o.decode=i=>te(i,o.codec())})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=ne((o,s,i={})=>{if(i.lengthDelimited!==!1&&s.fork(),o.addresses!=null)for(let a of o.addresses)s.uint32(10),uf.codec().encode(a,s);if(o.protocols!=null)for(let a of o.protocols)s.uint32(18),s.string(a);if(o.publicKey!=null&&(s.uint32(34),s.bytes(o.publicKey)),o.peerRecordEnvelope!=null&&(s.uint32(42),s.bytes(o.peerRecordEnvelope)),o.metadata!=null&&o.metadata.size!==0)for(let[a,c]of o.metadata.entries())s.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},s);if(o.tags!=null&&o.tags.size!==0)for(let[a,c]of o.tags.entries())s.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},s);i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={addresses:[],protocols:[],metadata:new Map,tags:new Map},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.addresses.push(uf.codec().decode(o,o.uint32()));break;case 2:i.protocols.push(o.string());break;case 4:i.publicKey=o.bytes();break;case 5:i.peerRecordEnvelope=o.bytes();break;case 6:{let l=r.Peer$metadataEntry.codec().decode(o,o.uint32());i.metadata.set(l.key,l.value);break}case 7:{let l=r.Peer$tagsEntry.codec().decode(o,o.uint32());i.tags.set(l.key,l.value);break}default:o.skipType(c&7);break}}return i})),n),r.encode=o=>re(o,r.codec()),r.decode=o=>te(o,r.codec())})(ca||(ca={}));var uf;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={multiaddr:new Uint8Array(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.multiaddr=t.bytes();break;case 2:o.isCertified=t.bool();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(uf||(uf={}));var df;(function(r){let e;r.codec=()=>(e==null&&(e=ne((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:o.value=t.uint32();break;case 2:o.expiry=t.uint64();break;default:t.skipType(i&7);break}}return o})),e),r.encode=t=>re(t,r.codec()),r.decode=t=>te(t,r.codec())})(df||(df={}));function la(r,e){let t=ca.decode(e);t.publicKey!=null&&r.publicKey==null&&(r=u8({...r,publicKey:r.publicKey}));let n=new Map,o=BigInt(Date.now());for(let[s,i]of t.tags.entries())i.expiry!=null&&i.expiry<o||n.set(s,i);return{...t,id:r,addresses:t.addresses.map(({multiaddr:s,isCertified:i})=>({multiaddr:j(s),isCertified:i??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}var Q3="/peers/";function ua(r){if(!Ms(r)||r.type==null)throw new g("Invalid PeerId",It.ERR_INVALID_PARAMETERS);let e=r.toCID().toString();return new Pe(`${Q3}${e}`)}async function ub(r,e,t){let n=new Map;for(let o of t){if(o==null)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=j(o.multiaddr)),!ko(o.multiaddr))throw new g("Multiaddr was invalid",It.ERR_INVALID_PARAMETERS);if(!await e(r,o.multiaddr))continue;let s=o.isCertified??!1,i=o.multiaddr.toString(),a=n.get(i);a!=null?o.isCertified=a.isCertified||s:n.set(i,{multiaddr:o.multiaddr,isCertified:s})}return[...n.values()].sort((o,s)=>o.multiaddr.toString().localeCompare(s.multiaddr.toString())).map(({isCertified:o,multiaddr:s})=>({isCertified:o,multiaddr:s.bytes}))}async function hf(r,e,t,n){if(e==null)throw new g("Invalid PeerData",It.ERR_INVALID_PARAMETERS);if(e.publicKey!=null&&r.publicKey!=null&&!Z(e.publicKey,r.publicKey))throw new g("publicKey bytes do not match peer id publicKey bytes",It.ERR_INVALID_PARAMETERS);let o=n.existingPeer;if(o!=null&&!r.equals(o.id))throw new g("peer id did not match existing peer id",It.ERR_INVALID_PARAMETERS);let s=o?.addresses??[],i=new Set(o?.protocols??[]),a=o?.metadata??new Map,c=o?.tags??new Map,l=o?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(s=[],e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses)),e.protocols!=null&&(i=new Set(e.protocols)),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=ff(u,{validate:db})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=ff(u,{validate:fb,map:hb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&s.push(...e.multiaddrs.map(u=>({isCertified:!1,multiaddr:u}))),e.addresses!=null&&s.push(...e.addresses),e.protocols!=null&&(i=new Set([...i,...e.protocols])),e.metadata!=null){let u=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,f]of u)f==null?a.delete(h):a.set(h,f);a=ff([...a.entries()],{validate:db})}if(e.tags!=null){let u=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[f,p]of u)p==null?h.delete(f):h.set(f,p);c=ff([...h.entries()],{validate:fb,map:hb})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let d={addresses:await ub(r,n.addressFilter??(async()=>!0),s),protocols:[...i.values()].sort((u,h)=>u.localeCompare(h)),metadata:a,tags:c,publicKey:o?.id.publicKey??e.publicKey??r.publicKey,peerRecordEnvelope:l};return r.type!=="RSA"&&delete d.publicKey,d}function ff(r,e){let t=new Map;for(let[n,o]of r)o!=null&&e.validate(n,o);for(let[n,o]of r.sort(([s],[i])=>s.localeCompare(i)))o!=null&&t.set(n,e.map?.(n,o)??o);return t}function db(r,e){if(typeof r!="string")throw new g("Metadata key must be a string",It.ERR_INVALID_PARAMETERS);if(!(e instanceof Uint8Array))throw new g("Metadata value must be a Uint8Array",It.ERR_INVALID_PARAMETERS)}function fb(r,e){if(typeof r!="string")throw new g("Tag name must be a string",It.ERR_INVALID_PARAMETERS);if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new g("Tag value must be an integer",It.ERR_INVALID_PARAMETERS);if(e.value<0||e.value>100)throw new g("Tag value must be between 0-100",It.ERR_INVALID_PARAMETERS)}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new g("Tag ttl must be an integer",It.ERR_INVALID_PARAMETERS);if(e.ttl<0)throw new g("Tag ttl must be between greater than 0",It.ERR_INVALID_PARAMETERS)}}function hb(r,e){let t;return e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl))),{value:e.value??0,expiry:t}}function pf(r,e,t){let n=r.toString().split("/")[2],o=ut.decode(n),s=Je(o),i=t.get(s);if(i!=null)return i;let a=la(s,e);return t.set(s,a),a}function pN(r,e){return r==null?{}:{prefix:Q3,filters:(r.filters??[]).map(t=>({key:n,value:o})=>t(pf(n,o,e))),orders:(r.orders??[]).map(t=>(n,o)=>t(pf(n.key,n.value,e),pf(o.key,o.value,e)))}}var mf=class{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=Ya({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(ua(e))}async delete(e){if(this.peerId.equals(e))throw new g("Cannot delete self peer",It.ERR_INVALID_PARAMETERS);await this.datastore.delete(ua(e))}async load(e){let t=await this.datastore.get(ua(e));return la(e,t)}async save(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"patch",{addressFilter:this.addressFilter});return this.#t(e,s,n,o)}async patch(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async merge(e,t){let{existingBuf:n,existingPeer:o}=await this.#e(e),s=await hf(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:o});return this.#t(e,s,n,o)}async*all(e){let t=new it;for await(let{key:n,value:o}of this.datastore.query(pN(e??{},t))){let s=pf(n,o,t);s.id.equals(this.peerId)||(yield s)}}async#e(e){try{let t=await this.datastore.get(ua(e)),n=la(e,t);return{existingBuf:t,existingPeer:n}}catch(t){if(t.code!=="ERR_NOT_FOUND")throw t}return{}}async#t(e,t,n,o){let s=ca.encode(t);return n!=null&&Z(s,n)?{peer:la(e,s),previous:o,updated:!1}:(await this.datastore.put(ua(e),s),{peer:la(e,s),previous:o,updated:!0})}};var gf=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new mf(e,t)}async forEach(e,t){this.log.trace("forEach await read lock");let n=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(let o of this.store.all(t))e(o)}finally{this.log.trace("forEach release read lock"),n()}}async all(e){this.log.trace("all await read lock");let t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await sc(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");let t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");let t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");let t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");let n=await this.store.lock.writeLock();this.log.trace("save got write lock");try{let o=await this.store.save(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("save release write lock"),n()}}async patch(e,t){this.log.trace("patch await write lock");let n=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{let o=await this.store.patch(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("patch release write lock"),n()}}async merge(e,t){this.log.trace("merge await write lock");let n=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{let o=await this.store.merge(e,t);return this.#e(e,o),o.peer}finally{this.log.trace("merge release write lock"),n()}}async consumePeerRecord(e,t){let n=await mr.openAndCertify(e,Vt.DOMAIN);if(t?.equals(n.peerId)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n.peerId),!1;let o=Vt.createFromProtobuf(n.payload),s;try{s=await this.get(n.peerId)}catch(i){if(i.code!=="ERR_NOT_FOUND")throw i}if(s?.peerRecordEnvelope!=null){let i=await mr.createFromProtobuf(s.peerRecordEnvelope),a=Vt.createFromProtobuf(i.payload);if(a.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",a.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map(i=>({isCertified:!0,multiaddr:i}))}),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function pb(r,e){let t;return function(){let n=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(n,e)}}var mN=r=>r;function j3(r,e){let t=r.getPeerId();return t!=null&&ge(t).equals(e)&&(r=r.decapsulate(j(`/p2p/${e.toString()}`))),r}var yf=class{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){let{listen:n=[],announce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(o.map(s=>s.toString())),this.observed=new Map,this.announceFilter=t.announceFilter??mN,this._updatePeerStoreAddresses=pb(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}_updatePeerStoreAddresses(){let e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter(([t,n])=>n.confident).map(([t])=>j(t))).map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>j(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>j(e))}getObservedAddrs(){return Array.from(this.observed).map(([e])=>j(e))}addObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString(),o=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),o||this._updatePeerStoreAddresses()}removeObservedAddr(e){e=j3(e,this.components.peerId);let t=e.toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map(n=>n.toString());e.length===0&&(e=this.components.transportManager.getAddrs().map(n=>n.toString())),e=e.concat(Array.from(this.observed).filter(([n,o])=>o.confident).map(([n])=>n));let t=new Set(e);return this.announceFilter(Array.from(t).map(n=>j(n))).map(n=>n.protos().pop()?.path===!0||n.getPeerId()===this.components.peerId.toString()?n:n.encapsulate(`/p2p/${this.components.peerId.toString()}`))}};var Z3=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=So())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>Fc(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},gN=["metrics","connectionProtector","dns"],yN=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function mb(r={}){let e=new Z3(r);return new Proxy(e,{get(n,o,s){if(typeof o=="string"&&!yN.includes(o)){let i=e.components[o];if(i==null&&!gN.includes(o))throw new g(`${o} not set`,"ERR_SERVICE_MISSING");return i}return Reflect.get(n,o,s)},set(n,o,s){return typeof o=="string"?e.components[o]=s:Reflect.set(n,o,s),!0}})}function gb(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{let t=e.stringTuples();return t[0][0]===4||t[0][0]===41?!!Yt(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}function J3(r){try{let{address:e}=r.nodeAddress();return!!Yt(e)}catch{return!0}}function wN(r,e){let t=J3(r.multiaddr),n=J3(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function EN(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function bN(r,e){let t=bs.exactMatch(r.multiaddr),n=bs.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function da(r,e){let t=wN(r,e);if(t!==0)return t;let n=bN(r,e);return n!==0?n:EN(r,e)}var xN=32,{code:vN}=ee("dnsaddr"),Ps=async function(e,t={}){let n=t.maxRecursiveDepth??xN;if(n===0)throw new g("Max recursive depth reached","ERR_MAX_RECURSIVE_DEPTH_REACHED");let[,o]=e.stringTuples().find(([l])=>l===vN)??[],i=await(t?.dns??wu()).query(`_dnsaddr.${o}`,{signal:t?.signal,types:[ar.TXT]}),a=e.getPeerId(),c=[];for(let l of i.Answer){let d=l.data.replace(/["']/g,"").trim().split("=")[1];if(d==null||a!=null&&!d.includes(a))continue;let u=j(d);if(d.startsWith("/dnsaddr")){let h=await u.resolve({...t,maxRecursiveDepth:n-1});c.push(...h.map(f=>f.toString()))}else c.push(u.toString())}return c};var Jn;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",r.NOT_FOUND="Not found"})(Jn||(Jn={}));var z;(function(r){r.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",r.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",r.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",r.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",r.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",r.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",r.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",r.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",r.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",r.ERR_DIALED_SELF="ERR_DIALED_SELF",r.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",r.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",r.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",r.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",r.ERR_INVALID_KEY="ERR_INVALID_KEY",r.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_INVALID_PEER="ERR_INVALID_PEER",r.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",r.ERR_NOT_FOUND="ERR_NOT_FOUND",r.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",r.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",r.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",r.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",r.ERR_FIND_SELF="ERR_FIND_SELF",r.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",r.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",r.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",r.ERR_INVALID_CMS="ERR_INVALID_CMS",r.ERR_MISSING_KEYS="ERR_MISSING_KEYS",r.ERR_NO_KEY="ERR_NO_KEY",r.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",r.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",r.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",r.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",r.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",r.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",r.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",r.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",r.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",r.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",r.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",r.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",r.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",r.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",r.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",r.ERR_INVALID_RECORD="ERR_INVALID_RECORD",r.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",r.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",r.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"})(z||(z={}));var RN={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Ps},addressSorter:da},transportManager:{faultTolerance:to.FATAL_ALL}};async function yb(r){let e=Xi(RN,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new g(Jn.ERR_PROTECTOR_REQUIRED,z.ERR_PROTECTOR_REQUIRED);if(!(await dt(e.privateKey.public.bytes,e.privateKey.bytes)).equals(e.peerId))throw new g("Private key doesn't match peer id",z.ERR_INVALID_KEY);return e}function wf(r){if(Ms(r))return{peerId:r,multiaddrs:[]};Array.isArray(r)||(r=[r]);let e;if(r.length>0){let t=r[0].getPeerId();e=t==null?void 0:ge(t),r.forEach(n=>{if(!ko(n))throw new g("Invalid Multiaddr",z.ERR_INVALID_MULTIADDR);let o=n.getPeerId();if(o==null){if(e!=null)throw new g("Multiaddrs must all have the same peer id or have no peer id",z.ERR_INVALID_PARAMETERS)}else{let s=ge(o);if(e==null||!e.equals(s))throw new g("Multiaddrs must all have the same peer id or have no peer id",z.ERR_INVALID_PARAMETERS)}})}return{peerId:e,multiaddrs:r}}var Ef="last-dial-failure";var bf=5,xf=100,vf=50,Rf=1e3*60*7;var Os={minConnections:bf,maxQueueLength:100,autoDialConcurrency:25,autoDialPriority:0,autoDialInterval:5e3,autoDialPeerRetryThreshold:Rf,autoDialDiscoveredPeersDebounce:10},Sf=class{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??Os.minConnections,this.autoDialPriority=t.autoDialPriority??Os.autoDialPriority,this.autoDialIntervalMs=t.autoDialInterval??Os.autoDialInterval,this.autoDialMaxQueueLength=t.maxQueueLength??Os.maxQueueLength,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??Os.autoDialPeerRetryThreshold,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??Os.autoDialDiscoveredPeersDebounce,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new wr({concurrency:t.autoDialConcurrency??Os.autoDialConcurrency,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",o=>{this.log.error("error during auto-dial",o.detail)}),e.events.addEventListener("connection:close",()=>{this.autoDial().catch(o=>{this.log.error(o)})});let n;e.events.addEventListener("peer:discovery",()=>{clearTimeout(n),n=setTimeout(()=>{this.autoDial().catch(o=>{this.log.error(o)})},this.autoDialDiscoveredPeersDebounce)})}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;let e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections){this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections);return}if(this.queue.size>this.autoDialMaxQueueLength){this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),this.sheduleNextAutodial();return}this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);let n=new ht(this.connectionManager.getDialQueue().map(l=>l.peerId).filter(Boolean)),o=await this.peerStore.all({filters:[l=>l.addresses.length===0?(this.log.trace("not autodialing %p because they have no addresses",l.id),!1):e.has(l.id)?(this.log.trace("not autodialing %p because they are already connected",l.id),!1):n.has(l.id)?(this.log.trace("not autodialing %p because they are already being dialed",l.id),!1):this.queue.has(l.id)?(this.log.trace("not autodialing %p because they are already being autodialed",l.id),!1):!0]}),s=o.sort(()=>Math.random()>.5?1:-1),i=new it;for(let l of s)i.has(l.id)||i.set(l.id,[...l.tags.values()].reduce((d,u)=>d+u.value,0));let c=s.sort((l,d)=>{let u=i.get(l.id)??0,h=i.get(d.id)??0;return u>h?-1:u<h?1:0}).filter(l=>{let d=l.metadata.get(Ef);if(d==null)return!0;let u=parseInt(O(d));return isNaN(u)?!0:Date.now()-u>this.autoDialPeerRetryThresholdMs});this.log("selected %d/%d peers to dial",c.length,o.length);for(let l of c)this.queue.add(async()=>{let d=this.connectionManager.getConnectionsMap().size;if(d>=this.minConnections){this.log("got enough connections now %d/%d",d,this.minConnections),this.queue.clear();return}this.log("connecting to a peerStore stored peer %p",l.id),await this.connectionManager.openConnection(l.id,{priority:this.autoDialPriority})},{peerId:l.id}).catch(d=>{this.log.error("could not connect to peerStore stored peer",d)});this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout(()=>{this.autoDial().catch(e=>{this.log.error("error while autodialing",e)})},this.autoDialIntervalMs))}};var _N=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function wb(r,e){let t=r?.streams?.map(o=>o.protocol)??[],n=e?.closableProtocols??_N;if(!(t.filter(o=>o!=null&&!n.includes(o)).length>0))try{await r?.close(e)}catch(o){r?.abort(o)}}var Eb={maxConnections:xf,allow:[]},_f=class{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Eb.maxConnections,this.allow=t.allow??Eb.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",()=>{this.maybePruneConnections().catch(n=>{this.log.error(n)})})}async maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;let n=new it;for(let a of e){let c=a.remotePeer;if(!n.has(c)){n.set(c,0);try{let l=await this.peerStore.get(c);n.set(c,[...l.tags.values()].reduce((d,u)=>d+u.value,0))}catch(l){l.code!=="ERR_NOT_FOUND"&&this.log.error("error loading peer tags",l)}}}let o=this.sortConnections(e,n),s=Math.max(t-this.maxConnections,0),i=[];for(let a of o)if(this.log("too many connections open - closing a connection to %p",a.remotePeer),this.allow.some(l=>a.remoteAddr.toString().startsWith(l.toString()))||i.push(a),i.length===s)break;await Promise.all(i.map(async a=>{await wb(a,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:i})}sortConnections(e,t){return e.sort((n,o)=>{let s=n.timeline.open,i=o.timeline.open;return s<i?1:s>i?-1:0}).sort((n,o)=>n.direction==="outbound"&&o.direction==="inbound"?1:n.direction==="inbound"&&o.direction==="outbound"?-1:0).sort((n,o)=>n.streams.length>o.streams.length?1:n.streams.length<o.streams.length?-1:0).sort((n,o)=>{let s=t.get(n.remotePeer)??0,i=t.get(o.remotePeer)??0;return s>i?1:s<i?-1:0})}};var Af=class extends tr{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};async function bb(r,e){let t=!1;for(let o of Di.keys())if(t=r.protoNames().includes(o),t)break;if(!t)return[r];let n=await r.resolve(e);return e.log("resolved %s to",r,n.map(o=>o.toString())),n}var Lc={addressSorter:da,maxParallelDials:vf,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:5e3,resolvers:{dnsaddr:Ps}},If=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter??Lc.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Lc.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Lc.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Lc.dialTimeout,this.connections=t.connections??new it,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal);for(let[n,o]of Object.entries(t.resolvers??{}))Di.set(n,o);this.queue=new Af({concurrency:t.maxParallelDials??Lc.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",n=>{this.log.error("error in dial queue",n.detail)})}start(){this.shutDownController=new AbortController,H(1/0,this.shutDownController.signal)}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:o}=wf(e),s=Array.from(this.connections.values()).flat().find(a=>t.force===!0?!1:a.remotePeer.equals(n)?!0:o.find(c=>c.equals(a.remoteAddr)));if(s!=null)return this.log("already connected to %a",s.remoteAddr),s;let i=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of o)if(c.has(l.toString()))return!0;return!1});if(i!=null){this.log("joining existing dial target for %p",n);for(let a of o)i.options.multiaddrs.add(a.toString());return i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new g("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",n,o.map(a=>a.toString())),this.queue.add(async a=>{let c=this.createDialAbortController(a?.signal),l;try{l=await this.calculateMultiaddrs(n,a?.multiaddrs,{...a,signal:c}),l.map(({multiaddr:d})=>d.toString()).forEach(d=>{a?.multiaddrs.add(d)})}catch(d){throw c.clear(),d}try{let d=0,u=[];for(let h of l){if(d===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",d,n),new g("Peer had more than maxPeerAddrsToDial",z.ERR_TOO_MANY_ADDRESSES);d++;try{let f=await this.components.transportManager.dial(h.multiaddr,{...a,signal:c});return this.log("dial to %a succeeded",h.multiaddr),f}catch(f){if(this.log.error("dial failed to %a",h.multiaddr,f),n!=null)try{await this.components.peerStore.patch(n,{metadata:{[Ef]:M(Date.now().toString())}})}catch(p){this.log.error("could not update last dial failure key for %p",n,p)}if(c.aborted)throw new g(f.message,vn);u.push(f)}}throw u.length===1?u[0]:new Uc(u,"All multiaddr dials failed",z.ERR_TRANSPORT_DIAL_FAILED)}finally{c.clear()}},{peerId:n,priority:t.priority??a4,multiaddrs:new Set(o.map(a=>a.toString())),signal:t.signal})}createDialAbortController(e){let t=Ae([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e]);return H(1/0,t),t}async calculateMultiaddrs(e,t=new Set,n={}){let o=[...t].map(u=>({multiaddr:j(u),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new g("Tried to dial self",z.ERR_DIALED_SELF);if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new g("The dial request is blocked by gater.allowDialPeer",z.ERR_PEER_DIAL_INTERCEPTED);if(o.length===0){this.log("loading multiaddrs for %p",e);try{let u=await this.components.peerStore.get(e);o.push(...u.addresses),this.log("loaded multiaddrs for %p",e,o.map(({multiaddr:h})=>h.toString()))}catch(u){if(u.code!==z.ERR_NOT_FOUND)throw u}}if(o.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let u=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,o.map(({multiaddr:h})=>h.toString())),o.push(...u.multiaddrs.map(h=>({multiaddr:h,isCertified:!1})))}catch(u){u.code!==z.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,u)}}}let s=(await Promise.all(o.map(async u=>{let h=await bb(u.multiaddr,{dns:this.components.dns,...n,log:this.log});return h.length===1&&h[0].equals(u.multiaddr)?u:h.map(f=>({multiaddr:f,isCertified:!1}))}))).flat();if(e!=null){let u=`/p2p/${e.toString()}`;s=s.map(h=>h.multiaddr.protos().pop()?.path===!0?h:h.multiaddr.getPeerId()==null?{multiaddr:h.multiaddr.encapsulate(u),isCertified:h.isCertified}:h)}let i=s.filter(u=>{if(this.components.transportManager.dialTransportForMultiaddr(u.multiaddr)==null)return!1;let h=u.multiaddr.getPeerId();return e!=null&&h!=null?e.equals(h):!0}),a=new Map;for(let u of i){let h=u.multiaddr.toString(),f=a.get(h);if(f!=null){f.isCertified=f.isCertified||u.isCertified||!1;continue}a.set(h,u)}let c=[...a.values()];if(c.length===0)throw new g("The dial request has no valid addresses",z.ERR_NO_VALID_ADDRESSES);let l=[];for(let u of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(u.multiaddr)||l.push(u);let d=l.sort(this.addressSorter);if(d.length===0)throw new g("The connection gater denied all addresses in the dial request",z.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:u})=>u.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",d.map(({multiaddr:u})=>u.toString())),d}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(o=>o.toString())),t);return t.runOnTransientConnection===!1?n.find(o=>!bs.matches(o.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var a4=50,eo={minConnections:bf,maxConnections:xf,inboundConnectionThreshold:5,maxIncomingPendingConnections:10,autoDialConcurrency:25,autoDialPriority:0,autoDialMaxQueueLength:100,autoDialPeerRetryThreshold:Rf,autoDialDiscoveredPeersDebounce:10},Df=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??eo.maxConnections;let n=t.minConnections??eo.minConnections;if(this.maxConnections<n)throw new g("Connection Manager maxConnections must be greater than minConnections",z.ERR_INVALID_PARAMETERS);this.connections=new it,this.started=!1,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),this.allow=(t.allow??[]).map(o=>j(o)),this.deny=(t.deny??[]).map(o=>j(o)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??eo.maxIncomingPendingConnections,this.inboundConnectionRateLimiter=new Qi({points:t.inboundConnectionThreshold??eo.inboundConnectionThreshold,duration:1}),this.autoDial=new Sf({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:n,autoDialConcurrency:t.autoDialConcurrency??eo.autoDialConcurrency,autoDialPriority:t.autoDialPriority??eo.autoDialPriority,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??eo.autoDialPeerRetryThreshold,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??eo.autoDialDiscoveredPeersDebounce,maxQueueLength:t.autoDialMaxQueueLength??eo.autoDialMaxQueueLength}),this.connectionPruner=new _f({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new If(e,{addressSorter:t.addressSorter??da,maxParallelDials:t.maxParallelDials??vf,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Ps},connections:this.connections})}isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,outbound:0};for(let t of this.connections.values())for(let n of t)n.direction==="inbound"?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let o of n.streams){let s=`${o.direction} ${o.protocol??"unnegotiated"}`;e[s]=(e[s]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let o of n){let s={};for(let i of o.streams){let a=`${i.direction} ${i.protocol??"unnegotiated"}`;s[a]=(s[a]??0)+1}for(let[i,a]of Object.entries(s))e[i]=e[i]??[],e[i].push(a)}let t={};for(let[n,o]of Object.entries(e)){o=o.sort((i,a)=>i-a);let s=Math.floor(o.length*.9);t[n]=o[s]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(R4)]});await Promise.all(e.map(async t=>{await this.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)}),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(o){this.log.error(o)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}let n=t.remotePeer,o=this.connections.get(n),s=!1;o!=null?o.push(t):(s=!0,this.connections.set(n,[t])),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e;if(!this.started)return;let n=t.remotePeer,o=this.connections.get(n);o!=null&&o.length>1?(o=o.filter(s=>s.id!==t.id),this.connections.set(n,o)):o!=null&&(this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new g("Not started",z.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();let{peerId:n}=wf(e);if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>!c.transient);if(a!=null)return this.log("had an existing non-transient connection to %p",n),a}let o=await this.dialQueue.dial(e,{...t,priority:t.priority??a4}),s=this.connections.get(o.remotePeer);s==null&&(s=[],this.connections.set(o.remotePeer,s));let i=!1;for(let a of s)a.id===o.id&&(i=!0);return i||s.push(o),o}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async o=>{try{await o.close(t)}catch(s){o.abort(s)}}))}async acceptIncomingConnection(e){if(this.deny.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(o=>e.remoteAddr.toString().startsWith(o.toString())))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let o=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(o,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,o),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>j(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var Tf=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new g("No content routers available",z.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ht;for await(let s of Mt(...n.routers.map(i=>i.findProviders(e,t))))s!=null&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}async provide(e,t={}){if(this.routers.length===0)throw new g("No content routers available",z.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map(async n=>{await n.provide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new g(Jn.NOT_STARTED_YET,z.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map(async o=>{await o.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new g(Jn.NOT_STARTED_YET,z.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map(async n=>n.get(e,t)))}};var kf=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}async findPeer(e,t){if(this.routers.length===0)throw new g("No peer routers available",z.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new g("Should not try to find self",z.ERR_FIND_SELF);let n=this,o=Mt(...this.routers.map(s=>async function*(){try{yield await s.findPeer(e,t)}catch(i){n.log.error(i)}}()));for await(let s of o)if(s!=null)return s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),s;throw new g(Jn.NOT_FOUND,z.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new g("No peer routers available",z.ERR_NO_ROUTERS_AVAILABLE);let n=this,o=new ht;for await(let s of en(async function*(){let i=Mt(...n.routers.map(a=>a.getClosestPeers(e,t)));for await(let a of i)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}}()))s!=null&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),!o.has(s.id)&&(o.add(s.id),yield s))}};var Cf=class extends ye{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,H(1/0,this.shutdownController.signal)}start(){this.shutdownController=new AbortController,H(1/0,this.shutdownController.signal)}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Ae([this.shutdownController.signal,e?.signal]);H(1/0,t);try{for(;;)this.needNext?.resolve(),this.needNext=J(),yield(await er(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,H(1/0,this.walkController.signal);let e=Ae([this.walkController.signal,this.shutdownController.signal]);H(1/0,e);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{for await(let o of this.peerRouting.getClosestPeers(pt(32),{signal:e}))e.throwIfAborted(),this.log("found peer %p",o.id),n++,this.safeDispatchEvent("walk:peer",{detail:o}),this.walkers===1&&this.needNext!=null&&await Ue(this.needNext.promise,e)}catch(o){this.log.error("randomwalk errored",o),this.safeDispatchEvent("walk:error",{detail:o})}}).catch(o=>{this.log.error("randomwalk errored",o)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var c4=32,l4=64,Nf=class{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new g(`No handler registered for protocol ${e}`,z.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e))throw new g(`Handler already registered for protocol ${e}`,z.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);let o=Xi.bind({ignoreUndefined:!0})({maxInboundStreams:c4,maxOutboundStreams:l4},n);this.handlers.set(e,{handler:t,options:o}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach(n=>{this.handlers.delete(n)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(t==null)throw new g("invalid topology",z.ERR_INVALID_PARAMETERS);let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,o=this.topologies.get(e);return o==null&&(o=new Map,this.topologies.set(e,o)),o.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail;this.components.peerStore.get(t).then(n=>{for(let o of n.protocols){let s=this.topologies.get(o);if(s!=null)for(let i of s.values())i.filter?.has(t)!==!1&&(i.filter?.remove(t),i.onDisconnect?.(t))}}).catch(n=>{n.code!==z.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,n)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,o=(n?.protocols??[]).filter(s=>!t.protocols.includes(s));for(let s of o){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,o=e.detail.peerId;for(let s of t){let i=this.topologies.get(s);if(i!=null)for(let a of i.values())n.transient&&a.notifyOnTransient!==!0||a.filter?.has(o)!==!0&&(a.filter?.add(o),a.onConnect?.(o,n))}}};var Lf=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=Wu({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??to.FATAL_ALL}add(e){let t=e[Symbol.toStringTag];if(t==null)throw new g("Transport must have a valid tag",z.ERR_INVALID_KEY);if(this.transports.has(t))throw new g(`There is already a transport with the tag ${t}`,z.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let o=n.pop();o!=null&&e.push(o.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new g(`No transport available for address ${String(e)}`,z.ERR_TRANSPORT_UNAVAILABLE);try{return await n.dial(e,{...t,upgrader:this.components.upgrader})}catch(o){throw o.code==null&&(o.code=z.ERR_TRANSPORT_DIAL_FAILED),o}}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new g("Not started",z.ERR_NODE_NOT_STARTED);if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t=[];for(let[n,o]of this.transports.entries()){let s=o.listenFilter(e),i=[];for(let l of s){this.log("creating listener for %s on %a",n,l);let d=o.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(n)??[];u==null&&(u=[],this.listeners.set(n,u)),u.push(d),d.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:d})}),d.addEventListener("close",()=>{let h=u.findIndex(f=>f===d);u.splice(h,1),this.components.events.safeDispatchEvent("transport:close",{detail:d})}),i.push(d.listen(l))}if(i.length===0){t.push(n);continue}if((await Promise.allSettled(i)).find(l=>l.status==="fulfilled")==null&&this.faultTolerance!==to.NO_FATAL)throw new g(`Transport (${n}) could not listen on any available address`,z.ERR_NO_VALID_ADDRESSES)}if(t.length===this.transports.size){let n=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===to.FATAL_ALL)throw new g(n,z.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${n}`)}}async remove(e){let t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);let n=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){let o=t.pop();o!=null&&n.push(o.close())}await Promise.all(n),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){let e=[];for(let t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}};var Dt="/multistream/1.0.0";var DN=M(`
|
|
53
53
|
`);async function Bs(r,e,t){await r.write(e,t)}async function xb(r,e,t){await r.writeV(e,t)}async function TN(r,e){let t=await r.read(e);if(t.byteLength===0||t.get(t.byteLength-1)!==DN[0])throw e.log.error("Invalid mss message - missing newline",t),new g("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return t.sublist(0,-1)}async function qo(r,e){let t=await TN(r,e);return O(t.subarray())}async function Pc(r,e,t){if(e=Array.isArray(e)?[...e]:[e],e.length===1&&t.negotiateFully===!1)return kN(r,e[0],t);let n=gn(r,{...t,maxDataLength:1024}),o=e.shift();if(o==null)throw new Error("At least one protocol must be specified");t.log.trace('select: write ["%s", "%s"]',Dt,o);let s=M(`${Dt}
|
|
54
54
|
`),i=M(`${o}
|
|
55
55
|
`);await xb(n,[s,i],t),t.log.trace("select: reading multistream-select header");let a=await qo(n,t);if(t.log.trace('select: read "%s"',a),a===Dt&&(t.log.trace("select: reading protocol response"),a=await qo(n,t),t.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(let c of e){t.log.trace('select: write "%s"',c),await Bs(n,M(`${c}
|
|
@@ -62,7 +62,7 @@ a=ice-pwd:`+e+`
|
|
|
62
62
|
`),t),t.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:n.unwrap(),protocol:o};if(o==="ls"){let s=new ce(...e.map(i=>Ht.single(M(`${i}
|
|
63
63
|
`))),M(`
|
|
64
64
|
`));t.log.trace('handle: respond with "%s" for %s',e,o),await Bs(n,s,t),t.log.trace('handle: responded with "%s" for %s',e,o);continue}t.log('handle: respond with "na" for "%s"',o),await Bs(n,M(`na
|
|
65
|
-
`),t),t.log('handle: responded with "na" for "%s"',o)}}var NN=500,d4=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[v4]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new g("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new g("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new g("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(NN);H(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function Rb(r){return new d4(r)}var LN=3e4;function PN(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==z.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return c4}function ON(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==z.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??l4}function Sb(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Pf=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}async shouldBlockConnection(e,t,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new g(`The multiaddr connection is blocked by gater.${n}`,z.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new g("connection denied",z.ERR_CONNECTION_DENIED);let o,s,i,a,c,l=AbortSignal.timeout(this.inboundUpgradeTimeout),d=()=>{e.abort(new g("inbound upgrade timeout",vn))};l.addEventListener("abort",d,{once:!0}),H(1/0,l);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new g("The multiaddr connection is blocked by gater.acceptConnection",z.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let u=e;if(t?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(e.log("protecting the inbound connection"),u=await h.protect(e))}try{if(o=u,t?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(u));let h={...u,...o};await this.shouldBlockConnection(s,h,"denyInboundEncryptedConnection")}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new g("inbound connection that skipped encryption must have a peer id",z.ERR_INVALID_MULTIADDR);let f=ge(h);c="native",s=f}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...u,...o},this.muxers);a=h.muxerFactory,i=h.stream}}catch(h){throw e.log.error("failed to upgrade inbound connection",h),h}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,transient:t?.transient})}finally{l.removeEventListener("abort",d),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=ge(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,l;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let d=e;if(t?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(d=await u.protect(e))}try{if(s=d,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(d,o));let u={...d,...s};await this.shouldBlockConnection(i,u,"denyOutboundEncryptedConnection")}else{if(o==null)throw new g("Encryption was skipped but no peer id was passed",z.ERR_INVALID_PEER);c="native",i=o}if(a=s,t?.muxerFactory!=null)l=t.muxerFactory;else if(this.muxers.size>0){let u=await this._multiplexOutbound({...d,...s},this.muxers);l=u.muxerFactory,a=u.stream}}catch(u){throw e.log.error("failed to upgrade outbound connection",u),await e.close(u),u}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:l,remotePeer:i,transient:t?.transient})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,transient:c}=e,l,d,u;a!=null&&(l=a.createStreamMuxer({direction:n,onIncomingStream:p=>{u!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:y,protocol:w}=await Oc(p,m,{log:p.log,yieldBytes:!1});if(u==null)return;u.log("incoming stream opened on %s",w);let b=PN(w,this.components.registrar);if(Sb(w,"inbound",u)===b){let x=new g(`Too many inbound protocol streams for protocol "${w}" - limit ${b}`,z.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw p.abort(x),x}p.source=y.source,p.sink=y.sink,p.protocol=w,y.closeWrite!=null&&(p.closeWrite=y.closeWrite),y.closeRead!=null&&(p.closeRead=y.closeRead),y.close!=null&&(p.close=y.close),await this.components.peerStore.merge(i,{protocols:[w]}),this.components.metrics?.trackProtocolStream(p,u),this._onStream({connection:u,stream:p,protocol:w})}).catch(async m=>{u.log.error("error handling incoming stream id %s",p.id,m.message,m.code,m.stack),p.timeline.close==null&&await p.close()})}}),d=async(p,m={})=>{if(l==null)throw new g("Stream is not multiplexed",z.ERR_MUXER_UNAVAILABLE);u.log("starting new stream for protocols %s",p);let y=await l.newStream();u.log.trace("started new stream %s for protocols %s",y.id,p);try{if(m.signal==null){y.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let v=AbortSignal.timeout(LN);H(1/0,v),m={...m,signal:v}}y.log.trace("selecting protocol from protocols %s",p);let{stream:w,protocol:b}=await Pc(y,p,{...m,log:y.log,yieldBytes:!0});y.log("selected protocol %s",b);let E=ON(b,this.components.registrar,m),x=Sb(b,"outbound",u);if(x>=E){let v=new g(`Too many outbound protocol streams for protocol "${b}" - ${x}/${E}`,z.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw y.abort(v),v}return await this.components.peerStore.merge(i,{protocols:[b]}),y.source=w.source,y.sink=w.sink,y.protocol=b,w.closeWrite!=null&&(y.closeWrite=w.closeWrite),w.closeRead!=null&&(y.closeRead=w.closeRead),w.close!=null&&(y.close=w.close),this.components.metrics?.trackProtocolStream(y,u),y}catch(w){throw u.log.error("could not create new stream for protocols %s",p,w),y.timeline.close==null&&y.abort(w),w.code!=null?w:new g(String(w),z.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([l.sink(s.source),s.sink(l.source)]).catch(p=>{u.log.error("error piping data through muxer",p)}));let h=o.timeline;o.timeline=new Proxy(h,{set:(...p)=>(u!=null&&p[1]==="close"&&p[2]!=null&&h.close==null&&(async()=>{try{u.status==="open"&&await u.close()}catch(m){u.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch(m=>{u.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let f=()=>{throw new g("connection is not multiplexed",z.ERR_CONNECTION_NOT_MULTIPLEXED)};return u=Rb({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:l?.protocol,encryption:t,transient:c,logger:this.components.logger,newStream:d??f,getStreams:()=>l!=null?l.streams:[],close:async p=>{l!=null&&(u.log.trace("close muxer"),await l.close(p)),u.log.trace("close maconn"),await o.close(p),u.log.trace("closed maconn")},abort:p=>{o.abort(p),l?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:u}),u}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.transient&&i.runOnTransientConnection!==!0)throw new g("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:o}=await Oc(e,t,{log:e.log}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using",o),{...await s.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection to %p failed",n),new g(n.message,z.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await Pc(e,n,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,i),{...await i.secureOutbound(this.components.peerId,o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",o),new g(o.message,z.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await Pc(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new g(String(o),z.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await Oc(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new g(String(o),z.ERR_MUXER_UNAVAILABLE)}}};var f4=class extends ye{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new ye,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),l=this.dispatchEvent(new Ot(a.type,{detail:a.detail}));return c||l},H(1/0,t),this.peerId=e.peerId,this.logger=e.logger??So(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=mb({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:cf,version:af},logger:this.logger,events:t,datastore:e.datastore??new vs,connectionGater:gb(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new gf(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(l=>l.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new Pf(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Lf(this.components,e.transportManager)),this.configureComponent("connectionManager",new Df(this.components,e.connectionManager)),this.configureComponent("registrar",new Nf(this.components)),this.configureComponent("addressManager",new yf(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new kf(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Tf(this.components,{routers:i})),this.configureComponent("randomWalk",new Cf(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],l=c(this.components);if(l==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=l,this.configureComponent(a,l),l[on]!=null&&(this.log("registering service %s for content routing",a),i.push(l[on])),l[sn]!=null&&(this.log("registering service %s for peer routing",a),s.push(l[sn])),l[Wo]!=null&&(this.log("registering service %s for peer discovery",a),l[Wo].addEventListener?.("peer",d=>{this.#e(d)}))}}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new ht;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 g("no protocols were provided to open a stream",z.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new g("no protocols were provided to open a stream",z.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){ko(e)&&(e=ge(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.code!==z.ERR_NOT_FOUND)throw s}let n=ve([M("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return zr(o),await this.peerStore.patch(e,{publicKey:o}),o}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){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error(new Error(z.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function _b(r={}){let e=r.peerId??=await K1();if(e.privateKey==null)throw new g("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await Ar(e.privateKey),new f4(await yb(r))}async function Ab(r={}){let e=await _b(r);return r.start!==!1&&await e.start(),e}async function Ib(r){let e=r.libp2p?.peerId,t=r.logger??So(),n=new Pe("/pkcs8/self"),o;e==null&&r.datastore!=null&&(o=Nd(r.keychain)({datastore:r.datastore,logger:t}),await r.datastore.has(n)&&(r.libp2p=r.libp2p??{},r.libp2p.peerId=await o.exportPeerId("self")));let s=lf(r);s.datastore=s.datastore??r.datastore,r=r??{};let i=await Ab({...s,...r.libp2p,start:!1});return e==null&&o!=null&&!await r.datastore.has(n)&&await o.importPeer("self",i.peerId),i}async function BN(r={}){let e=r.datastore??new vs,t=r.blockstore??new Qa,n;MN(r.libp2p)?n=r.libp2p:n=await Ib({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e});let o=new S1({...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[v2(),n2()],routers:[U2(n),B2()],metrics:n.metrics});return r.start!==!1&&await o.start(),o}function MN(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}return Mc(UN);})();
|
|
65
|
+
`),t),t.log('handle: responded with "na" for "%s"',o)}}var NN=500,d4=class{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){let{remoteAddr:t,remotePeer:n,newStream:o,close:s,abort:i,getStreams:a}=e;this.id=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=n,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),this.remoteAddr.getPeerId()==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=o,this._close=s,this._abort=i,this._getStreams=a,this.tags=[]}[Symbol.toStringTag]="Connection";[v4]=!0;get streams(){return this._getStreams()}async newStream(e,t){if(this.status==="closing")throw new g("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if(this.status==="closed")throw new g("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&t?.runOnTransientConnection!==!0)throw new g("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");let n=await this._newStream(e,t);return n.direction="outbound",n}async close(e={}){if(!(this.status==="closed"||this.status==="closing")){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",e.signal==null){let t=AbortSignal.timeout(NN);H(1/0,t),e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map(async t=>t.close(e))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(t){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,t),this.abort(t)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach(t=>{t.abort(e)}),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}};function Rb(r){return new d4(r)}var LN=3e4;function PN(r,e){try{let{options:t}=e.getHandler(r);return t.maxInboundStreams}catch(t){if(t.code!==z.ERR_NO_HANDLER_FOR_PROTOCOL)throw t}return c4}function ON(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.code!==z.ERR_NO_HANDLER_FOR_PROTOCOL)throw n}return t.maxOutboundStreams??l4}function Sb(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var Pf=class{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach(n=>{this.connectionEncryption.set(n.protocol,n)}),this.muxers=new Map,t.muxers.forEach(n=>{this.muxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}async shouldBlockConnection(e,t,n){let o=this.components.connectionGater[n];if(o!==void 0&&await o(e,t))throw new g(`The multiaddr connection is blocked by gater.${n}`,z.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new g("connection denied",z.ERR_CONNECTION_DENIED);let o,s,i,a,c,l=AbortSignal.timeout(this.inboundUpgradeTimeout),d=()=>{e.abort(new g("inbound upgrade timeout",vn))};l.addEventListener("abort",d,{once:!0}),H(1/0,l);try{if(await this.components.connectionGater.denyInboundConnection?.(e)===!0)throw new g("The multiaddr connection is blocked by gater.acceptConnection",z.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let u=e;if(t?.skipProtection!==!0){let h=this.components.connectionProtector;h!=null&&(e.log("protecting the inbound connection"),u=await h.protect(e))}try{if(o=u,t?.skipEncryption!==!0){({conn:o,remotePeer:s,protocol:c}=await this._encryptInbound(u));let h={...u,...o};await this.shouldBlockConnection(s,h,"denyInboundEncryptedConnection")}else{let h=e.remoteAddr.getPeerId();if(h==null)throw new g("inbound connection that skipped encryption must have a peer id",z.ERR_INVALID_MULTIADDR);let f=ge(h);c="native",s=f}if(i=o,t?.muxerFactory!=null)a=t.muxerFactory;else if(this.muxers.size>0){let h=await this._multiplexInbound({...u,...o},this.muxers);a=h.muxerFactory,i=h.stream}}catch(h){throw e.log.error("failed to upgrade inbound connection",h),h}return await this.shouldBlockConnection(s,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:c,direction:"inbound",maConn:e,upgradedConn:i,muxerFactory:a,remotePeer:s,transient:t?.transient})}finally{l.removeEventListener("abort",d),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){let n=e.remoteAddr.getPeerId(),o;n!=null&&(o=ge(n),await this.shouldBlockConnection(o,e,"denyOutboundConnection"));let s,i,a,c,l;this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let d=e;if(t?.skipProtection!==!0){let u=this.components.connectionProtector;u!=null&&(d=await u.protect(e))}try{if(s=d,t?.skipEncryption!==!0){({conn:s,remotePeer:i,protocol:c}=await this._encryptOutbound(d,o));let u={...d,...s};await this.shouldBlockConnection(i,u,"denyOutboundEncryptedConnection")}else{if(o==null)throw new g("Encryption was skipped but no peer id was passed",z.ERR_INVALID_PEER);c="native",i=o}if(a=s,t?.muxerFactory!=null)l=t.muxerFactory;else if(this.muxers.size>0){let u=await this._multiplexOutbound({...d,...s},this.muxers);l=u.muxerFactory,a=u.stream}}catch(u){throw e.log.error("failed to upgrade outbound connection",u),await e.close(u),u}return await this.shouldBlockConnection(i,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:c,direction:"outbound",maConn:e,upgradedConn:a,muxerFactory:l,remotePeer:i,transient:t?.transient})}_createConnection(e){let{cryptoProtocol:t,direction:n,maConn:o,upgradedConn:s,remotePeer:i,muxerFactory:a,transient:c}=e,l,d,u;a!=null&&(l=a.createStreamMuxer({direction:n,onIncomingStream:p=>{u!=null&&Promise.resolve().then(async()=>{let m=this.components.registrar.getProtocols(),{stream:y,protocol:w}=await Oc(p,m,{log:p.log,yieldBytes:!1});if(u==null)return;u.log("incoming stream opened on %s",w);let b=PN(w,this.components.registrar);if(Sb(w,"inbound",u)===b){let x=new g(`Too many inbound protocol streams for protocol "${w}" - limit ${b}`,z.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw p.abort(x),x}p.source=y.source,p.sink=y.sink,p.protocol=w,y.closeWrite!=null&&(p.closeWrite=y.closeWrite),y.closeRead!=null&&(p.closeRead=y.closeRead),y.close!=null&&(p.close=y.close),await this.components.peerStore.merge(i,{protocols:[w]}),this.components.metrics?.trackProtocolStream(p,u),this._onStream({connection:u,stream:p,protocol:w})}).catch(async m=>{u.log.error("error handling incoming stream id %s",p.id,m.message,m.code,m.stack),p.timeline.close==null&&await p.close()})}}),d=async(p,m={})=>{if(l==null)throw new g("Stream is not multiplexed",z.ERR_MUXER_UNAVAILABLE);u.log("starting new stream for protocols %s",p);let y=await l.newStream();u.log.trace("started new stream %s for protocols %s",y.id,p);try{if(m.signal==null){y.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",p);let v=AbortSignal.timeout(LN);H(1/0,v),m={...m,signal:v}}y.log.trace("selecting protocol from protocols %s",p);let{stream:w,protocol:b}=await Pc(y,p,{...m,log:y.log,yieldBytes:!0});y.log("selected protocol %s",b);let E=ON(b,this.components.registrar,m),x=Sb(b,"outbound",u);if(x>=E){let v=new g(`Too many outbound protocol streams for protocol "${b}" - ${x}/${E}`,z.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw y.abort(v),v}return await this.components.peerStore.merge(i,{protocols:[b]}),y.source=w.source,y.sink=w.sink,y.protocol=b,w.closeWrite!=null&&(y.closeWrite=w.closeWrite),w.closeRead!=null&&(y.closeRead=w.closeRead),w.close!=null&&(y.close=w.close),this.components.metrics?.trackProtocolStream(y,u),y}catch(w){throw u.log.error("could not create new stream for protocols %s",p,w),y.timeline.close==null&&y.abort(w),w.code!=null?w:new g(String(w),z.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([l.sink(s.source),s.sink(l.source)]).catch(p=>{u.log.error("error piping data through muxer",p)}));let h=o.timeline;o.timeline=new Proxy(h,{set:(...p)=>(u!=null&&p[1]==="close"&&p[2]!=null&&h.close==null&&(async()=>{try{u.status==="open"&&await u.close()}catch(m){u.log.error("error closing connection after timeline close",m)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch(m=>{u.log.error("error thrown while dispatching connection:close event",m)}),Reflect.set(...p))}),o.timeline.upgraded=Date.now();let f=()=>{throw new g("connection is not multiplexed",z.ERR_CONNECTION_NOT_MULTIPLEXED)};return u=Rb({remoteAddr:o.remoteAddr,remotePeer:i,status:"open",direction:n,timeline:o.timeline,multiplexer:l?.protocol,encryption:t,transient:c,logger:this.components.logger,newStream:d??f,getStreams:()=>l!=null?l.streams:[],close:async p=>{l!=null&&(u.log.trace("close muxer"),await l.close(p)),u.log.trace("close maconn"),await o.close(p),u.log.trace("closed maconn")},abort:p=>{o.abort(p),l?.abort(p)}}),this.events.safeDispatchEvent("connection:open",{detail:u}),u}_onStream(e){let{connection:t,stream:n,protocol:o}=e,{handler:s,options:i}=this.components.registrar.getHandler(o);if(t.transient&&i.runOnTransientConnection!==!0)throw new g("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:n})}async _encryptInbound(e){let t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{let{stream:n,protocol:o}=await Oc(e,t,{log:e.log}),s=this.connectionEncryption.get(o);if(s==null)throw new Error(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using",o),{...await s.secureInbound(this.components.peerId,n),protocol:o}}catch(n){throw e.log.error("encrypting inbound connection failed",n),new g(n.message,z.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",n);try{e.log.trace("selecting encrypter from %s",n);let{stream:o,protocol:s}=await Pc(e,n,{log:e.log,yieldBytes:!0}),i=this.connectionEncryption.get(s);if(i==null)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,i),{...await i.secureOutbound(this.components.peerId,o,t),protocol:s}}catch(o){throw e.log.error("encrypting outbound connection to %p failed",t,o),new g(o.message,z.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){let n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);let{stream:o,protocol:s}=await Pc(e,n,{log:e.log,yieldBytes:!0});e.log("selected %s as muxer protocol",s);let i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing outbound connection",o),new g(String(o),z.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){let n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{let{stream:o,protocol:s}=await Oc(e,n,{log:e.log}),i=t.get(s);return{stream:o,muxerFactory:i}}catch(o){throw e.log.error("error multiplexing inbound connection",o),new g(String(o),z.ERR_MUXER_UNAVAILABLE)}}};var f4=class extends ye{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new ye,n=t.dispatchEvent.bind(t);t.dispatchEvent=a=>{let c=n(a),l=this.dispatchEvent(new Ot(a.type,{detail:a.detail}));return c||l},H(1/0,t),this.peerId=e.peerId,this.logger=e.logger??So(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=this.components=mb({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:cf,version:af},logger:this.logger,events:t,datastore:e.datastore??new vs,connectionGater:gb(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new gf(o,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),o.events.addEventListener("peer:update",a=>{if(a.detail.previous==null){let c={id:a.detail.peer.id,multiaddrs:a.detail.peer.addresses.map(l=>l.multiaddr)};o.events.safeDispatchEvent("peer:discovery",{detail:c})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(o)),this.components.upgrader=new Pf(this.components,{connectionEncryption:(e.connectionEncryption??[]).map((a,c)=>this.configureComponent(`connection-encryption-${c}`,a(this.components))),muxers:(e.streamMuxers??[]).map((a,c)=>this.configureComponent(`stream-muxers-${c}`,a(this.components))),inboundUpgradeTimeout:e.connectionManager.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Lf(this.components,e.transportManager)),this.configureComponent("connectionManager",new Df(this.components,e.connectionManager)),this.configureComponent("registrar",new Nf(this.components)),this.configureComponent("addressManager",new yf(this.components,e.addresses));let s=(e.peerRouters??[]).map((a,c)=>this.configureComponent(`peer-router-${c}`,a(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new kf(this.components,{routers:s}));let i=(e.contentRouters??[]).map((a,c)=>this.configureComponent(`content-router-${c}`,a(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Tf(this.components,{routers:i})),this.configureComponent("randomWalk",new Cf(this.components)),(e.peerDiscovery??[]).forEach((a,c)=>{this.configureComponent(`peer-discovery-${c}`,a(this.components)).addEventListener("peer",d=>{this.#e(d)})}),e.transports?.forEach((a,c)=>{this.components.transportManager.add(this.configureComponent(`transport-${c}`,a(this.components)))}),e.services!=null)for(let a of Object.keys(e.services)){let c=e.services[a],l=c(this.components);if(l==null){this.log.error("service factory %s returned null or undefined instance",a);continue}this.services[a]=l,this.configureComponent(a,l),l[on]!=null&&(this.log("registering service %s for content routing",a),i.push(l[on])),l[sn]!=null&&(this.log("registering service %s for peer routing",a),s.push(l[sn])),l[Wo]!=null&&(this.log("registering service %s for peer discovery",a),l[Wo].addEventListener?.("peer",d=>{this.#e(d)}))}}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new ht;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 g("no protocols were provided to open a stream",z.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(t=Array.isArray(t)?t:[t],t.length===0)throw new g("no protocols were provided to open a stream",z.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,n)).newStream(t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){ko(e)&&(e=ge(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let s=await this.peerStore.get(e);if(s.id.publicKey!=null)return s.id.publicKey}catch(s){if(s.code!==z.ERR_NOT_FOUND)throw s}let n=ve([M("/pk/"),e.multihash.digest]),o=await this.contentRouting.get(n,t);return zr(o),await this.peerStore.patch(e,{publicKey:o}),o}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){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async t=>{await this.components.registrar.unhandle(t)}))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error(new Error(z.ERR_DISCOVERED_SELF));return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error(n)})}};async function _b(r={}){let e=r.peerId??=await K1();if(e.privateKey==null)throw new g("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return r.privateKey??=await Ar(e.privateKey),new f4(await yb(r))}async function Ab(r={}){let e=await _b(r);return r.start!==!1&&await e.start(),e}async function Ib(r){let e=r.libp2p?.peerId,t=r.logger??So(),n=new Pe("/pkcs8/self"),o;e==null&&r.datastore!=null&&(o=Nd(r.keychain)({datastore:r.datastore,logger:t}),await r.datastore.has(n)&&(r.libp2p=r.libp2p??{},r.libp2p.peerId=await o.exportPeerId("self")));let s=lf(r);s.datastore=s.datastore??r.datastore,r=r??{};let i=await Ab({...s,...r.libp2p,start:!1});return e==null&&o!=null&&!await r.datastore.has(n)&&await o.importPeer("self",i.peerId),i}async function BN(r={}){let e=r.datastore??new vs,t=r.blockstore??new Qa,n;MN(r.libp2p)?n=r.libp2p:n=await Ib({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e});let o=new S1({...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[v2(),n2()],routers:[U2(n),B2()],metrics:n.metrics});return r.start!==!1&&await o.start(),o}function MN(r){return r==null?!1:["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every(t=>typeof r[t]=="function")}return Mc(UN);})();
|
|
66
66
|
/*! Bundled license information:
|
|
67
67
|
|
|
68
68
|
pvtsutils/build/index.js:
|