@helia/verified-fetch 1.4.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +1 -1
  2. package/dist/index.min.js +17 -18
  3. package/dist/src/errors.d.ts +13 -0
  4. package/dist/src/errors.d.ts.map +1 -0
  5. package/dist/src/errors.js +22 -0
  6. package/dist/src/errors.js.map +1 -0
  7. package/dist/src/index.d.ts +1 -1
  8. package/dist/src/index.js +2 -2
  9. package/dist/src/index.js.map +1 -1
  10. package/dist/src/utils/byte-range-context.d.ts.map +1 -1
  11. package/dist/src/utils/byte-range-context.js +3 -2
  12. package/dist/src/utils/byte-range-context.js.map +1 -1
  13. package/dist/src/utils/get-stream-from-async-iterable.d.ts.map +1 -1
  14. package/dist/src/utils/get-stream-from-async-iterable.js +2 -1
  15. package/dist/src/utils/get-stream-from-async-iterable.js.map +1 -1
  16. package/dist/src/utils/get-tar-stream.js +3 -3
  17. package/dist/src/utils/get-tar-stream.js.map +1 -1
  18. package/dist/src/utils/handle-redirects.d.ts.map +1 -1
  19. package/dist/src/utils/handle-redirects.js +2 -1
  20. package/dist/src/utils/handle-redirects.js.map +1 -1
  21. package/dist/src/utils/parse-url-string.d.ts.map +1 -1
  22. package/dist/src/utils/parse-url-string.js +5 -2
  23. package/dist/src/utils/parse-url-string.js.map +1 -1
  24. package/dist/src/utils/request-headers.d.ts.map +1 -1
  25. package/dist/src/utils/request-headers.js +5 -4
  26. package/dist/src/utils/request-headers.js.map +1 -1
  27. package/dist/src/utils/response-headers.d.ts.map +1 -1
  28. package/dist/src/utils/response-headers.js +3 -2
  29. package/dist/src/utils/response-headers.js.map +1 -1
  30. package/dist/src/utils/select-output-type.js +1 -1
  31. package/dist/src/utils/select-output-type.js.map +1 -1
  32. package/dist/src/utils/walk-path.d.ts.map +1 -1
  33. package/dist/src/utils/walk-path.js +3 -2
  34. package/dist/src/utils/walk-path.js.map +1 -1
  35. package/dist/src/verified-fetch.d.ts.map +1 -1
  36. package/dist/src/verified-fetch.js +2 -2
  37. package/dist/src/verified-fetch.js.map +1 -1
  38. package/package.json +120 -35
  39. package/src/errors.ts +26 -0
  40. package/src/index.ts +2 -2
  41. package/src/utils/byte-range-context.ts +3 -2
  42. package/src/utils/get-stream-from-async-iterable.ts +2 -1
  43. package/src/utils/get-tar-stream.ts +3 -3
  44. package/src/utils/handle-redirects.ts +2 -1
  45. package/src/utils/parse-url-string.ts +6 -3
  46. package/src/utils/request-headers.ts +6 -4
  47. package/src/utils/response-headers.ts +3 -2
  48. package/src/utils/select-output-type.ts +1 -1
  49. package/src/utils/walk-path.ts +3 -2
  50. package/src/verified-fetch.ts +4 -5
package/dist/index.min.js CHANGED
@@ -1,25 +1,24 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaVerifiedFetch = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var HeliaVerifiedFetch=(()=>{var tb=Object.create;var ss=Object.defineProperty;var rb=Object.getOwnPropertyDescriptor;var nb=Object.getOwnPropertyNames;var ob=Object.getPrototypeOf,ib=Object.prototype.hasOwnProperty;var Oe=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Se=(r,e)=>{for(var t in e)ss(r,t,{get:e[t],enumerable:!0})},Fh=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of nb(e))!ib.call(r,o)&&o!==t&&ss(r,o,{get:()=>e[o],enumerable:!(n=rb(e,o))||n.enumerable});return r};var re=(r,e,t)=>(t=r!=null?tb(ob(r)):{},Fh(e||!r||!r.__esModule?ss(t,"default",{value:r,enumerable:!0}):t,r)),sb=r=>Fh(ss({},"__esModule",{value:!0}),r);var De=Oe((SI,Gh)=>{"use strict";function qh(r,e){for(let t in e)Object.defineProperty(r,t,{value:e[t],enumerable:!0,configurable:!0});return r}function yb(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 qh(r,t)}catch{t.message=r.message,t.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),qh(new o,t)}}Gh.exports=yb});var Jd=Oe(fo=>{"use strict";var J1="[object ArrayBuffer]",wr=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===J1}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let i=0;i<n.length;i++)if(n[i]!==o[i])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let s of t)n+=s.byteLength;let o=new Uint8Array(n),i=0;for(let s of t){let a=this.toUint8Array(s);o.set(a,i),i+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},gu="string",Q1=/^[0-9a-f]+$/i,eE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,tE=/^[a-zA-Z0-9-_]+$/,Ds=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=wr.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return decodeURIComponent(escape(n))}},kt=class{static toString(e,t=!1){let n=wr.toArrayBuffer(e),o=new DataView(n),i="";for(let s=0;s<n.byteLength;s+=2){let a=o.getUint16(s,t);i+=String.fromCharCode(a)}return i}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let i=0;i<e.length;i++)o.setUint16(i*2,e.charCodeAt(i),t);return n}},Ps=class r{static isHex(e){return typeof e===gu&&Q1.test(e)}static isBase64(e){return typeof e===gu&&eE.test(e)}static isBase64Url(e){return typeof e===gu&&tE.test(e)}static ToString(e,t="utf8"){let n=wr.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 kt.toString(n,!0);case"utf16":case"utf16be":return kt.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 kt.fromString(e,!0);case"utf16":case"utf16be":return kt.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=wr.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 Ds.fromString(e);case"utf16":case"utf16be":return kt.fromString(e);case"utf16le":case"usc2":return kt.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 Ds.toString(e);case"utf16":case"utf16be":return kt.toString(e);case"utf16le":case"usc2":return kt.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=wr.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=wr.toUint8Array(e),n="",o=t.length;for(let i=0;i<o;i++){let s=t[i];s<16&&(n+="0"),n+=s.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let i=t.slice(o,o+2);n[o/2]=parseInt(i,16)}return n.buffer}static ToUtf16String(e,t=!1){return kt.toString(e,t)}static FromUtf16String(e,t=!1){return kt.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,"")||""}};Ps.DEFAULT_UTF8_ENCODING="utf8";function rE(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let i in o)t[i]=o[i]}return t}function nE(...r){let e=r.map(o=>o.byteLength).reduce((o,i)=>o+i),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let i of o)t[n++]=i}),t.buffer}function oE(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}fo.BufferSourceConverter=wr;fo.Convert=Ps;fo.assign=rE;fo.combine=nE;fo.isEqual=oE});var im=Oe((gi,Aa)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var m=0;m<h.length;m++)if(!Number.isInteger(h[m])||h[m]<0||h[m]>255)return!1;return!0}function o(h,m){return(h&65535)*m+(((h>>>16)*m&65535)<<16)}function i(h,m){return h<<m|h>>>32-m}function s(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var d=[0,0,0,0];return d[3]+=h[3]+m[3],d[2]+=d[3]>>>16,d[3]&=65535,d[2]+=h[2]+m[2],d[1]+=d[2]>>>16,d[2]&=65535,d[1]+=h[1]+m[1],d[0]+=d[1]>>>16,d[1]&=65535,d[0]+=h[0]+m[0],d[0]&=65535,[d[0]<<16|d[1],d[2]<<16|d[3]]}function c(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var d=[0,0,0,0];return d[3]+=h[3]*m[3],d[2]+=d[3]>>>16,d[3]&=65535,d[2]+=h[2]*m[3],d[1]+=d[2]>>>16,d[2]&=65535,d[2]+=h[3]*m[2],d[1]+=d[2]>>>16,d[2]&=65535,d[1]+=h[1]*m[3],d[0]+=d[1]>>>16,d[1]&=65535,d[1]+=h[2]*m[2],d[0]+=d[1]>>>16,d[1]&=65535,d[1]+=h[3]*m[1],d[0]+=d[1]>>>16,d[1]&=65535,d[0]+=h[0]*m[3]+h[1]*m[2]+h[2]*m[1]+h[3]*m[0],d[0]&=65535,[d[0]<<16|d[1],d[2]<<16|d[3]]}function l(h,m){return m%=64,m===32?[h[1],h[0]]:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m|h[0]>>>32-m]:(m-=32,[h[1]<<m|h[0]>>>32-m,h[0]<<m|h[1]>>>32-m])}function f(h,m){return m%=64,m===0?h:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m]:[h[1]<<m-32,0]}function u(h,m){return[h[0]^m[0],h[1]^m[1]]}function p(h){return h=u(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=u(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=u(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%4,y=h.length-d,g=m,b=0,x=3432918353,E=461845907,v=0;v<y;v=v+4)b=h[v]|h[v+1]<<8|h[v+2]<<16|h[v+3]<<24,b=o(b,x),b=i(b,15),b=o(b,E),g^=b,g=i(g,13),g=o(g,5)+3864292196;switch(b=0,d){case 3:b^=h[v+2]<<16;case 2:b^=h[v+1]<<8;case 1:b^=h[v],b=o(b,x),b=i(b,15),b=o(b,E),g^=b}return g^=h.length,g=s(g),g>>>0},t.x86.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%16,y=h.length-d,g=m,b=m,x=m,E=m,v=0,_=0,S=0,A=0,L=597399067,U=2869860233,O=951274213,$=2716044179,C=0;C<y;C=C+16)v=h[C]|h[C+1]<<8|h[C+2]<<16|h[C+3]<<24,_=h[C+4]|h[C+5]<<8|h[C+6]<<16|h[C+7]<<24,S=h[C+8]|h[C+9]<<8|h[C+10]<<16|h[C+11]<<24,A=h[C+12]|h[C+13]<<8|h[C+14]<<16|h[C+15]<<24,v=o(v,L),v=i(v,15),v=o(v,U),g^=v,g=i(g,19),g+=b,g=o(g,5)+1444728091,_=o(_,U),_=i(_,16),_=o(_,O),b^=_,b=i(b,17),b+=x,b=o(b,5)+197830471,S=o(S,O),S=i(S,17),S=o(S,$),x^=S,x=i(x,15),x+=E,x=o(x,5)+2530024501,A=o(A,$),A=i(A,18),A=o(A,L),E^=A,E=i(E,13),E+=g,E=o(E,5)+850148119;switch(v=0,_=0,S=0,A=0,d){case 15:A^=h[C+14]<<16;case 14:A^=h[C+13]<<8;case 13:A^=h[C+12],A=o(A,$),A=i(A,18),A=o(A,L),E^=A;case 12:S^=h[C+11]<<24;case 11:S^=h[C+10]<<16;case 10:S^=h[C+9]<<8;case 9:S^=h[C+8],S=o(S,O),S=i(S,17),S=o(S,$),x^=S;case 8:_^=h[C+7]<<24;case 7:_^=h[C+6]<<16;case 6:_^=h[C+5]<<8;case 5:_^=h[C+4],_=o(_,U),_=i(_,16),_=o(_,O),b^=_;case 4:v^=h[C+3]<<24;case 3:v^=h[C+2]<<16;case 2:v^=h[C+1]<<8;case 1:v^=h[C],v=o(v,L),v=i(v,15),v=o(v,U),g^=v}return g^=h.length,b^=h.length,x^=h.length,E^=h.length,g+=b,g+=x,g+=E,b+=g,x+=g,E+=g,g=s(g),b=s(b),x=s(x),E=s(E),g+=b,g+=x,g+=E,b+=g,x+=g,E+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(E>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var d=h.length%16,y=h.length-d,g=[0,m],b=[0,m],x=[0,0],E=[0,0],v=[2277735313,289559509],_=[1291169091,658871167],S=0;S<y;S=S+16)x=[h[S+4]|h[S+5]<<8|h[S+6]<<16|h[S+7]<<24,h[S]|h[S+1]<<8|h[S+2]<<16|h[S+3]<<24],E=[h[S+12]|h[S+13]<<8|h[S+14]<<16|h[S+15]<<24,h[S+8]|h[S+9]<<8|h[S+10]<<16|h[S+11]<<24],x=c(x,v),x=l(x,31),x=c(x,_),g=u(g,x),g=l(g,27),g=a(g,b),g=a(c(g,[0,5]),[0,1390208809]),E=c(E,_),E=l(E,33),E=c(E,v),b=u(b,E),b=l(b,31),b=a(b,g),b=a(c(b,[0,5]),[0,944331445]);switch(x=[0,0],E=[0,0],d){case 15:E=u(E,f([0,h[S+14]],48));case 14:E=u(E,f([0,h[S+13]],40));case 13:E=u(E,f([0,h[S+12]],32));case 12:E=u(E,f([0,h[S+11]],24));case 11:E=u(E,f([0,h[S+10]],16));case 10:E=u(E,f([0,h[S+9]],8));case 9:E=u(E,[0,h[S+8]]),E=c(E,_),E=l(E,33),E=c(E,v),b=u(b,E);case 8:x=u(x,f([0,h[S+7]],56));case 7:x=u(x,f([0,h[S+6]],48));case 6:x=u(x,f([0,h[S+5]],40));case 5:x=u(x,f([0,h[S+4]],32));case 4:x=u(x,f([0,h[S+3]],24));case 3:x=u(x,f([0,h[S+2]],16));case 2:x=u(x,f([0,h[S+1]],8));case 1:x=u(x,[0,h[S]]),x=c(x,v),x=l(x,31),x=c(x,_),g=u(g,x)}return g=u(g,[0,h.length]),b=u(b,[0,h.length]),g=a(g,b),b=a(b,g),g=p(g),b=p(b),g=a(g,b),b=a(b,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof gi<"u"?(typeof Aa<"u"&&Aa.exports&&(gi=Aa.exports=t),gi.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)})(gi)});var Nu=Oe((A8,sm)=>{sm.exports=im()});var cm=Oe((_8,am)=>{var yo=1e3,wo=yo*60,bo=wo*60,Tn=bo*24,UE=Tn*7,FE=Tn*365.25;am.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return ME(r);if(t==="number"&&isFinite(r))return e.long?HE(r):VE(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function ME(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*FE;case"weeks":case"week":case"w":return t*UE;case"days":case"day":case"d":return t*Tn;case"hours":case"hour":case"hrs":case"hr":case"h":return t*bo;case"minutes":case"minute":case"mins":case"min":case"m":return t*wo;case"seconds":case"second":case"secs":case"sec":case"s":return t*yo;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function VE(r){var e=Math.abs(r);return e>=Tn?Math.round(r/Tn)+"d":e>=bo?Math.round(r/bo)+"h":e>=wo?Math.round(r/wo)+"m":e>=yo?Math.round(r/yo)+"s":r+"ms"}function HE(r){var e=Math.abs(r);return e>=Tn?_a(r,e,Tn,"day"):e>=bo?_a(r,e,bo,"hour"):e>=wo?_a(r,e,wo,"minute"):e>=yo?_a(r,e,yo,"second"):r+" ms"}function _a(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var um=Oe((I8,lm)=>{function $E(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=s,t.humanize=cm(),t.destroy=l,Object.keys(r).forEach(f=>{t[f]=r[f]}),t.names=[],t.skips=[],t.formatters={};function e(f){let u=0;for(let p=0;p<f.length;p++)u=(u<<5)-u+f.charCodeAt(p),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(f){let u,p=null,h,m;function d(...y){if(!d.enabled)return;let g=d,b=Number(new Date),x=b-(u||b);g.diff=x,g.prev=u,g.curr=b,u=b,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let E=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(_,S)=>{if(_==="%%")return"%";E++;let A=t.formatters[S];if(typeof A=="function"){let L=y[E];_=A.call(g,L),y.splice(E,1),E--}return _}),t.formatArgs.call(g,y),(g.log||t.log).apply(g,y)}return d.namespace=f,d.useColors=t.useColors(),d.color=t.selectColor(f),d.extend=n,d.destroy=t.destroy,Object.defineProperty(d,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(h!==t.namespaces&&(h=t.namespaces,m=t.enabled(f)),m),set:y=>{p=y}}),typeof t.init=="function"&&t.init(d),d}function n(f,u){let p=t(this.namespace+(typeof u>"u"?":":u)+f);return p.log=this.log,p}function o(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let u,p=(typeof f=="string"?f:"").split(/[\s,]+/),h=p.length;for(u=0;u<h;u++)p[u]&&(f=p[u].replace(/\*/g,".*?"),f[0]==="-"?t.skips.push(new RegExp("^"+f.slice(1)+"$")):t.names.push(new RegExp("^"+f+"$")))}function i(){let f=[...t.names.map(a),...t.skips.map(a).map(u=>"-"+u)].join(",");return t.enable(""),f}function s(f){if(f[f.length-1]==="*")return!0;let u,p;for(u=0,p=t.skips.length;u<p;u++)if(t.skips[u].test(f))return!1;for(u=0,p=t.names.length;u<p;u++)if(t.names[u].test(f))return!0;return!1}function a(f){return f.toString().substring(2,f.toString().length-2).replace(/\.\*\?$/,"*")}function c(f){return f instanceof Error?f.stack||f.message:f}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}lm.exports=$E});var fm=Oe((pt,Ia)=>{pt.formatArgs=KE;pt.save=qE;pt.load=GE;pt.useColors=zE;pt.storage=WE();pt.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`."))}})();pt.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 zE(){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 KE(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ia.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)}pt.log=console.debug||console.log||(()=>{});function qE(r){try{r?pt.storage.setItem("debug",r):pt.storage.removeItem("debug")}catch{}}function GE(){let r;try{r=pt.storage.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function WE(){try{return localStorage}catch{}}Ia.exports=um()(pt);var{formatters:jE}=Ia.exports;jE.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var pm=Oe((N8,Cu)=>{"use strict";var XE=Object.prototype.hasOwnProperty,et="~";function yi(){}Object.create&&(yi.prototype=Object.create(null),new yi().__proto__||(et=!1));function ZE(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function dm(r,e,t,n,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new ZE(t,n||r,o),s=et?et+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],i]:r._events[s].push(i):(r._events[s]=i,r._eventsCount++),r}function Ra(r,e){--r._eventsCount===0?r._events=new yi:delete r._events[e]}function We(){this._events=new yi,this._eventsCount=0}We.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)XE.call(t,n)&&e.push(et?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};We.prototype.listeners=function(e){var t=et?et+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,s=new Array(i);o<i;o++)s[o]=n[o].fn;return s};We.prototype.listenerCount=function(e){var t=et?et+e:e,n=this._events[t];return n?n.fn?1:n.length:0};We.prototype.emit=function(e,t,n,o,i,s){var a=et?et+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,f,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,i),!0;case 6:return c.fn.call(c.context,t,n,o,i,s),!0}for(u=1,f=new Array(l-1);u<l;u++)f[u-1]=arguments[u];c.fn.apply(c.context,f)}else{var p=c.length,h;for(u=0;u<p;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(!f)for(h=1,f=new Array(l-1);h<l;h++)f[h-1]=arguments[h];c[u].fn.apply(c[u].context,f)}}return!0};We.prototype.on=function(e,t,n){return dm(this,e,t,n,!1)};We.prototype.once=function(e,t,n){return dm(this,e,t,n,!0)};We.prototype.removeListener=function(e,t,n,o){var i=et?et+e:e;if(!this._events[i])return this;if(!t)return Ra(this,i),this;var s=this._events[i];if(s.fn)s.fn===t&&(!o||s.once)&&(!n||s.context===n)&&Ra(this,i);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==t||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:Ra(this,i)}return this};We.prototype.removeAllListeners=function(e){var t;return e?(t=et?et+e:e,this._events[t]&&Ra(this,t)):(this._events=new yi,this._eventsCount=0),this};We.prototype.off=We.prototype.removeListener;We.prototype.addListener=We.prototype.on;We.prefixed=et;We.EventEmitter=We;typeof Cu<"u"&&(Cu.exports=We)});var Fu=Oe((eT,wm)=>{wm.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function o(i,s){t[i]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(i){return t[i]!==void 0||n[i]!==void 0},remove:function(i){t[i]!==void 0&&(t[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=t[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){t[i]!==void 0?t[i]=s:o(i,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Yg=Oe(Pi=>{(function(){var r,e,t,n,o,i,s,a;a=function(c){var l,f,u,p;return l=(c&255<<24)>>>24,f=(c&255<<16)>>>16,u=(c&65280)>>>8,p=c&255,[l,f,u,p].join(".")},s=function(c){var l,f,u,p,h,m;for(l=[],u=p=0;p<=3&&c.length!==0;u=++p){if(u>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}m=e(c),h=m[0],f=m[1],c=c.substring(f),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),i=t("a"),o=t("A"),e=function(c){var l,f,u,p,h;for(p=0,l=10,f="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,f="7")),h=u;u<c.length;){if("0"<=c[u]&&c[u]<=f)p=p*l+(t(c[u])-n)>>>0;else if(l===16)if("a"<=c[u]&&c[u]<="f")p=p*l+(10+t(c[u])-i)>>>0;else if("A"<=c[u]&&c[u]<="F")p=p*l+(10+t(c[u])-o)>>>0;else break;else break;if(p>4294967295)throw new Error("too large");u++}if(u===h)throw new Error("empty octet");return[p,u]},r=function(){function c(l,f){var u,p,h,m;if(typeof l!="string")throw new Error("Missing `net' parameter");if(f||(m=l.split("/",2),l=m[0],f=m[1]),f||(f=32),typeof f=="string"&&f.indexOf(".")>-1){try{this.maskLong=s(f)}catch(d){throw u=d,new Error("Invalid mask: "+f)}for(p=h=32;h>=0;p=--h)if(this.maskLong===4294967295<<32-p>>>0){this.bitmask=p;break}}else if(f||f===0)this.bitmask=parseInt(f,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(s(l)&this.maskLong)>>>0}catch(d){throw u=d,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+f);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):(s(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 f,u,p;for(p=s(this.first),u=s(this.last),f=0;p<=u;)l(a(p),p,f),f++,p++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Pi.ip2long=s,Pi.long2ip=a,Pi.Netmask=r}).call(Pi)});var Ec=Oe((aL,Pf)=>{var sL=function(){typeof Pf<"u"&&(Pf.exports=d);var r=86400,e=3200,t=146097*e/400,n=r*t,o=1e3*n,i=864e13,s=4294967296,a=1e6,c="000000000",l=Math.trunc||function(A){var L=A-A%1;return L==0&&(A<0||A===0&&1/A!=1/0)?-0:L},f=d.prototype,u=(d.fromDate=function(A){return new d(+A)},d.fromInt64BE=E(0,1,2,3,0,4),d.fromInt64LE=E(3,2,1,0,4,0),d.fromString=function(O){var L,U=new d,O=(O+="").replace(/^\s*[+\-]?\d+/,function(C){var C=+C,ee=1970+(C-1970)%400;return U.year=C-ee,ee}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function($,C,ee){return C<0&&(ee*=-1),L=6e4*(60*+C+ +ee),""}).replace(/\.\d+$/,function($){return U.nano=+($+c).substr(1,9),""}).split(/\D+/);if(1<O.length?O[1]--:O[1]=0,U.time=L=Date.UTC.apply(Date,O)-(L||0),isNaN(L))throw new TypeError("Invalid Date");return y(U)},d.fromTimeT=function(A){return b(A,0)},f.year=0,f.time=0,f.nano=0,f.addNano=function(A){return this.nano+=+A||0,this},f.getNano=function(){var A=y(this);return(A.time%1e3*a+ +A.nano+1e9)%1e9},f.getTimeT=function(){var L=y(this),A=Math.floor(L.time/1e3),L=L.year;return L&&(A+=L*t*r/e),A},f.getYear=function(){return this.toDate().getUTCFullYear()+this.year},f.toDate=function(){return g(y(this).time)},f.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},f.toString=function(A){var L=this,U=L.toDate(),O={H:function(){return _(U.getUTCHours())},L:function(){return S(U.getUTCMilliseconds(),3)},M:function(){return _(U.getUTCMinutes())},N:function(){return S(L.getNano(),9)},S:function(){return _(U.getUTCSeconds())},Y:function(){var $=L.getYear();return 999999<$?"+"+$:9999<$?"+"+S($,6):0<=$?S($,4):-999999<=$?"-"+S(-$,6):$},a:function(){return h[U.getUTCDay()]},b:function(){return p[U.getUTCMonth()]},d:function(){return _(U.getUTCDate())},e:function(){return function($){return(9<$?"":" ")+(0|$)}(U.getUTCDate())},m:function(){return _(U.getUTCMonth()+1)}};return function $(C){return C.replace(/%./g,function(ee){var T=ee[1],k=m[T],T=O[T];return k?$(k):T?T():ee})}(A||u)},f.writeInt64BE=x(0,1,2,3,0,4),f.writeInt64LE=x(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),p=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m={"%":"%",F:"%Y-%m-%d",n:`
3
- `,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return d;function d(A,L,U){var O=this;if(!(O instanceof d))return new d(A,L,U);O.time=+A||0,O.nano=+L||0,O.year=+U||0,y(O)}function y(A){var L,U,O,$=A.year,C=A.time,ee=A.nano,k=((ee<0||a<=ee)&&(ee-=(U=Math.floor(ee/a))*a,C+=U,U=1),$%e);return(C<-i||i<C||k)&&((L=l(C/o))&&($+=L*e,C-=L*o),(O=g(C)).setUTCFullYear(k+O.getUTCFullYear()),O=(C=+O)+(L=l(($-=k)/e))*o,L&&-i<=O&&O<=i&&($-=L*e,C=O),U=1),U&&(A.year=$,A.time=C,A.nano=ee),A}function g(A){var L=new Date(0);return L.setTime(A),L}function b($,O){$=+$||0;var U=l((O=(O|0)*s)/n)+l($/n),O=O%n+$%n,$=l(O/n);return $&&(U+=$,O-=$*n),new d(1e3*O,0,U*e)}function x(A,L,U,O,$,C){return function(k,T){var B=y(this);k=k||new Array(8),v(k,T|=0);var I=Math.floor(B.time/1e3),B=B.year*(t*r/e),q=l(B/s)+l(I/s),B=B%s+I%s,I=Math.floor(B/s);return I&&(q+=I,B-=I*s),ee(k,T+$,q),ee(k,T+C,B),k};function ee(k,T,q){k[T+A]=q>>24&255,k[T+L]=q>>16&255,k[T+U]=q>>8&255,k[T+O]=255&q}}function E(A,L,U,O,$,C){return function(k,T){v(k,T|=0);var q=ee(k,T+$);return b(ee(k,T+C),q)};function ee(k,T){return 16777216*k[T+A]+(k[T+L]<<16|k[T+U]<<8|k[T+O])}}function v(A,L){if(A=A&&A.length,A==null)throw new TypeError("Invalid Buffer");if(A<L+8)throw new RangeError("Out of range")}function _(A){return(9<A?"":"0")+(0|A)}function S(A,L){return(c+(0|A)).substr(-L)}}()});var fy=Oe((nP,uy)=>{uy.exports=Qf;var ly=128,IS=127,RS=~IS,kS=Math.pow(2,31);function Qf(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw Qf.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=kS;)e[t++]=r&255|ly,r/=128;for(;r&RS;)e[t++]=r&255|ly,r>>>=7;return e[t]=r|0,Qf.bytes=t-n+1,e}});var py=Oe((oP,dy)=>{dy.exports=eh;var BS=128,hy=127;function eh(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a||o>49)throw eh.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&hy)<<o:(s&hy)*Math.pow(2,o),o+=7}while(s>=BS);return eh.bytes=i-n,t}});var gy=Oe((iP,my)=>{var TS=Math.pow(2,7),NS=Math.pow(2,14),CS=Math.pow(2,21),LS=Math.pow(2,28),OS=Math.pow(2,35),DS=Math.pow(2,42),PS=Math.pow(2,49),US=Math.pow(2,56),FS=Math.pow(2,63);my.exports=function(r){return r<TS?1:r<NS?2:r<CS?3:r<LS?4:r<OS?5:r<DS?6:r<PS?7:r<US?8:r<FS?9:10}});var Nc=Oe((sP,yy)=>{yy.exports={encode:fy(),decode:py(),encodingLength:gy()}});var Xy=Oe((SU,Yy)=>{"use strict";Yy.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let n=this._internalPositionFor(e,!1);if(t===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let o=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):o=!0,this._setInternalPos(n,e,t,o),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let t=this._internalPositionFor(e,!0);if(t!==-1)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let t=0;for(;t<this.length;)e(this.get(t),t,this),t++}map(e){let t=0,n=new Array(this.length);for(;t<this.length;)n[t]=e(this.get(t),t,this),t++;return n}reduce(e,t){let n=0,o=t;for(;n<this.length;){let i=this.get(n);o=e(o,i,n),n++}return o}find(e){let t=0,n,o;for(;t<this.length&&!n;)o=this.get(t),n=e(o),t++;return n?o:void 0}_internalPositionFor(e,t){let n=this._bytePosFor(e,t);if(n>=this._bitArrays.length)return-1;let o=this._bitArrays[n],i=e-n*7;if(!((o&1<<i)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(hA,0),c=~(4294967295<<i+1),l=jy(o&c);return a+l-1}_bytePosFor(e,t){let n=Math.floor(e/7),o=n+1;for(;!t&&this._bitArrays.length<o;)this._bitArrays.push(0);return n}_setBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]|=1<<e-t*7}_unsetBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]&=~(1<<e-t*7)}_setInternalPos(e,t,n,o){let i=this._data,s=[t,n];if(o)this._sortData(),i[e]=s;else{if(i.length)if(i[i.length-1][0]>=t)i.push(s);else if(i[0][0]<=t)i.unshift(s);else{let a=Math.round(i.length/2);this._data=i.slice(0,a).concat(s).concat(i.slice(a))}else this._data.push(s);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(dA),this._changedData=!1}bitField(){let e=[],t=8,n=0,o=0,i,s=this._bitArrays.slice();for(;s.length||n;){n===0&&(i=s.shift(),n=7);let c=Math.min(n,t),l=~(255<<c),f=i&l;o|=f<<8-t,i=i>>>c,n-=c,t-=c,(!t||!n&&!s.length)&&(e.push(o),o=0,t=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(pA)}};function hA(r,e){return r+jy(e)}function jy(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function dA(r,e){return r[0]-e[0]}function pA(r){return r[1]}});var Nw=Oe((S7,Tw)=>{"use strict";Tw.exports={RTLD_LAZY:1,RTLD_NOW:2,RTLD_GLOBAL:256,RTLD_LOCAL:0,RTLD_DEEPBIND:8,E2BIG:7,EACCES:13,EADDRINUSE:98,EADDRNOTAVAIL:99,EAFNOSUPPORT:97,EAGAIN:11,EALREADY:114,EBADF:9,EBADMSG:74,EBUSY:16,ECANCELED:125,ECHILD:10,ECONNABORTED:103,ECONNREFUSED:111,ECONNRESET:104,EDEADLK:35,EDESTADDRREQ:89,EDOM:33,EDQUOT:122,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:113,EIDRM:43,EILSEQ:84,EINPROGRESS:115,EINTR:4,EINVAL:22,EIO:5,EISCONN:106,EISDIR:21,ELOOP:40,EMFILE:24,EMLINK:31,EMSGSIZE:90,EMULTIHOP:72,ENAMETOOLONG:36,ENETDOWN:100,ENETRESET:102,ENETUNREACH:101,ENFILE:23,ENOBUFS:105,ENODATA:61,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:37,ENOLINK:67,ENOMEM:12,ENOMSG:42,ENOPROTOOPT:92,ENOSPC:28,ENOSR:63,ENOSTR:60,ENOSYS:38,ENOTCONN:107,ENOTDIR:20,ENOTEMPTY:39,ENOTSOCK:88,ENOTSUP:95,ENOTTY:25,ENXIO:6,EOPNOTSUPP:95,EOVERFLOW:75,EPERM:1,EPIPE:32,EPROTO:71,EPROTONOSUPPORT:93,EPROTOTYPE:91,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:116,ETIME:62,ETIMEDOUT:110,ETXTBSY:26,EWOULDBLOCK:11,EXDEV:18,PRIORITY_LOW:19,PRIORITY_BELOW_NORMAL:10,PRIORITY_NORMAL:0,PRIORITY_ABOVE_NORMAL:-7,PRIORITY_HIGH:-14,PRIORITY_HIGHEST:-20,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:17,SIGSTKFLT:16,SIGCONT:18,SIGSTOP:19,SIGTSTP:20,SIGTTIN:21,SIGTTOU:22,SIGURG:23,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:29,SIGPOLL:29,SIGPWR:30,SIGSYS:31,UV_FS_SYMLINK_DIR:1,UV_FS_SYMLINK_JUNCTION:2,O_RDONLY:0,O_WRONLY:1,O_RDWR:2,UV_DIRENT_UNKNOWN:0,UV_DIRENT_FILE:1,UV_DIRENT_DIR:2,UV_DIRENT_LINK:3,UV_DIRENT_FIFO:4,UV_DIRENT_SOCKET:5,UV_DIRENT_CHAR:6,UV_DIRENT_BLOCK:7,EXTENSIONLESS_FORMAT_JAVASCRIPT:0,EXTENSIONLESS_FORMAT_WASM:1,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:64,O_EXCL:128,UV_FS_O_FILEMAP:0,O_NOCTTY:256,O_TRUNC:512,O_APPEND:1024,O_DIRECTORY:65536,O_NOATIME:262144,O_NOFOLLOW:131072,O_SYNC:1052672,O_DSYNC:4096,O_DIRECT:16384,O_NONBLOCK:2048,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,F_OK:0,R_OK:4,W_OK:2,X_OK:1,UV_FS_COPYFILE_EXCL:1,COPYFILE_EXCL:1,UV_FS_COPYFILE_FICLONE:2,COPYFILE_FICLONE:2,UV_FS_COPYFILE_FICLONE_FORCE:4,COPYFILE_FICLONE_FORCE:4,OPENSSL_VERSION_NUMBER:805306576,SSL_OP_ALL:2147485776,SSL_OP_ALLOW_NO_DHE_KEX:1024,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_ENCRYPT_THEN_MAC:524288,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_RENEGOTIATION:1073741824,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:0,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_NO_TLSv1_3:536870912,SSL_OP_PRIORITIZE_CHACHA:2097152,SSL_OP_TLS_ROLLBACK_BUG:8388608,ENGINE_METHOD_RSA:1,ENGINE_METHOD_DSA:2,ENGINE_METHOD_DH:4,ENGINE_METHOD_RAND:8,ENGINE_METHOD_EC:2048,ENGINE_METHOD_CIPHERS:64,ENGINE_METHOD_DIGESTS:128,ENGINE_METHOD_PKEY_METHS:512,ENGINE_METHOD_PKEY_ASN1_METHS:1024,ENGINE_METHOD_ALL:65535,ENGINE_METHOD_NONE:0,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,RSA_PKCS1_PADDING:1,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,RSA_PSS_SALTLEN_DIGEST:-1,RSA_PSS_SALTLEN_MAX_SIGN:-2,RSA_PSS_SALTLEN_AUTO:-2,defaultCoreCipherList:"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA",TLS1_VERSION:769,TLS1_1_VERSION:770,TLS1_2_VERSION:771,TLS1_3_VERSION:772,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}});var C_={};Se(C_,{createVerifiedFetch:()=>Bh,verifiedFetch:()=>rl});var $o=Symbol.for("@libp2p/content-routing");var zo=Symbol.for("@libp2p/peer-id");function Mh(r){return r!=null&&!!r[zo]}var Ko=Symbol.for("@libp2p/peer-routing");var qt=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"},N=class extends Error{code;props;constructor(e,t,n){super(e),this.code=t,this.name=n?.name??"CodeError",this.props=n??{}}};var me=(r,...e)=>{try{[...e]}catch{}};var Mn=class extends EventTarget{#e=new Map;constructor(){super(),me(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:i})=>i!==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 ab(e,t))}},ol=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},ab=globalThis.CustomEvent??ol;function Vh(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Fr(...r){let e=[];for(let t of r)Vh(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Mr(...r){let e=[];for(let t of r)Vh(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 Ye(r){let e=new globalThis.AbortController;function t(){e.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let i of r){if(i?.aborted===!0){t();break}i?.addEventListener!=null&&i.addEventListener("abort",t)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}function fe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var as=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}},Vn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new as(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 as(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 il=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Gt(r={}){return cb(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 cb(r,e){e=e??{};let t=e.onEnd,n=new Vn,o,i,s,a=fe(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,g)=>{i=b=>{i=null,n.push(b);try{y(r(n))}catch(x){g(x)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=fe()})}},l=y=>i!=null?i(y):(n.push(y),o),f=y=>(n=new Vn,i!=null?i({error:y}):(n.push({error:y}),o)),u=y=>{if(s)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})},p=y=>s?o:(s=!0,y!=null?f(y):l({done:!0})),h=()=>(n=new Vn,p(),{done:!0}),m=y=>(p(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:u,end:p,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let b,x;g!=null&&(b=new Promise((E,v)=>{x=()=>{v(new il)},g.addEventListener("abort",x)}));try{await Promise.race([a.promise,b])}finally{x!=null&&g!=null&&g?.removeEventListener("abort",x)}}},t==null)return o;let d=o;return o={[Symbol.asyncIterator](){return this},next(){return d.next()},throw(y){return d.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return d.return(),t!=null&&(t(),t=void 0),{done:!0}},push:u,end(y){return d.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return d.readableLength},onEmpty:y=>d.onEmpty(y)},o}var sl=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 cs(r,e,t,n){let o=new sl(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{function a(){t?.removeEventListener("abort",f),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=u=>{try{if(n?.filter?.(u)===!1)return}catch(p){a(),s(p);return}a(),i(u)},l=u=>{a(),s(u.detail)},f=()=>{a(),s(o)};t?.addEventListener("abort",f),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var ls=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 Hh(r,e,t){if(e==null)return r;if(e.aborted)return Promise.reject(new ls(t?.errorMessage,t?.errorCode));let n,o=new ls(t?.errorMessage,t?.errorCode);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var us=class{deferred;signal;where;constructor(e,t){this.signal=t,this.deferred=fe(),this.where=e,this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new qt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function lb(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var fs=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=lb(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,me(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 qt),this.cleanup())}async join(e={}){let t=new us(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 Hh(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 lr=class extends Mn{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 fs(e,t),o=n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("error",{detail:i}),this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i});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 qt)}),this.clear()}async onEmpty(e){this.size!==0&&await cs(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await cs(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await cs(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=Gt({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},i=c=>{n(c.detail)},s=()=>{n()},a=()=>{n(new N("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",o),this.addEventListener("error",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("error",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var hs=class extends lr{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function ub(r){return r[Symbol.asyncIterator]!=null}function fb(r){if(ub(r))return(async()=>{for await(let e of r);})();for(let e of r);}var ur=fb;function rt(r=0){return new Uint8Array(r)}function nt(r=0){return new Uint8Array(r)}var hb=Math.pow(2,7),db=Math.pow(2,14),pb=Math.pow(2,21),al=Math.pow(2,28),cl=Math.pow(2,35),ll=Math.pow(2,42),ul=Math.pow(2,49),ae=128,ze=127;function ot(r){if(r<hb)return 1;if(r<db)return 2;if(r<pb)return 3;if(r<al)return 4;if(r<cl)return 5;if(r<ll)return 6;if(r<ul)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function fl(r,e,t=0){switch(ot(r)){case 8:e[t++]=r&255|ae,r/=128;case 7:e[t++]=r&255|ae,r/=128;case 6:e[t++]=r&255|ae,r/=128;case 5:e[t++]=r&255|ae,r/=128;case 4:e[t++]=r&255|ae,r>>>=7;case 3:e[t++]=r&255|ae,r>>>=7;case 2:e[t++]=r&255|ae,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function mb(r,e,t=0){switch(ot(r)){case 8:e.set(t++,r&255|ae),r/=128;case 7:e.set(t++,r&255|ae),r/=128;case 6:e.set(t++,r&255|ae),r/=128;case 5:e.set(t++,r&255|ae),r/=128;case 4:e.set(t++,r&255|ae),r>>>=7;case 3:e.set(t++,r&255|ae),r>>>=7;case 2:e.set(t++,r&255|ae),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function hl(r,e){let t=r[e],n=0;if(n+=t&ze,t<ae||(t=r[e+1],n+=(t&ze)<<7,t<ae)||(t=r[e+2],n+=(t&ze)<<14,t<ae)||(t=r[e+3],n+=(t&ze)<<21,t<ae)||(t=r[e+4],n+=(t&ze)*al,t<ae)||(t=r[e+5],n+=(t&ze)*cl,t<ae)||(t=r[e+6],n+=(t&ze)*ll,t<ae)||(t=r[e+7],n+=(t&ze)*ul,t<ae))return n;throw new RangeError("Could not decode varint")}function gb(r,e){let t=r.get(e),n=0;if(n+=t&ze,t<ae||(t=r.get(e+1),n+=(t&ze)<<7,t<ae)||(t=r.get(e+2),n+=(t&ze)<<14,t<ae)||(t=r.get(e+3),n+=(t&ze)<<21,t<ae)||(t=r.get(e+4),n+=(t&ze)*al,t<ae)||(t=r.get(e+5),n+=(t&ze)*cl,t<ae)||(t=r.get(e+6),n+=(t&ze)*ll,t<ae)||(t=r.get(e+7),n+=(t&ze)*ul,t<ae))return n;throw new RangeError("Could not decode varint")}function Hn(r,e,t=0){return e==null&&(e=nt(ot(r))),e instanceof Uint8Array?fl(r,e,t):mb(r,e,t)}function wn(r,e=0){return r instanceof Uint8Array?hl(r,e):gb(r,e)}function ue(r,e){e==null&&(e=r.reduce((o,i)=>o+i.length,0));let t=nt(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function ne(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 Kh=Symbol.for("@achingbrain/uint8arraylist");function zh(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 Wt(r){return!!r?.[Kh]}var fr=class r{bufs;length;[Kh]=!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(Wt(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(Wt(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=zh(this.bufs,e);return t.buf[t.index]}set(e,t){let n=zh(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(Wt(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 ue(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:ue(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),i=new r;return i.length=o,i.bufs=[...n],i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,f=t>a&&t<=c;if(l&&f){if(e===a&&t===c){n.push(s);break}let u=e-a;n.push(s.subarray(u,u+(t-e)));break}if(l){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(f){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Wt(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let u=0;u<i;u++)s[u]=-1;for(let u=0;u<o;u++)s[n[u]]=u;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,f;for(let u=t;u<=c;u+=f){f=0;for(let p=l;p>=0;p--){let h=this.get(u+p);if(n[p]!==h){f=Math.max(1,p-a[h]);break}}if(f===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=nt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=rt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=rt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=rt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=nt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=rt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=rt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=rt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=rt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=rt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!ne(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,i)=>o+i.byteLength,0)),n.length=t,n}};function wb(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 $n=wb;function bb(r){return r[Symbol.asyncIterator]!=null}function xb(r,e){let t=0;if(bb(r))return async function*(){for await(let c of r)yield e(c,t++)}();let n=$n(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=e(o,t++);if(typeof s.then=="function")return async function*(){yield await s;for await(let c of n)yield e(c,t++)}();let a=e;return function*(){yield s;for(let c of n)yield a(c,t++)}()}var Ke=xb;function Eb(r){return r[Symbol.asyncIterator]!=null}function vb(...r){let e=[];for(let t of r)Eb(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=Gt({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 Vr=vb;function jt(r,...e){if(r==null)throw new Error("Empty pipeline");if(dl(r)){let n=r;r=()=>n.source}else if(jh(r)||Wh(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&dl(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++)dl(t[n])&&(t[n]=Ab(t[n]));return Sb(...t)}var Sb=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},Wh=r=>r?.[Symbol.asyncIterator]!=null,jh=r=>r?.[Symbol.iterator]!=null,dl=r=>r==null?!1:r.sink!=null&&r.source!=null,Ab=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=Gt({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(Wh(i))o=async function*(){yield*i,n.end()};else if(jh(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Vr(n,o())}return r.source};function _b(r){return r[Symbol.asyncIterator]!=null}function Ib(r,e){return _b(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 ds=Ib;var V=class extends Event{constructor(e,t){super(e),this.detail=t}};var pl=new Float32Array([-0]),Hr=new Uint8Array(pl.buffer);function Yh(r,e,t){pl[0]=r,e[t]=Hr[0],e[t+1]=Hr[1],e[t+2]=Hr[2],e[t+3]=Hr[3]}function Xh(r,e){return Hr[0]=r[e],Hr[1]=r[e+1],Hr[2]=r[e+2],Hr[3]=r[e+3],pl[0]}var ml=new Float64Array([-0]),qe=new Uint8Array(ml.buffer);function Zh(r,e,t){ml[0]=r,e[t]=qe[0],e[t+1]=qe[1],e[t+2]=qe[2],e[t+3]=qe[3],e[t+4]=qe[4],e[t+5]=qe[5],e[t+6]=qe[6],e[t+7]=qe[7]}function Jh(r,e){return qe[0]=r[e],qe[1]=r[e+1],qe[2]=r[e+2],qe[3]=r[e+3],qe[4]=r[e+4],qe[5]=r[e+5],qe[6]=r[e+6],qe[7]=r[e+7],ml[0]}var Rb=BigInt(Number.MAX_SAFE_INTEGER),kb=BigInt(Number.MIN_SAFE_INTEGER),ft=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 bn;if(e<Rb&&e>kb)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>Qh&&(o=0n,++n>Qh&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return bn;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):bn}},bn=new ft(0,0);bn.toBigInt=function(){return 0n};bn.zzEncode=bn.zzDecode=function(){return this};bn.length=function(){return 1};var Qh=4294967296n;function ed(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 td(r,e,t){if(t-e<1)return"";let o,i=[],s=0,a;for(;e<t;)a=r[e++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function gl(r,e,t){let n=t,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function Ct(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function ps(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var yl=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,Ct(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 Ct(this,4);return ps(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Ct(this,4);return ps(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Ct(this,4);let e=Xh(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Ct(this,4);let e=Jh(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 Ct(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return td(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Ct(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Ct(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 ft(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 Ct(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 Ct(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 Ct(this,8);let e=ps(this.buf,this.pos+=4),t=ps(this.buf,this.pos+=4);return new ft(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=hl(this.buf,this.pos);return this.pos+=ot(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 wl(r){return new yl(r instanceof Uint8Array?r:r.subarray())}function St(r,e,t){let n=wl(r);return e.decode(n,void 0,t)}var Il={};Se(Il,{base10:()=>Ub});var zn={};Se(zn,{coerce:()=>Yt,empty:()=>nd,equals:()=>bl,fromHex:()=>Tb,fromString:()=>xl,isBinary:()=>Nb,toHex:()=>Bb,toString:()=>El});var nd=new Uint8Array(0);function Bb(r){return r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function Tb(r){let e=r.match(/../g);return e!=null?new Uint8Array(e.map(t=>parseInt(t,16))):nd}function bl(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 Yt(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 Nb(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function xl(r){return new TextEncoder().encode(r)}function El(r){return new TextDecoder().decode(r)}function Cb(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function u(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var d=0,y=0,g=0,b=m.length;g!==b&&m[g]===0;)g++,d++;for(var x=(b-g)*f+1>>>0,E=new Uint8Array(x);g!==b;){for(var v=m[g],_=0,S=x-1;(v!==0||_<y)&&S!==-1;S--,_++)v+=256*E[S]>>>0,E[S]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");y=_,g++}for(var A=x-y;A!==x&&E[A]===0;)A++;for(var L=c.repeat(d);A<x;++A)L+=r.charAt(E[A]);return L}function p(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var d=0;if(m[d]!==" "){for(var y=0,g=0;m[d]===c;)y++,d++;for(var b=(m.length-d)*l+1>>>0,x=new Uint8Array(b);m[d];){var E=t[m.charCodeAt(d)];if(E===255)return;for(var v=0,_=b-1;(E!==0||v<g)&&_!==-1;_--,v++)E+=a*x[_]>>>0,x[_]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");g=v,d++}if(m[d]!==" "){for(var S=b-g;S!==b&&x[S]===0;)S++;for(var A=new Uint8Array(y+(b-S)),L=y;S!==b;)A[L++]=x[S++];return A}}}function h(m){var d=p(m);if(d)return d;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:p,decode:h}}var Lb=Cb,Ob=Lb,od=Ob;var vl=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")}},Sl=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 id(this,e)}},Al=class{decoders;constructor(e){this.decoders=e}or(e){return id(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 id(r,e){return new Al({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var _l=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 vl(e,t,n),this.decoder=new Sl(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Kn({name:r,prefix:e,encode:t,decode:n}){return new _l(r,e,t,n)}function $r({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=od(t,r);return Kn({prefix:e,name:r,encode:n,decode:i=>Yt(o(i))})}function Db(r,e,t,n){let o={};for(let f=0;f<e.length;++f)o[e[f]]=f;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*t/8|0),a=0,c=0,l=0;for(let f=0;f<i;++f){let u=o[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|u,a+=t,a>=8&&(a-=8,s[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s}function Pb(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,i+=e[o&a>>s];if(s!==0&&(i+=e[o&a<<t-s]),n)for(;i.length*t&7;)i+="=";return i}function we({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return Kn({prefix:e,name:r,encode(o){return Pb(o,n,t)},decode(o){return Db(o,n,t,r)}})}var Ub=$r({prefix:"9",name:"base10",alphabet:"0123456789"});var Rl={};Se(Rl,{base16:()=>Fb,base16upper:()=>Mb});var Fb=we({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Mb=we({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var kl={};Se(kl,{base2:()=>Vb});var Vb=we({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Bl={};Se(Bl,{base256emoji:()=>qb});var sd=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}"),Hb=sd.reduce((r,e,t)=>(r[t]=e,r),[]),$b=sd.reduce((r,e,t)=>(r[e.codePointAt(0)]=t,r),[]);function zb(r){return r.reduce((e,t)=>(e+=Hb[t],e),"")}function Kb(r){let e=[];for(let t of r){let n=$b[t.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var qb=Kn({prefix:"\u{1F680}",name:"base256emoji",encode:zb,decode:Kb});var Tl={};Se(Tl,{base32:()=>Pe,base32hex:()=>jb,base32hexpad:()=>Xb,base32hexpadupper:()=>Zb,base32hexupper:()=>Yb,base32pad:()=>Gb,base32padupper:()=>Wb,base32upper:()=>ad,base32z:()=>Jb});var Pe=we({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ad=we({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Gb=we({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Wb=we({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),jb=we({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Yb=we({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Xb=we({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Zb=we({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Jb=we({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Nl={};Se(Nl,{base36:()=>zr,base36upper:()=>Qb});var zr=$r({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Qb=$r({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Cl={};Se(Cl,{base58btc:()=>ge,base58flickr:()=>ex});var ge=$r({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ex=$r({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ol={};Se(Ol,{base64:()=>it,base64pad:()=>tx,base64url:()=>Ll,base64urlpad:()=>rx});var it=we({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),tx=we({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ll=we({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),rx=we({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Dl={};Se(Dl,{base8:()=>nx});var nx=we({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Pl={};Se(Pl,{identity:()=>ox});var ox=Kn({prefix:"\0",name:"identity",encode:r=>El(r),decode:r=>xl(r)});var nR=new TextEncoder,ix=new TextDecoder;var Kr=512;function cd(r){return JSON.parse(ix.decode(r))}var ht=85;var Fl={};Se(Fl,{identity:()=>Be});var sx=fd,ld=128,ax=127,cx=~ax,lx=Math.pow(2,31);function fd(r,e,t){e=e||[],t=t||0;for(var n=t;r>=lx;)e[t++]=r&255|ld,r/=128;for(;r&cx;)e[t++]=r&255|ld,r>>>=7;return e[t]=r|0,fd.bytes=t-n+1,e}var ux=Ul,fx=128,ud=127;function Ul(r,n){var t=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Ul.bytes=0,new RangeError("Could not decode varint");s=r[i++],t+=o<28?(s&ud)<<o:(s&ud)*Math.pow(2,o),o+=7}while(s>=fx);return Ul.bytes=i-n,t}var hx=Math.pow(2,7),dx=Math.pow(2,14),px=Math.pow(2,21),mx=Math.pow(2,28),gx=Math.pow(2,35),yx=Math.pow(2,42),wx=Math.pow(2,49),bx=Math.pow(2,56),xx=Math.pow(2,63),Ex=function(r){return r<hx?1:r<dx?2:r<px?3:r<mx?4:r<gx?5:r<yx?6:r<wx?7:r<bx?8:r<xx?9:10},vx={encode:sx,decode:ux,encodingLength:Ex},Sx=vx,Go=Sx;function Wo(r,e=0){return[Go.decode(r,e),Go.decode.bytes]}function qn(r,e,t=0){return Go.encode(r,e,t),e}function Gn(r){return Go.encodingLength(r)}function Xt(r,e){let t=e.byteLength,n=Gn(r),o=n+Gn(t),i=new Uint8Array(o+t);return qn(r,i,0),qn(t,i,n),i.set(e,o),new Wn(r,t,e,i)}function Xe(r){let e=Yt(r),[t,n]=Wo(e),[o,i]=Wo(e.subarray(n)),s=e.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Wn(t,o,s,e)}function hd(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&bl(r.bytes,t.bytes)}}var Wn=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var dd=0,Ax="identity",pd=Yt;function _x(r){return Xt(dd,pd(r))}var Be={code:dd,name:Ax,encode:pd,digest:_x};var Hl={};Se(Hl,{sha256:()=>Re,sha512:()=>Vl});function xn({name:r,code:e,encode:t}){return new Ml(r,e,t)}var Ml=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?Xt(this.code,t):t.then(n=>Xt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function gd(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Re=xn({name:"sha2-256",code:18,encode:gd("SHA-256")}),Vl=xn({name:"sha2-512",code:19,encode:gd("SHA-512")});function yd(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Rx(t,$l(r),e??ge.encoder);default:return kx(t,$l(r),e??Pe.encoder)}}var wd=new WeakMap;function $l(r){let e=wd.get(r);if(e==null){let t=new Map;return wd.set(r,t),t}return e}var z=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!==jo)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Bx)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=Xt(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&&hd(e.multihash,n.multihash)}toString(e){return yd(this,e)}toJSON(){return{"/":yd(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:i,bytes:s}=t;return new r(n,o,i,s??bd(n,o,i.bytes))}else if(t[Tx]===!0){let{version:n,multihash:o,code:i}=t,s=Xe(o);return r.create(n,i,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==jo)throw new Error(`Version 0 CID must use dag-pb (code: ${jo}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=bd(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,jo,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=Yt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=o.subarray(t.multihashSize-t.digestSize),s=new Wn(t.multihashCode,t.digestSize,i,o);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[u,p]=Wo(e.subarray(t));return t+=p,u},o=n(),i=jo;if(o===18?(o=0,t=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=t,a=n(),c=n(),l=t+c,f=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[n,o]=Ix(e,t),i=r.decode(o);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return $l(i).set(n,e),i}};function Ix(r,e){switch(r[0]){case"Q":{let t=e??ge;return[ge.prefix,t.decode(`${ge.prefix}${r}`)]}case ge.prefix:{let t=e??ge;return[ge.prefix,t.decode(r)]}case Pe.prefix:{let t=e??Pe;return[Pe.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 Rx(r,e,t){let{prefix:n}=t;if(n!==ge.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return o}function kx(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let i=t.encode(r);return e.set(n,i),i}else return o}var jo=112,Bx=18;function bd(r,e,t){let n=Gn(r),o=n+Gn(e),i=new Uint8Array(o+t.byteLength);return qn(r,i,0),qn(e,i,n),i.set(t,o),i}var Tx=Symbol.for("@ipld/js-cid/CID");var qr={...Pl,...kl,...Dl,...Il,...Rl,...Tl,...Nl,...Cl,...Ol,...Bl},AR={...Hl,...Fl};function Ed(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var xd=Ed("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),zl=Ed("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=nt(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Nx={utf8:xd,"utf-8":xd,hex:qr.base16,latin1:zl,ascii:zl,binary:zl,...qr},ys=Nx;function P(r,e="utf8"){let t=ys[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Kl(r){let e=r??8192,t=e>>>1,n,o=e;return function(s){if(s<1||s>t)return nt(s);o+s>e&&(n=nt(e),o=0);let a=n.subarray(o,o+=s);return o&7&&(o=(o|7)+1),a}}var En=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function ql(){}var Wl=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Cx=Kl();function Lx(r){return globalThis.Buffer!=null?nt(r):Cx(r)}var Xo=class{len;head;tail;states;constructor(){this.len=0,this.head=new En(ql,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new En(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new jl((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(ws,10,ft.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ft.fromBigInt(e);return this._push(ws,t.length(),t)}uint64Number(e){return this._push(fl,ot(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=ft.fromBigInt(e).zzEncode();return this._push(ws,t.length(),t)}sint64Number(e){let t=ft.fromNumber(e).zzEncode();return this._push(ws,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Gl,1,e?1:0)}fixed32(e){return this._push(Yo,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ft.fromBigInt(e);return this._push(Yo,4,t.lo)._push(Yo,4,t.hi)}fixed64Number(e){let t=ft.fromNumber(e);return this._push(Yo,4,t.lo)._push(Yo,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(Yh,4,e)}double(e){return this._push(Zh,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(Gl,1,0):this.uint32(t)._push(Dx,t,e)}string(e){let t=ed(e);return t!==0?this.uint32(t)._push(gl,t,e):this._push(Gl,1,0)}fork(){return this.states=new Wl(this),this.head=this.tail=new En(ql,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 En(ql,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=Lx(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function Gl(r,e,t){e[t]=r&255}function Ox(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var jl=class extends En{next;constructor(e,t){super(Ox,e,t),this.next=void 0}};function ws(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 Yo(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 Dx(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(Xo.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Px,e,r),this},Xo.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Ux,e,r),this});function Px(r,e,t){e.set(r,t)}function Ux(r,e,t){r.length<40?gl(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(P(r),t)}function Yl(){return new Xo}function _t(r,e){let t=Yl();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var jn;(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"})(jn||(jn={}));function bs(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function vn(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(i,s){let a=e(i);s.int32(a)},n=function(i){let s=i.int32();return e(s)};return bs("enum",jn.VARINT,t,n)}function It(r,e){return bs("message",jn.LENGTH_DELIMITED,r,e)}var Fx=Symbol.for("nodejs.util.inspect.custom"),vd=Object.values(qr).map(r=>r.decoder).reduce((r,e)=>r.or(e),qr.identity.decoder),Sd=114,Xl=36,Zl=37,Zo=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()})`}[zo]=!0;toString(){return this.string==null&&(this.string=ge.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return z.createV1(Sd,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ne(this.multihash.bytes,e);if(typeof e=="string")return Lt(e).equals(this);if(e?.multihash?.bytes!=null)return ne(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Fx](){return`PeerId(${this.toString()})`}},Yn=class extends Zo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Xn=class extends Zo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}},Zn=class extends Zo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}};function Lt(r,e){if(e=e??vd,r.charAt(0)==="1"||r.charAt(0)==="Q"){let t=Xe(ge.decode(`z${r}`));return r.startsWith("12D")?new Xn({multihash:t}):r.startsWith("16U")?new Zn({multihash:t}):new Yn({multihash:t})}return Jo(vd.decode(r))}function Jo(r){try{let e=Xe(r);if(e.code===Be.code){if(e.digest.length===Xl)return new Xn({multihash:e});if(e.digest.length===Zl)return new Zn({multihash:e})}if(e.code===Re.code)return new Yn({multihash:e})}catch{return Mx(z.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Mx(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==Sd)throw new Error("Supplied PeerID CID is invalid");let e=r.multihash;if(e.code===Re.code)return new Yn({multihash:r.multihash});if(e.code===Be.code){if(e.digest.length===Xl)return new Xn({multihash:r.multihash});if(e.digest.length===Zl)return new Zn({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Ad(r,e){return r.length===Xl?new Xn({multihash:Xt(Be.code,r),privateKey:e}):r.length===Zl?new Zn({multihash:Xt(Be.code,r),privateKey:e}):new Yn({multihash:await Re.digest(r),publicKey:r,privateKey:e})}var Ze={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 pu={};Se(pu,{Ed25519PrivateKey:()=>In,Ed25519PublicKey:()=>ti,generateKeyPair:()=>Y1,generateKeyPairFromSeed:()=>Zd,unmarshalEd25519PrivateKey:()=>W1,unmarshalEd25519PublicKey:()=>j1});function Rt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Jn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Vx(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Qn(r,...e){if(!Vx(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 xs(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Jn(r.outputLen),Jn(r.blockLen)}function eo(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 _d(r,e){Qn(r);let t=e.outputLen;if(r.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}var Es=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var ro=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Ot=(r,e)=>r<<32-e|r>>>e;var gk=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Hx=async()=>{};async function Id(r,e,t){let n=Date.now();for(let o=0;o<r;o++){t(o);let i=Date.now()-n;i>=0&&i<e||(await Hx(),n+=i)}}function Jl(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Gr(r){return typeof r=="string"&&(r=Jl(r)),Qn(r),r}function vs(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Qn(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}var to=class{clone(){return this._cloneInto()}},$x={}.toString;function Rd(r,e){if(e!==void 0&&$x.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,e)}function Ss(r){let e=n=>r().update(Gr(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function no(r=32){if(Es&&typeof Es.getRandomValues=="function")return Es.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function zx(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(t>>o&i),a=Number(t&i),c=n?4:0,l=n?0:4;r.setUint32(e+c,s,n),r.setUint32(e+l,a,n)}var kd=(r,e,t)=>r&e^~r&t,Bd=(r,e,t)=>r&e^r&t^e&t,oo=class extends to{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=ro(this.buffer)}update(e){eo(this);let{view:t,buffer:n,blockLen:o}=this;e=Gr(e);let i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=ro(e);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){eo(this),_d(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;t[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>o-s&&(this.process(n,0),s=0);for(let u=s;u<o;u++)t[u]=0;zx(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=ro(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,f[u],i)}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:i,destroyed:s,pos:a}=this;return e.length=o,e.pos=a,e.finished=i,e.destroyed=s,o%t&&e.buffer.set(n),e}};var As=BigInt(4294967295),Ql=BigInt(32);function Td(r,e=!1){return e?{h:Number(r&As),l:Number(r>>Ql&As)}:{h:Number(r>>Ql&As)|0,l:Number(r&As)|0}}function Kx(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:i,l:s}=Td(r[o],e);[t[o],n[o]]=[i,s]}return[t,n]}var qx=(r,e)=>BigInt(r>>>0)<<Ql|BigInt(e>>>0),Gx=(r,e,t)=>r>>>t,Wx=(r,e,t)=>r<<32-t|e>>>t,jx=(r,e,t)=>r>>>t|e<<32-t,Yx=(r,e,t)=>r<<32-t|e>>>t,Xx=(r,e,t)=>r<<64-t|e>>>t-32,Zx=(r,e,t)=>r>>>t-32|e<<64-t,Jx=(r,e)=>e,Qx=(r,e)=>r,e1=(r,e,t)=>r<<t|e>>>32-t,t1=(r,e,t)=>e<<t|r>>>32-t,r1=(r,e,t)=>e<<t-32|r>>>64-t,n1=(r,e,t)=>r<<t-32|e>>>64-t;function o1(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var i1=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),s1=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,a1=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),c1=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,l1=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),u1=(r,e,t,n,o,i)=>e+t+n+o+i+(r/2**32|0)|0;var f1={fromBig:Td,split:Kx,toBig:qx,shrSH:Gx,shrSL:Wx,rotrSH:jx,rotrSL:Yx,rotrBH:Xx,rotrBL:Zx,rotr32H:Jx,rotr32L:Qx,rotlSH:e1,rotlSL:t1,rotlBH:r1,rotlBL:n1,add:o1,add3L:i1,add3H:s1,add4L:a1,add4H:c1,add5H:u1,add5L:l1},j=f1;var[h1,d1]=j.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))),Wr=new Uint32Array(80),jr=new Uint32Array(80),eu=class extends oo{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:i,Cl:s,Dh:a,Dl:c,Eh:l,El:f,Fh:u,Fl:p,Gh:h,Gl:m,Hh:d,Hl:y}=this;return[e,t,n,o,i,s,a,c,l,f,u,p,h,m,d,y]}set(e,t,n,o,i,s,a,c,l,f,u,p,h,m,d,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=f|0,this.Fh=u|0,this.Fl=p|0,this.Gh=h|0,this.Gl=m|0,this.Hh=d|0,this.Hl=y|0}process(e,t){for(let x=0;x<16;x++,t+=4)Wr[x]=e.getUint32(t),jr[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let E=Wr[x-15]|0,v=jr[x-15]|0,_=j.rotrSH(E,v,1)^j.rotrSH(E,v,8)^j.shrSH(E,v,7),S=j.rotrSL(E,v,1)^j.rotrSL(E,v,8)^j.shrSL(E,v,7),A=Wr[x-2]|0,L=jr[x-2]|0,U=j.rotrSH(A,L,19)^j.rotrBH(A,L,61)^j.shrSH(A,L,6),O=j.rotrSL(A,L,19)^j.rotrBL(A,L,61)^j.shrSL(A,L,6),$=j.add4L(S,O,jr[x-7],jr[x-16]),C=j.add4H($,_,U,Wr[x-7],Wr[x-16]);Wr[x]=C|0,jr[x]=$|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:f,Eh:u,El:p,Fh:h,Fl:m,Gh:d,Gl:y,Hh:g,Hl:b}=this;for(let x=0;x<80;x++){let E=j.rotrSH(u,p,14)^j.rotrSH(u,p,18)^j.rotrBH(u,p,41),v=j.rotrSL(u,p,14)^j.rotrSL(u,p,18)^j.rotrBL(u,p,41),_=u&h^~u&d,S=p&m^~p&y,A=j.add5L(b,v,S,d1[x],jr[x]),L=j.add5H(A,g,E,_,h1[x],Wr[x]),U=A|0,O=j.rotrSH(n,o,28)^j.rotrBH(n,o,34)^j.rotrBH(n,o,39),$=j.rotrSL(n,o,28)^j.rotrBL(n,o,34)^j.rotrBL(n,o,39),C=n&i^n&a^i&a,ee=o&s^o&c^s&c;g=d|0,b=y|0,d=h|0,y=m|0,h=u|0,m=p|0,{h:u,l:p}=j.add(l|0,f|0,L|0,U|0),l=a|0,f=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let k=j.add3L(U,$,ee);n=j.add3H(k,L,O,C),o=k|0}({h:n,l:o}=j.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=j.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=j.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:f}=j.add(this.Dh|0,this.Dl|0,l|0,f|0),{h:u,l:p}=j.add(this.Eh|0,this.El|0,u|0,p|0),{h,l:m}=j.add(this.Fh|0,this.Fl|0,h|0,m|0),{h:d,l:y}=j.add(this.Gh|0,this.Gl|0,d|0,y|0),{h:g,l:b}=j.add(this.Hh|0,this.Hl|0,g|0,b|0),this.set(n,o,i,s,a,c,l,f,u,p,h,m,d,y,g,b)}roundClean(){Wr.fill(0),jr.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 io=Ss(()=>new eu);var Is={};Se(Is,{abytes:()=>so,bitGet:()=>x1,bitLen:()=>b1,bitMask:()=>Qo,bitSet:()=>E1,bytesToHex:()=>dr,bytesToNumberBE:()=>pr,bytesToNumberLE:()=>Xr,concatBytes:()=>mr,createHmacDrbg:()=>nu,ensureBytes:()=>be,equalBytes:()=>y1,hexToBytes:()=>Sn,hexToNumber:()=>ru,isBytes:()=>Yr,numberToBytesBE:()=>Zr,numberToBytesLE:()=>An,numberToHexUnpadded:()=>Od,numberToVarBytesBE:()=>g1,utf8ToBytes:()=>w1,validateObject:()=>Zt});var Ld=BigInt(0),_s=BigInt(1),p1=BigInt(2);function Yr(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function so(r){if(!Yr(r))throw new Error("Uint8Array expected")}var m1=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function dr(r){so(r);let e="";for(let t=0;t<r.length;t++)e+=m1[r[t]];return e}function Od(r){let e=r.toString(16);return e.length&1?`0${e}`:e}function ru(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var hr={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Nd(r){if(r>=hr._0&&r<=hr._9)return r-hr._0;if(r>=hr._A&&r<=hr._F)return r-(hr._A-10);if(r>=hr._a&&r<=hr._f)return r-(hr._a-10)}function Sn(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,i=0;o<t;o++,i+=2){let s=Nd(r.charCodeAt(i)),a=Nd(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function pr(r){return ru(dr(r))}function Xr(r){return so(r),ru(dr(Uint8Array.from(r).reverse()))}function Zr(r,e){return Sn(r.toString(16).padStart(e*2,"0"))}function An(r,e){return Zr(r,e).reverse()}function g1(r){return Sn(Od(r))}function be(r,e,t){let n;if(typeof e=="string")try{n=Sn(e)}catch(i){throw new Error(`${r} must be valid hex string, got "${e}". Cause: ${i}`)}else if(Yr(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 mr(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];so(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let i=r[n];t.set(i,o),o+=i.length}return t}function y1(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 w1(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function b1(r){let e;for(e=0;r>Ld;r>>=_s,e+=1);return e}function x1(r,e){return r>>BigInt(e)&_s}function E1(r,e,t){return r|(t?_s:Ld)<<BigInt(e)}var Qo=r=>(p1<<BigInt(r-1))-_s,tu=r=>new Uint8Array(r),Cd=r=>Uint8Array.from(r);function nu(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=tu(r),o=tu(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...u)=>t(o,n,...u),c=(u=tu())=>{o=a(Cd([0]),u),n=a(),u.length!==0&&(o=a(Cd([1]),u),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let u=0,p=[];for(;u<e;){n=a();let h=n.slice();p.push(h),u+=n.length}return mr(...p)};return(u,p)=>{s(),c(u);let h;for(;!(h=p(l()));)c();return s(),h}}var v1={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"||Yr(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 Zt(r,e,t={}){let n=(o,i,s)=>{let a=v1[i];if(typeof a!="function")throw new Error(`Invalid validator "${i}", expected function`);let c=r[o];if(!(s&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${i}`)};for(let[o,i]of Object.entries(e))n(o,i,!1);for(let[o,i]of Object.entries(t))n(o,i,!0);return r}var ke=BigInt(0),he=BigInt(1),_n=BigInt(2),S1=BigInt(3),ou=BigInt(4),Dd=BigInt(5),Pd=BigInt(8),A1=BigInt(9),_1=BigInt(16);function ce(r,e){let t=r%e;return t>=ke?t:e+t}function I1(r,e,t){if(t<=ke||e<ke)throw new Error("Expected power/modulo > 0");if(t===he)return ke;let n=he;for(;e>ke;)e&he&&(n=n*r%t),r=r*r%t,e>>=he;return n}function de(r,e,t){let n=r;for(;e-- >ke;)n*=n,n%=t;return n}function Rs(r,e){if(r===ke||e<=ke)throw new Error(`invert: expected positive integers, got n=${r} mod=${e}`);let t=ce(r,e),n=e,o=ke,i=he,s=he,a=ke;for(;t!==ke;){let l=n/t,f=n%t,u=o-s*l,p=i-a*l;n=t,t=f,o=s,i=a,s=u,a=p}if(n!==he)throw new Error("invert: does not exist");return ce(o,e)}function R1(r){let e=(r-he)/_n,t,n,o;for(t=r-he,n=0;t%_n===ke;t/=_n,n++);for(o=_n;o<r&&I1(o,e,r)!==r-he;o++);if(n===1){let s=(r+he)/ou;return function(c,l){let f=c.pow(l,s);if(!c.eql(c.sqr(f),l))throw new Error("Cannot find square root");return f}}let i=(t+he)/_n;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,f=a.pow(a.mul(a.ONE,o),t),u=a.pow(c,i),p=a.pow(c,t);for(;!a.eql(p,a.ONE);){if(a.eql(p,a.ZERO))return a.ZERO;let h=1;for(let d=a.sqr(p);h<l&&!a.eql(d,a.ONE);h++)d=a.sqr(d);let m=a.pow(f,he<<BigInt(l-h-1));f=a.sqr(m),u=a.mul(u,m),p=a.mul(p,f),l=h}return u}}function k1(r){if(r%ou===S1){let e=(r+he)/ou;return function(n,o){let i=n.pow(o,e);if(!n.eql(n.sqr(i),o))throw new Error("Cannot find square root");return i}}if(r%Pd===Dd){let e=(r-Dd)/Pd;return function(n,o){let i=n.mul(o,_n),s=n.pow(i,e),a=n.mul(o,s),c=n.mul(n.mul(a,_n),s),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%_1,R1(r)}var Ud=(r,e)=>(ce(r,e)&he)===he,B1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function iu(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=B1.reduce((n,o)=>(n[o]="function",n),e);return Zt(r,t)}function T1(r,e,t){if(t<ke)throw new Error("Expected power > 0");if(t===ke)return r.ONE;if(t===he)return e;let n=r.ONE,o=e;for(;t>ke;)t&he&&(n=r.mul(n,o)),o=r.sqr(o),t>>=he;return n}function N1(r,e){let t=new Array(e.length),n=e.reduce((i,s,a)=>r.is0(s)?i:(t[a]=i,r.mul(i,s)),r.ONE),o=r.inv(n);return e.reduceRight((i,s,a)=>r.is0(s)?i:(t[a]=r.mul(i,t[a]),r.mul(i,s)),o),t}function su(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function ks(r,e,t=!1,n={}){if(r<=ke)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:i}=su(r,e);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=k1(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:i,MASK:Qo(o),ZERO:ke,ONE:he,create:c=>ce(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return ke<=c&&c<r},is0:c=>c===ke,isOdd:c=>(c&he)===he,neg:c=>ce(-c,r),eql:(c,l)=>c===l,sqr:c=>ce(c*c,r),add:(c,l)=>ce(c+l,r),sub:(c,l)=>ce(c-l,r),mul:(c,l)=>ce(c*l,r),pow:(c,l)=>T1(a,c,l),div:(c,l)=>ce(c*Rs(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Rs(c,r),sqrt:n.sqrt||(c=>s(a,c)),invertBatch:c=>N1(a,c),cmov:(c,l,f)=>f?l:c,toBytes:c=>t?An(c,i):Zr(c,i),fromBytes:c=>{if(c.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${c.length}`);return t?Xr(c):pr(c)}});return Object.freeze(a)}function Fd(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 Md(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 au(r){let e=Md(r);return e+Math.ceil(e/2)}function Vd(r,e,t=!1){let n=r.length,o=Md(e),i=au(e);if(n<16||n<i||n>1024)throw new Error(`expected ${i}-1024 bytes of input, got ${n}`);let s=t?pr(r):Xr(r),a=ce(s,e-he)+he;return t?An(a,o):Zr(a,o)}var L1=BigInt(0),cu=BigInt(1);function Bs(r,e){let t=(o,i)=>{let s=i.negate();return o?s:i},n=o=>{let i=Math.ceil(e/o)+1,s=2**(o-1);return{windows:i,windowSize:s}};return{constTimeNegate:t,unsafeLadder(o,i){let s=r.ZERO,a=o;for(;i>L1;)i&cu&&(s=s.add(a)),a=a.double(),i>>=cu;return s},precomputeWindow(o,i){let{windows:s,windowSize:a}=n(i),c=[],l=o,f=l;for(let u=0;u<s;u++){f=l,c.push(f);for(let p=1;p<a;p++)f=f.add(l),c.push(f);l=f.double()}return c},wNAF(o,i,s){let{windows:a,windowSize:c}=n(o),l=r.ZERO,f=r.BASE,u=BigInt(2**o-1),p=2**o,h=BigInt(o);for(let m=0;m<a;m++){let d=m*c,y=Number(s&u);s>>=h,y>c&&(y-=p,s+=cu);let g=d,b=d+Math.abs(y)-1,x=m%2!==0,E=y<0;y===0?f=f.add(t(x,i[g])):l=l.add(t(E,i[b]))}return{p:l,f}},wNAFCached(o,i,s,a){let c=o._WINDOW_SIZE||1,l=i.get(o);return l||(l=this.precomputeWindow(o,c),c!==1&&i.set(o,a(l))),this.wNAF(c,l,s)}}}function ei(r){return iu(r.Fp),Zt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...su(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Dt=BigInt(0),dt=BigInt(1),Ts=BigInt(2),O1=BigInt(8),D1={zip215:!0};function P1(r){let e=ei(r);return Zt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Ns(r){let e=P1(r),{Fp:t,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=e,l=Ts<<BigInt(a*8)-dt,f=t.create,u=e.uvRatio||((B,I)=>{try{return{isValid:!0,value:t.sqrt(B*t.inv(I))}}catch{return{isValid:!1,value:Dt}}}),p=e.adjustScalarBytes||(B=>B),h=e.domain||((B,I,M)=>{if(I.length||M)throw new Error("Contexts/pre-hash are not supported");return B}),m=B=>typeof B=="bigint"&&Dt<B,d=(B,I)=>m(B)&&m(I)&&B<I,y=B=>B===Dt||d(B,l);function g(B,I){if(d(B,I))return B;throw new Error(`Expected valid scalar < ${I}, got ${typeof B} ${B}`)}function b(B){return B===Dt?B:g(B,n)}let x=new Map;function E(B){if(!(B instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(I,M,K,W){if(this.ex=I,this.ey=M,this.ez=K,this.et=W,!y(I))throw new Error("x required");if(!y(M))throw new Error("y required");if(!y(K))throw new Error("z required");if(!y(W))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(I){if(I instanceof v)throw new Error("extended point not allowed");let{x:M,y:K}=I||{};if(!y(M)||!y(K))throw new Error("invalid affine point");return new v(M,K,dt,f(M*K))}static normalizeZ(I){let M=t.invertBatch(I.map(K=>K.ez));return I.map((K,W)=>K.toAffine(M[W])).map(v.fromAffine)}_setWindowSize(I){this._WINDOW_SIZE=I,x.delete(this)}assertValidity(){let{a:I,d:M}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:K,ey:W,ez:X,et:Z}=this,ie=f(K*K),Q=f(W*W),te=f(X*X),ve=f(te*te),ye=f(ie*I),Ce=f(te*f(ye+Q)),Le=f(ve+f(M*f(ie*Q)));if(Ce!==Le)throw new Error("bad point: equation left != right (1)");let Ie=f(K*W),$e=f(X*Z);if(Ie!==$e)throw new Error("bad point: equation left != right (2)")}equals(I){E(I);let{ex:M,ey:K,ez:W}=this,{ex:X,ey:Z,ez:ie}=I,Q=f(M*ie),te=f(X*W),ve=f(K*ie),ye=f(Z*W);return Q===te&&ve===ye}is0(){return this.equals(v.ZERO)}negate(){return new v(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:I}=e,{ex:M,ey:K,ez:W}=this,X=f(M*M),Z=f(K*K),ie=f(Ts*f(W*W)),Q=f(I*X),te=M+K,ve=f(f(te*te)-X-Z),ye=Q+Z,Ce=ye-ie,Le=Q-Z,Ie=f(ve*Ce),$e=f(ye*Le),cr=f(ve*Le),yn=f(Ce*ye);return new v(Ie,$e,yn,cr)}add(I){E(I);let{a:M,d:K}=e,{ex:W,ey:X,ez:Z,et:ie}=this,{ex:Q,ey:te,ez:ve,et:ye}=I;if(M===BigInt(-1)){let Nh=f((X-W)*(te+Q)),Ch=f((X+W)*(te-Q)),nl=f(Ch-Nh);if(nl===Dt)return this.double();let Lh=f(Z*Ts*ye),Oh=f(ie*Ts*ve),Dh=Oh+Lh,Ph=Ch+Nh,Uh=Oh-Lh,Zw=f(Dh*nl),Jw=f(Ph*Uh),Qw=f(Dh*Uh),eb=f(nl*Ph);return new v(Zw,Jw,eb,Qw)}let Ce=f(W*Q),Le=f(X*te),Ie=f(ie*K*ye),$e=f(Z*ve),cr=f((W+X)*(Q+te)-Ce-Le),yn=$e-Ie,Ho=$e+Ie,Th=f(Le-M*Ce),Ww=f(cr*yn),jw=f(Ho*Th),Yw=f(cr*Th),Xw=f(yn*Ho);return new v(Ww,jw,Xw,Yw)}subtract(I){return this.add(I.negate())}wNAF(I){return A.wNAFCached(this,x,I,v.normalizeZ)}multiply(I){let{p:M,f:K}=this.wNAF(g(I,n));return v.normalizeZ([M,K])[0]}multiplyUnsafe(I){let M=b(I);return M===Dt?S:this.equals(S)||M===dt?this:this.equals(_)?this.wNAF(M).p:A.unsafeLadder(this,M)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return A.unsafeLadder(this,n).is0()}toAffine(I){let{ex:M,ey:K,ez:W}=this,X=this.is0();I==null&&(I=X?O1:t.inv(W));let Z=f(M*I),ie=f(K*I),Q=f(W*I);if(X)return{x:Dt,y:dt};if(Q!==dt)throw new Error("invZ was invalid");return{x:Z,y:ie}}clearCofactor(){let{h:I}=e;return I===dt?this:this.multiplyUnsafe(I)}static fromHex(I,M=!1){let{d:K,a:W}=e,X=t.BYTES;I=be("pointHex",I,X);let Z=I.slice(),ie=I[X-1];Z[X-1]=ie&-129;let Q=Xr(Z);Q===Dt||(M?g(Q,l):g(Q,t.ORDER));let te=f(Q*Q),ve=f(te-dt),ye=f(K*te-W),{isValid:Ce,value:Le}=u(ve,ye);if(!Ce)throw new Error("Point.fromHex: invalid y coordinate");let Ie=(Le&dt)===dt,$e=(ie&128)!==0;if(!M&&Le===Dt&&$e)throw new Error("Point.fromHex: x=0 and x_0=1");return $e!==Ie&&(Le=f(-Le)),v.fromAffine({x:Le,y:Q})}static fromPrivateKey(I){return O(I).point}toRawBytes(){let{x:I,y:M}=this.toAffine(),K=An(M,t.BYTES);return K[K.length-1]|=I&dt?128:0,K}toHex(){return dr(this.toRawBytes())}}v.BASE=new v(e.Gx,e.Gy,dt,f(e.Gx*e.Gy)),v.ZERO=new v(Dt,dt,dt,Dt);let{BASE:_,ZERO:S}=v,A=Bs(v,a*8);function L(B){return ce(B,n)}function U(B){return L(Xr(B))}function O(B){let I=a;B=be("private key",B,I);let M=be("hashed private key",i(B),2*I),K=p(M.slice(0,I)),W=M.slice(I,2*I),X=U(K),Z=_.multiply(X),ie=Z.toRawBytes();return{head:K,prefix:W,scalar:X,point:Z,pointBytes:ie}}function $(B){return O(B).pointBytes}function C(B=new Uint8Array,...I){let M=mr(...I);return U(i(h(M,be("context",B),!!o)))}function ee(B,I,M={}){B=be("message",B),o&&(B=o(B));let{prefix:K,scalar:W,pointBytes:X}=O(I),Z=C(M.context,K,B),ie=_.multiply(Z).toRawBytes(),Q=C(M.context,ie,X,B),te=L(Z+Q*W);b(te);let ve=mr(ie,An(te,t.BYTES));return be("result",ve,a*2)}let k=D1;function T(B,I,M,K=k){let{context:W,zip215:X}=K,Z=t.BYTES;B=be("signature",B,2*Z),I=be("message",I),o&&(I=o(I));let ie=Xr(B.slice(Z,2*Z)),Q,te,ve;try{Q=v.fromHex(M,X),te=v.fromHex(B.slice(0,Z),X),ve=_.multiplyUnsafe(ie)}catch{return!1}if(!X&&Q.isSmallOrder())return!1;let ye=C(W,te.toRawBytes(),Q.toRawBytes(),I);return te.add(Q.multiplyUnsafe(ye)).subtract(ve).clearCofactor().equals(v.ZERO)}return _._setWindowSize(8),{CURVE:e,getPublicKey:$,sign:ee,verify:T,ExtendedPoint:v,utils:{getExtendedPublicKey:O,randomPrivateKey:()=>s(t.BYTES),precompute(B=8,I=v.BASE){return I._setWindowSize(B),I.multiply(BigInt(3)),I}}}}var uu=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Hd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Fk=BigInt(0),U1=BigInt(1),lu=BigInt(2),F1=BigInt(5),$d=BigInt(10),M1=BigInt(20),V1=BigInt(40),zd=BigInt(80);function H1(r){let e=uu,n=r*r%e*r%e,o=de(n,lu,e)*n%e,i=de(o,U1,e)*r%e,s=de(i,F1,e)*i%e,a=de(s,$d,e)*s%e,c=de(a,M1,e)*a%e,l=de(c,V1,e)*c%e,f=de(l,zd,e)*l%e,u=de(f,zd,e)*l%e,p=de(u,$d,e)*s%e;return{pow_p_5_8:de(p,lu,e)*r%e,b2:n}}function $1(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function z1(r,e){let t=uu,n=ce(e*e*e,t),o=ce(n*n*e,t),i=H1(r*o).pow_p_5_8,s=ce(r*n*i,t),a=ce(e*s*s,t),c=s,l=ce(s*Hd,t),f=a===r,u=a===ce(-r,t),p=a===ce(-r*Hd,t);return f&&(s=c),(u||p)&&(s=l),Ud(s,t)&&(s=ce(-s,t)),{isValid:f||u,value:s}}var gr=ks(uu,void 0,!0),fu={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:gr,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:io,randomBytes:no,adjustScalarBytes:$1,uvRatio:z1},ao=Ns(fu);function Kd(r,e,t){if(e.length>255)throw new Error("Context is too big");return vs(Jl("SigEd25519 no Ed25519 collisions"),new Uint8Array([t?1:0,e.length]),e,r)}var Mk=Ns({...fu,domain:Kd}),Vk=Ns({...fu,domain:Kd,prehash:io});var K1=(gr.ORDER+BigInt(3))/BigInt(8),Hk=gr.pow(lu,K1),$k=gr.sqrt(gr.neg(gr.ONE)),zk=(gr.ORDER-BigInt(5))/BigInt(8),Kk=BigInt(486662);var qk=Fd(gr,gr.neg(BigInt(486664)));var Gk=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Wk=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),jk=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Yk=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var Xk=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var co=32,yr=64,Cs=32;function qd(){let r=ao.utils.randomPrivateKey(),e=ao.getPublicKey(r);return{privateKey:Yd(r,e),publicKey:e}}function Gd(r){if(r.length!==Cs)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=ao.getPublicKey(e);return{privateKey:Yd(e,t),publicKey:t}}function Wd(r,e){let t=r.subarray(0,Cs);return ao.sign(e instanceof Uint8Array?e:e.subarray(),t)}function jd(r,e,t){return ao.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}function Yd(r,e){let t=new Uint8Array(yr);for(let n=0;n<Cs;n++)t[n]=r[n],t[Cs+n]=e[n];return t}var hu={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function Xd(r){let e=r?.algorithm??"AES-GCM",t=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",i=r?.saltLength??16,s=r?.iterations??32767,a=Ze.get();t*=8;async function c(u,p){let h=a.getRandomValues(new Uint8Array(i)),m=a.getRandomValues(new Uint8Array(n)),d={name:e,iv:m};typeof p=="string"&&(p=P(p));let y;if(p.length===0){y=await a.subtle.importKey("jwk",hu,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},x=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["encrypt"])}catch{y=await a.subtle.importKey("jwk",hu,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},x=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(b,x,{name:e,length:t},!0,["encrypt"])}let g=await a.subtle.encrypt(d,y,u);return ue([h,d.iv,new Uint8Array(g)])}async function l(u,p){let h=u.subarray(0,i),m=u.subarray(i,i+n),d=u.subarray(i+n),y={name:e,iv:m};typeof p=="string"&&(p=P(p));let g;if(p.length===0)try{let x={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},E=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,E,{name:e,length:t},!0,["decrypt"])}catch{g=await a.subtle.importKey("jwk",hu,{name:"AES-GCM"},!0,["decrypt"])}else{let x={name:"PBKDF2",salt:h,iterations:s,hash:{name:o}},E=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,E,{name:e,length:t},!0,["decrypt"])}let b=await a.subtle.decrypt(y,g,d);return new Uint8Array(b)}return{encrypt:c,decrypt:l}}async function lo(r,e){let n=await Xd().encrypt(r,e);return it.encode(n)}var pe;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(pe||(pe={}));var du;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(du||(du={}));(function(r){r.codec=()=>vn(du)})(pe||(pe={}));var Jt;(function(r){let e;r.codec=()=>(e==null&&(e=It((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),pe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.Type=pe.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>_t(t,r.codec()),r.decode=t=>St(t,r.codec())})(Jt||(Jt={}));var Qt;(function(r){let e;r.codec=()=>(e==null&&(e=It((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),pe.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.Type=pe.codec().decode(t);break;case 2:o.Data=t.bytes();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>_t(t,r.codec()),r.decode=t=>St(t,r.codec())})(Qt||(Qt={}));var ti=class{_key;constructor(e){this._key=uo(e,co)}verify(e,t){return jd(this._key,t,e)}marshal(){return this._key}get bytes(){return Jt.encode({Type:pe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Rt(e)?e.then(({bytes:t})=>t):e.bytes}},In=class{_key;_publicKey;constructor(e,t){this._key=uo(e,yr),this._publicKey=uo(t,co)}sign(e){return Wd(this._key,e)}get public(){return new ti(this._publicKey)}marshal(){return this._key}get bytes(){return Qt.encode({Type:pe.Ed25519,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return Rt(e)?{bytes:t}=await e:t=e.bytes,t}async id(){let e=Be.digest(this.public.bytes);return ge.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if(t==="libp2p-key")return lo(this.bytes,e);throw new N(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function W1(r){if(r.length>yr){r=uo(r,yr+co);let n=r.subarray(0,yr),o=r.subarray(yr,r.length);return new In(n,o)}r=uo(r,yr);let e=r.subarray(0,yr),t=r.subarray(co);return new In(e,t)}function j1(r){return r=uo(r,co),new ti(r)}async function Y1(){let{privateKey:r,publicKey:e}=qd();return new In(r,e)}async function Zd(r){let{privateKey:e,publicKey:t}=Gd(r);return new In(e,t)}function uo(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new N(`Key must be a Uint8Array of length ${e}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}function G(r,e="utf8"){let t=ys[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Au={};Se(Au,{MAX_RSA_KEY_SIZE:()=>di,RsaPrivateKey:()=>go,RsaPublicKey:()=>hi,fromJwk:()=>vE,generateKeyPair:()=>SE,unmarshalRsaPrivateKey:()=>vu,unmarshalRsaPublicKey:()=>EE});function er(r){if(isNaN(r)||r<=0)throw new N("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return no(r)}var tn={};Se(tn,{exportToPem:()=>gE,importFromPem:()=>yE,jwkToPkcs1:()=>hE,jwkToPkix:()=>pE,pkcs1ToJwk:()=>fE,pkixToJwk:()=>dE});var Os=class extends to{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,xs(e);let n=Gr(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?e.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(e){return eo(this),this.iHash.update(e),this}digestInto(e){eo(this),Qn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ri=(r,e,t)=>new Os(r,e).update(t).digest();ri.create=(r,e)=>new Os(r,e);function X1(r,e,t,n){xs(r);let o=Rd({dkLen:32,asyncTick:10},n),{c:i,dkLen:s,asyncTick:a}=o;if(Jn(i),Jn(s),Jn(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Gr(e),l=Gr(t),f=new Uint8Array(s),u=ri.create(r,c),p=u._cloneInto().update(l);return{c:i,dkLen:s,asyncTick:a,DK:f,PRF:u,PRFSalt:p}}function Z1(r,e,t,n,o){return r.destroy(),e.destroy(),n&&n.destroy(),o.fill(0),t}async function mu(r,e,t,n){let{c:o,dkLen:i,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=X1(r,e,t,n),f,u=new Uint8Array(4),p=ro(u),h=new Uint8Array(c.outputLen);for(let m=1,d=0;d<i;m++,d+=c.outputLen){let y=a.subarray(d,d+c.outputLen);p.setInt32(0,m,!1),(f=l._cloneInto(f)).update(u).digestInto(h),y.set(h.subarray(0,y.length)),await Id(o-1,s,()=>{c._cloneInto(f).update(h).digestInto(h);for(let g=0;g<y.length;g++)y[g]^=h[g]})}return Z1(c,l,a,f,h)}var J=re(Jd());function Rn(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 Jr(r,e,t=-1){let n=t,o=r,i=0,s=Math.pow(2,e);for(let a=1;a<8;a++){if(r<s){let c;if(n<0)c=new ArrayBuffer(a),i=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),i=n}let l=new Uint8Array(c);for(let f=a-1;f>=0;f--){let u=Math.pow(2,f*e);l[i-f-1]=Math.floor(o/u),o-=l[i-f-1]*u}return c}s*=Math.pow(2,e)}return new ArrayBuffer(0)}function Us(...r){let e=0,t=0;for(let i of r)e+=i.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let i of r)o.set(i,t),t+=i.length;return o}function yu(){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=Rn(t,8),o=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)i[a]=r[a];return i[0]&=127,Rn(i,8)-n}function Qd(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let s=t-e,a=Jr(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Jr(e,8,n),i=new Uint8Array(o);if(i[0]&128){let s=o.slice(0),a=new Uint8Array(s);o=new ArrayBuffer(o.byteLength+1),i=new Uint8Array(o);for(let c=0;c<s.byteLength;c++)i[c+1]=a[c];i[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function ep(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 st(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]="0";return o.join("").concat(t)}var _B=Math.log(2);function Fs(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function wu(r){let e=0,t=0;for(let o=0;o<r.length;o++){let i=r[o];e+=i.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let i=r[o];n.set(new Uint8Array(i),t),t+=i.byteLength}return n.buffer}function vr(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 oi=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return wu(this.items)}},ni=[new Uint8Array([1])],tp="0123456789";var po="",Ut=new ArrayBuffer(0),bu=new Uint8Array(0),ii="EndOfContent",np="OCTET STRING",op="BIT STRING";function Sr(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let i=n[0]||{};this.isHexOnly=(o=i.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=i.valueHex?J.BufferSourceConverter.toUint8Array(i.valueHex):bu}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,i){let s=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!vr(this,s,o,i))return-1;let a=o+i;return this.valueHexView=s.subarray(o,a),this.valueHexView.length?(this.blockLength=i,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",Ut)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:J.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var br=class{constructor({blockLength:e=0,error:t=po,warnings:n=[],valueBeforeDecode:o=bu}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=J.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:J.Convert.ToHex(this.valueBeforeDecodeView)}}};br.NAME="baseBlock";var Ge=class extends br{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'")}};Ge.NAME="valueBlock";var Ms=class extends Sr(br){constructor({idBlock:e={}}={}){var t,n,o,i;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?J.BufferSourceConverter.toUint8Array(e.valueHex):bu,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(i=e.isConstructed)!==null&&i!==void 0?i:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",Ut}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let i=this.tagNumber;i&=31,t|=i,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=Jr(this.tagNumber,7),i=new Uint8Array(o),s=o.byteLength,a=new Uint8Array(s+1);if(a[0]=t|31,!e){for(let c=0;c<s-1;c++)a[c+1]=i[c]|128;a[s]=i[s-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let i=0;i<o.length-1;i++)n[i+1]=o[i]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=J.BufferSourceConverter.toUint8Array(e);if(!vr(this,o,t,n))return-1;let i=o.subarray(t,t+n);if(i.length===0)return this.error="Zero buffer length",-1;switch(i[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(i[0]&32)===32,this.isHexOnly=!1;let a=i[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),f=255;for(;i[c]&128;){if(l[c-1]=i[c]&127,c++,c>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c===f){f+=255;let p=new Uint8Array(f);for(let h=0;h<l.length;h++)p[h]=l[h];l=this.valueHexView=new Uint8Array(f)}}this.blockLength=c+1,l[c-1]=i[c]&127;let u=new Uint8Array(c);for(let p=0;p<c;p++)u[p]=l[p];l=this.valueHexView=new Uint8Array(c),l.set(u),this.blockLength<=9?this.tagNumber=Rn(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}}};Ms.NAME="identificationBlock";var Vs=class extends br{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=J.BufferSourceConverter.toUint8Array(e);if(!vr(this,o,t,n))return-1;let i=o.subarray(t,t+n);if(i.length===0)return this.error="Zero buffer length",-1;if(i[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=i[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,t+this.blockLength;let s=i[0]&127;if(s>8)return this.error="Too big integer",-1;if(s+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+s);return c[s-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Rn(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=s+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=Jr(this.length,8);if(o.byteLength>127)return this.error="Too big length",Ut;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let i=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let s=0;s<o.byteLength;s++)n[s+1]=i[s];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Vs.NAME="lengthBlock";var F={},Ue=class extends br{constructor({name:e=po,optional:t=!1,primitiveSchema:n,...o}={},i){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new Ms(o),this.lenBlock=new Vs(o),this.valueBlock=i?new i(o):new Ge(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 oi;t||ip(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;let s=this.lenBlock.toBER(e);n.write(s),n.write(i)}return t?Ut:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():J.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${J.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 ep(t,n)}};Ue.NAME="BaseBlock";function ip(r){if(r instanceof F.Constructed)for(let e of r.valueBlock.value)ip(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Hs=class extends Ue{constructor({value:e=po,...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}'`}};Hs.NAME="BaseStringBlock";var $s=class extends Sr(Ge){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};$s.NAME="PrimitiveValueBlock";var sp,zs=class extends Ue{constructor(e={}){super(e,$s),this.idBlock.isConstructed=!1}};sp=zs;F.Primitive=sp;zs.NAME="PRIMITIVE";function sE(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 va(r,e=0,t=r.length){let n=e,o=new Ue({},Ge),i=new br;if(!vr(i,r,e,t))return o.error=i.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=Ue;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=F.EndOfContent;break;case 1:c=F.Boolean;break;case 2:c=F.Integer;break;case 3:c=F.BitString;break;case 4:c=F.OctetString;break;case 5:c=F.Null;break;case 6:c=F.ObjectIdentifier;break;case 10:c=F.Enumerated;break;case 12:c=F.Utf8String;break;case 13:c=F.RelativeObjectIdentifier;break;case 14:c=F.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=F.Sequence;break;case 17:c=F.Set;break;case 18:c=F.NumericString;break;case 19:c=F.PrintableString;break;case 20:c=F.TeletexString;break;case 21:c=F.VideotexString;break;case 22:c=F.IA5String;break;case 23:c=F.UTCTime;break;case 24:c=F.GeneralizedTime;break;case 25:c=F.GraphicString;break;case 26:c=F.VisibleString;break;case 27:c=F.GeneralString;break;case 28:c=F.UniversalString;break;case 29:c=F.CharacterString;break;case 30:c=F.BmpString;break;case 31:c=F.DATE;break;case 32:c=F.TimeOfDay;break;case 33:c=F.DateTime;break;case 34:c=F.Duration;break;default:{let l=o.idBlock.isConstructed?new F.Constructed:new F.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?F.Constructed:F.Primitive}return o=sE(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 mo(r){if(!r.byteLength){let e=new Ue({},Ge);return e.error="Input buffer has zero length",{offset:-1,result:e}}return va(J.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function aE(r,e){return r?1:e}var tr=class extends Ge{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=J.BufferSourceConverter.toUint8Array(e);if(!vr(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 i=t;for(;aE(this.isIndefiniteForm,n)>0;){let s=va(o,i,n);if(s.offset===-1)return this.error=s.result.error,this.warnings.concat(s.result.warnings),-1;if(i=s.offset,this.blockLength+=s.result.blockLength,n-=s.result.blockLength,this.value.push(s.result),this.isIndefiniteForm&&s.result.constructor.NAME===ii)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===ii?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){let n=t||new oi;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?Ut:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};tr.NAME="ConstructedValueBlock";var ap,Qr=class extends Ue{constructor(e={}){super(e,tr),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(`
2
+ "use strict";var HeliaVerifiedFetch=(()=>{var Pb=Object.create;var ls=Object.defineProperty;var Db=Object.getOwnPropertyDescriptor;var Ob=Object.getOwnPropertyNames;var Ub=Object.getPrototypeOf,Fb=Object.prototype.hasOwnProperty;var ge=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),vt=(r,t)=>{for(var e in t)ls(r,e,{get:t[e],enumerable:!0})},Bd=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ob(t))!Fb.call(r,o)&&o!==e&&ls(r,o,{get:()=>t[o],enumerable:!(n=Db(t,o))||n.enumerable});return r};var Ot=(r,t,e)=>(e=r!=null?Pb(Ub(r)):{},Bd(t||!r||!r.__esModule?ls(e,"default",{value:r,enumerable:!0}):e,r)),Mb=r=>Bd(ls({},"__esModule",{value:!0}),r);var Rp=ge(co=>{"use strict";var kE="[object ArrayBuffer]",wr=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===kE}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,e){if(t.constructor===e)return t;if(this.isArrayBuffer(t))return new e(t);if(this.isArrayBufferView(t))return new e(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,e){let n=r.toUint8Array(t),o=r.toUint8Array(e);if(n.length!==o.byteLength)return!1;for(let i=0;i<n.length;i++)if(n[i]!==o[i])return!1;return!0}static concat(...t){let e;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?e=t[0]:t[t.length-1]instanceof Function?e=t.slice(0,t.length-1):e=t;let n=0;for(let s of e)n+=s.byteLength;let o=new Uint8Array(n),i=0;for(let s of e){let a=this.toUint8Array(s);o.set(a,i),i+=a.length}return t[t.length-1]instanceof Function?this.toView(o,t[t.length-1]):o.buffer}},nf="string",_E=/^[0-9a-f]+$/i,BE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,TE=/^[a-zA-Z0-9-_]+$/,Rs=class{static fromString(t){let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}static toString(t){let e=wr.toUint8Array(t),n="";for(let i=0;i<e.length;i++)n+=String.fromCharCode(e[i]);return decodeURIComponent(escape(n))}},ke=class{static toString(t,e=!1){let n=wr.toArrayBuffer(t),o=new DataView(n),i="";for(let s=0;s<n.byteLength;s+=2){let a=o.getUint16(s,e);i+=String.fromCharCode(a)}return i}static fromString(t,e=!1){let n=new ArrayBuffer(t.length*2),o=new DataView(n);for(let i=0;i<t.length;i++)o.setUint16(i*2,t.charCodeAt(i),e);return n}},Ns=class r{static isHex(t){return typeof t===nf&&_E.test(t)}static isBase64(t){return typeof t===nf&&BE.test(t)}static isBase64Url(t){return typeof t===nf&&TE.test(t)}static ToString(t,e="utf8"){let n=wr.toUint8Array(t);switch(e.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 ke.toString(n,!0);case"utf16":case"utf16be":return ke.toString(n);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromString(t,e="utf8"){if(!t)return new ArrayBuffer(0);switch(e.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return ke.fromString(t,!0);case"utf16":case"utf16be":return ke.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=wr.toUint8Array(t);if(typeof btoa<"u"){let n=this.ToString(e,"binary");return btoa(n)}else return Buffer.from(e).toString("base64")}static FromBase64(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64(e))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(e)):new Uint8Array(Buffer.from(e,"base64")).buffer}static FromBase64Url(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64Url(e))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(e.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.FromBinary(t);case"utf8":return Rs.fromString(t);case"utf16":case"utf16be":return ke.fromString(t);case"utf16le":case"usc2":return ke.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.ToBinary(t);case"utf8":return Rs.toString(t);case"utf16":case"utf16be":return ke.toString(t);case"utf16le":case"usc2":return ke.toString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromBinary(t){let e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);return n.buffer}static ToBinary(t){let e=wr.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=wr.toUint8Array(t),n="",o=e.length;for(let i=0;i<o;i++){let s=e[i];s<16&&(n+="0"),n+=s.toString(16)}return n}static FromHex(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isHex(e))throw new TypeError("Argument 'hexString' is not HEX encoded");e.length%2&&(e=`0${e}`);let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o=o+2){let i=e.slice(o,o+2);n[o/2]=parseInt(i,16)}return n.buffer}static ToUtf16String(t,e=!1){return ke.toString(t,e)}static FromUtf16String(t,e=!1){return ke.fromString(t,e)}static Base64Padding(t){let e=4-t.length%4;if(e<4)for(let n=0;n<e;n++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}};Ns.DEFAULT_UTF8_ENCODING="utf8";function CE(r,...t){let e=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let i in o)e[i]=o[i]}return e}function RE(...r){let t=r.map(o=>o.byteLength).reduce((o,i)=>o+i),e=new Uint8Array(t),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let i of o)e[n++]=i}),e.buffer}function NE(r,t){if(!(r&&t)||r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)if(e[o]!==n[o])return!1;return!0}co.BufferSourceConverter=wr;co.Convert=Ns;co.assign=CE;co.combine=RE;co.isEqual=NE});var zm=ge((bi,Ta)=>{(function(r,t){"use strict";var e={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var m=0;m<h.length;m++)if(!Number.isInteger(h[m])||h[m]<0||h[m]>255)return!1;return!0}function o(h,m){return(h&65535)*m+(((h>>>16)*m&65535)<<16)}function i(h,m){return h<<m|h>>>32-m}function s(h){return h^=h>>>16,h=o(h,2246822507),h^=h>>>13,h=o(h,3266489909),h^=h>>>16,h}function a(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var p=[0,0,0,0];return p[3]+=h[3]+m[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=h[2]+m[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=h[1]+m[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=h[0]+m[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function c(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var p=[0,0,0,0];return p[3]+=h[3]*m[3],p[2]+=p[3]>>>16,p[3]&=65535,p[2]+=h[2]*m[3],p[1]+=p[2]>>>16,p[2]&=65535,p[2]+=h[3]*m[2],p[1]+=p[2]>>>16,p[2]&=65535,p[1]+=h[1]*m[3],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=h[2]*m[2],p[0]+=p[1]>>>16,p[1]&=65535,p[1]+=h[3]*m[1],p[0]+=p[1]>>>16,p[1]&=65535,p[0]+=h[0]*m[3]+h[1]*m[2]+h[2]*m[1]+h[3]*m[0],p[0]&=65535,[p[0]<<16|p[1],p[2]<<16|p[3]]}function l(h,m){return m%=64,m===32?[h[1],h[0]]:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m|h[0]>>>32-m]:(m-=32,[h[1]<<m|h[0]>>>32-m,h[0]<<m|h[1]>>>32-m])}function u(h,m){return m%=64,m===0?h:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m]:[h[1]<<m-32,0]}function f(h,m){return[h[0]^m[0],h[1]^m[1]]}function d(h){return h=f(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=f(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=f(h,[0,h[0]>>>1]),h}e.x86.hash32=function(h,m){if(e.inputValidation&&!n(h))return t;m=m||0;for(var p=h.length%4,y=h.length-p,g=m,x=0,b=3432918353,E=461845907,k=0;k<y;k=k+4)x=h[k]|h[k+1]<<8|h[k+2]<<16|h[k+3]<<24,x=o(x,b),x=i(x,15),x=o(x,E),g^=x,g=i(g,13),g=o(g,5)+3864292196;switch(x=0,p){case 3:x^=h[k+2]<<16;case 2:x^=h[k+1]<<8;case 1:x^=h[k],x=o(x,b),x=i(x,15),x=o(x,E),g^=x}return g^=h.length,g=s(g),g>>>0},e.x86.hash128=function(h,m){if(e.inputValidation&&!n(h))return t;m=m||0;for(var p=h.length%16,y=h.length-p,g=m,x=m,b=m,E=m,k=0,T=0,S=0,v=0,_=597399067,z=2869860233,F=951274213,U=2716044179,P=0;P<y;P=P+16)k=h[P]|h[P+1]<<8|h[P+2]<<16|h[P+3]<<24,T=h[P+4]|h[P+5]<<8|h[P+6]<<16|h[P+7]<<24,S=h[P+8]|h[P+9]<<8|h[P+10]<<16|h[P+11]<<24,v=h[P+12]|h[P+13]<<8|h[P+14]<<16|h[P+15]<<24,k=o(k,_),k=i(k,15),k=o(k,z),g^=k,g=i(g,19),g+=x,g=o(g,5)+1444728091,T=o(T,z),T=i(T,16),T=o(T,F),x^=T,x=i(x,17),x+=b,x=o(x,5)+197830471,S=o(S,F),S=i(S,17),S=o(S,U),b^=S,b=i(b,15),b+=E,b=o(b,5)+2530024501,v=o(v,U),v=i(v,18),v=o(v,_),E^=v,E=i(E,13),E+=g,E=o(E,5)+850148119;switch(k=0,T=0,S=0,v=0,p){case 15:v^=h[P+14]<<16;case 14:v^=h[P+13]<<8;case 13:v^=h[P+12],v=o(v,U),v=i(v,18),v=o(v,_),E^=v;case 12:S^=h[P+11]<<24;case 11:S^=h[P+10]<<16;case 10:S^=h[P+9]<<8;case 9:S^=h[P+8],S=o(S,F),S=i(S,17),S=o(S,U),b^=S;case 8:T^=h[P+7]<<24;case 7:T^=h[P+6]<<16;case 6:T^=h[P+5]<<8;case 5:T^=h[P+4],T=o(T,z),T=i(T,16),T=o(T,F),x^=T;case 4:k^=h[P+3]<<24;case 3:k^=h[P+2]<<16;case 2:k^=h[P+1]<<8;case 1:k^=h[P],k=o(k,_),k=i(k,15),k=o(k,z),g^=k}return g^=h.length,x^=h.length,b^=h.length,E^=h.length,g+=x,g+=b,g+=E,x+=g,b+=g,E+=g,g=s(g),x=s(x),b=s(b),E=s(E),g+=x,g+=b,g+=E,x+=g,b+=g,E+=g,("00000000"+(g>>>0).toString(16)).slice(-8)+("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(E>>>0).toString(16)).slice(-8)},e.x64.hash128=function(h,m){if(e.inputValidation&&!n(h))return t;m=m||0;for(var p=h.length%16,y=h.length-p,g=[0,m],x=[0,m],b=[0,0],E=[0,0],k=[2277735313,289559509],T=[1291169091,658871167],S=0;S<y;S=S+16)b=[h[S+4]|h[S+5]<<8|h[S+6]<<16|h[S+7]<<24,h[S]|h[S+1]<<8|h[S+2]<<16|h[S+3]<<24],E=[h[S+12]|h[S+13]<<8|h[S+14]<<16|h[S+15]<<24,h[S+8]|h[S+9]<<8|h[S+10]<<16|h[S+11]<<24],b=c(b,k),b=l(b,31),b=c(b,T),g=f(g,b),g=l(g,27),g=a(g,x),g=a(c(g,[0,5]),[0,1390208809]),E=c(E,T),E=l(E,33),E=c(E,k),x=f(x,E),x=l(x,31),x=a(x,g),x=a(c(x,[0,5]),[0,944331445]);switch(b=[0,0],E=[0,0],p){case 15:E=f(E,u([0,h[S+14]],48));case 14:E=f(E,u([0,h[S+13]],40));case 13:E=f(E,u([0,h[S+12]],32));case 12:E=f(E,u([0,h[S+11]],24));case 11:E=f(E,u([0,h[S+10]],16));case 10:E=f(E,u([0,h[S+9]],8));case 9:E=f(E,[0,h[S+8]]),E=c(E,T),E=l(E,33),E=c(E,k),x=f(x,E);case 8:b=f(b,u([0,h[S+7]],56));case 7:b=f(b,u([0,h[S+6]],48));case 6:b=f(b,u([0,h[S+5]],40));case 5:b=f(b,u([0,h[S+4]],32));case 4:b=f(b,u([0,h[S+3]],24));case 3:b=f(b,u([0,h[S+2]],16));case 2:b=f(b,u([0,h[S+1]],8));case 1:b=f(b,[0,h[S]]),b=c(b,k),b=l(b,31),b=c(b,T),g=f(g,b)}return g=f(g,[0,h.length]),x=f(x,[0,h.length]),g=a(g,x),x=a(x,g),g=d(g),x=d(x),g=a(g,x),x=a(x,g),("00000000"+(g[0]>>>0).toString(16)).slice(-8)+("00000000"+(g[1]>>>0).toString(16)).slice(-8)+("00000000"+(x[0]>>>0).toString(16)).slice(-8)+("00000000"+(x[1]>>>0).toString(16)).slice(-8)},typeof bi<"u"?(typeof Ta<"u"&&Ta.exports&&(bi=Ta.exports=e),bi.murmurHash3=e):typeof define=="function"&&define.amd?define([],function(){return e}):(e._murmurHash3=r.murmurHash3,e.noConflict=function(){return r.murmurHash3=e._murmurHash3,e._murmurHash3=t,e.noConflict=t,e},r.murmurHash3=e)})(bi)});var yf=ge((DC,qm)=>{qm.exports=zm()});var jm=ge((YC,bf)=>{"use strict";var mv=Object.prototype.hasOwnProperty,Jt="~";function xi(){}Object.create&&(xi.prototype=Object.create(null),new xi().__proto__||(Jt=!1));function gv(r,t,e){this.fn=r,this.context=t,this.once=e||!1}function Wm(r,t,e,n,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var i=new gv(e,n||r,o),s=Jt?Jt+t:t;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],i]:r._events[s].push(i):(r._events[s]=i,r._eventsCount++),r}function La(r,t){--r._eventsCount===0?r._events=new xi:delete r._events[t]}function Wt(){this._events=new xi,this._eventsCount=0}Wt.prototype.eventNames=function(){var t=[],e,n;if(this._eventsCount===0)return t;for(n in e=this._events)mv.call(e,n)&&t.push(Jt?n.slice(1):n);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Wt.prototype.listeners=function(t){var e=Jt?Jt+t:t,n=this._events[e];if(!n)return[];if(n.fn)return[n.fn];for(var o=0,i=n.length,s=new Array(i);o<i;o++)s[o]=n[o].fn;return s};Wt.prototype.listenerCount=function(t){var e=Jt?Jt+t:t,n=this._events[e];return n?n.fn?1:n.length:0};Wt.prototype.emit=function(t,e,n,o,i,s){var a=Jt?Jt+t:t;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,o),!0;case 5:return c.fn.call(c.context,e,n,o,i),!0;case 6:return c.fn.call(c.context,e,n,o,i,s),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(t,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,e);break;case 3:c[f].fn.call(c[f].context,e,n);break;case 4:c[f].fn.call(c[f].context,e,n,o);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};Wt.prototype.on=function(t,e,n){return Wm(this,t,e,n,!1)};Wt.prototype.once=function(t,e,n){return Wm(this,t,e,n,!0)};Wt.prototype.removeListener=function(t,e,n,o){var i=Jt?Jt+t:t;if(!this._events[i])return this;if(!e)return La(this,i),this;var s=this._events[i];if(s.fn)s.fn===e&&(!o||s.once)&&(!n||s.context===n)&&La(this,i);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==e||o&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[i]=c.length===1?c[0]:c:La(this,i)}return this};Wt.prototype.removeAllListeners=function(t){var e;return t?(e=Jt?Jt+t:t,this._events[e]&&La(this,e)):(this._events=new xi,this._eventsCount=0),this};Wt.prototype.off=Wt.prototype.removeListener;Wt.prototype.addListener=Wt.prototype.on;Wt.prefixed=Jt;Wt.EventEmitter=Wt;typeof bf<"u"&&(bf.exports=Wt)});var If=ge((w6,Jm)=>{Jm.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,e=Object.create(null),n=Object.create(null);function o(i,s){e[i]=s,t++,t>=r&&(t=0,n=e,e=Object.create(null))}return{has:function(i){return e[i]!==void 0||n[i]!==void 0},remove:function(i){e[i]!==void 0&&(e[i]=void 0),n[i]!==void 0&&(n[i]=void 0)},get:function(i){var s=e[i];if(s!==void 0)return s;if((s=n[i])!==void 0)return o(i,s),s},set:function(i,s){e[i]!==void 0?e[i]=s:o(i,s)},clear:function(){e=Object.create(null),n=Object.create(null)}}}});var R0=ge(Oi=>{(function(){var r,t,e,n,o,i,s,a;a=function(c){var l,u,f,d;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[l,u,f,d].join(".")},s=function(c){var l,u,f,d,h,m;for(l=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}m=t(c),h=m[0],u=m[1],c=c.substring(u),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},e=function(c){return c.charCodeAt(0)},n=e("0"),i=e("a"),o=e("A"),t=function(c){var l,u,f,d,h;for(d=0,l=10,u="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,l=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,l=8,u="7")),h=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)d=d*l+(e(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")d=d*l+(10+e(c[f])-i)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*l+(10+e(c[f])-o)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===h)throw new Error("empty octet");return[d,f]},r=function(){function c(l,u){var f,d,h,m;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(m=l.split("/",2),l=m[0],u=m[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=s(u)}catch(p){throw f=p,new Error("Invalid mask: "+u)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(s(l)&this.maskLong)>>>0}catch(p){throw f=p,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(s(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,f,d;for(d=s(this.first),f=s(this.last),u=0;d<=f;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c}(),Oi.ip2long=s,Oi.long2ip=a,Oi.Netmask=r}).call(Oi)});var Do=ge((vP,Rh)=>{var EP=function(){typeof Rh<"u"&&(Rh.exports=p);var r=86400,t=3200,e=146097*t/400,n=r*e,o=1e3*n,i=864e13,s=4294967296,a=1e6,c="000000000",l=Math.trunc||function(v){var _=v-v%1;return _==0&&(v<0||v===0&&1/v!=1/0)?-0:_},u=p.prototype,f=(p.fromDate=function(v){return new p(+v)},p.fromInt64BE=E(0,1,2,3,0,4),p.fromInt64LE=E(3,2,1,0,4,0),p.fromString=function(F){var _,z=new p,F=(F+="").replace(/^\s*[+\-]?\d+/,function(P){var P=+P,R=1970+(P-1970)%400;return z.year=P-R,R}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function(U,P,R){return P<0&&(R*=-1),_=6e4*(60*+P+ +R),""}).replace(/\.\d+$/,function(U){return z.nano=+(U+c).substr(1,9),""}).split(/\D+/);if(1<F.length?F[1]--:F[1]=0,z.time=_=Date.UTC.apply(Date,F)-(_||0),isNaN(_))throw new TypeError("Invalid Date");return y(z)},p.fromTimeT=function(v){return x(v,0)},u.year=0,u.time=0,u.nano=0,u.addNano=function(v){return this.nano+=+v||0,this},u.getNano=function(){var v=y(this);return(v.time%1e3*a+ +v.nano+1e9)%1e9},u.getTimeT=function(){var _=y(this),v=Math.floor(_.time/1e3),_=_.year;return _&&(v+=_*e*r/t),v},u.getYear=function(){return this.toDate().getUTCFullYear()+this.year},u.toDate=function(){return g(y(this).time)},u.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},u.toString=function(v){var _=this,z=_.toDate(),F={H:function(){return T(z.getUTCHours())},L:function(){return S(z.getUTCMilliseconds(),3)},M:function(){return T(z.getUTCMinutes())},N:function(){return S(_.getNano(),9)},S:function(){return T(z.getUTCSeconds())},Y:function(){var U=_.getYear();return 999999<U?"+"+U:9999<U?"+"+S(U,6):0<=U?S(U,4):-999999<=U?"-"+S(-U,6):U},a:function(){return h[z.getUTCDay()]},b:function(){return d[z.getUTCMonth()]},d:function(){return T(z.getUTCDate())},e:function(){return function(U){return(9<U?"":" ")+(0|U)}(z.getUTCDate())},m:function(){return T(z.getUTCMonth()+1)}};return function U(P){return P.replace(/%./g,function(R){var I=R[1],N=m[I],I=F[I];return N?U(N):I?I():R})}(v||f)},u.writeInt64BE=b(0,1,2,3,0,4),u.writeInt64LE=b(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m={"%":"%",F:"%Y-%m-%d",n:`
3
+ `,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return p;function p(v,_,z){var F=this;if(!(F instanceof p))return new p(v,_,z);F.time=+v||0,F.nano=+_||0,F.year=+z||0,y(F)}function y(v){var _,z,F,U=v.year,P=v.time,R=v.nano,N=((R<0||a<=R)&&(R-=(z=Math.floor(R/a))*a,P+=z,z=1),U%t);return(P<-i||i<P||N)&&((_=l(P/o))&&(U+=_*t,P-=_*o),(F=g(P)).setUTCFullYear(N+F.getUTCFullYear()),F=(P=+F)+(_=l((U-=N)/t))*o,_&&-i<=F&&F<=i&&(U-=_*t,P=F),z=1),z&&(v.year=U,v.time=P,v.nano=R),v}function g(v){var _=new Date(0);return _.setTime(v),_}function x(U,F){U=+U||0;var z=l((F=(F|0)*s)/n)+l(U/n),F=F%n+U%n,U=l(F/n);return U&&(z+=U,F-=U*n),new p(1e3*F,0,z*t)}function b(v,_,z,F,U,P){return function(N,I){var C=y(this);N=N||new Array(8),k(N,I|=0);var V=Math.floor(C.time/1e3),C=C.year*(e*r/t),A=l(C/s)+l(V/s),C=C%s+V%s,V=Math.floor(C/s);return V&&(A+=V,C-=V*s),R(N,I+U,A),R(N,I+P,C),N};function R(N,I,A){N[I+v]=A>>24&255,N[I+_]=A>>16&255,N[I+z]=A>>8&255,N[I+F]=255&A}}function E(v,_,z,F,U,P){return function(N,I){k(N,I|=0);var A=R(N,I+U);return x(R(N,I+P),A)};function R(N,I){return 16777216*N[I+v]+(N[I+_]<<16|N[I+z]<<8|N[I+F])}}function k(v,_){if(v=v&&v.length,v==null)throw new TypeError("Invalid Buffer");if(v<_+8)throw new RangeError("Out of range")}function T(v){return(9<v?"":"0")+(0|v)}function S(v,_){return(c+(0|v)).substr(-_)}}()});var Ny=ge((JO,Ry)=>{Ry.exports=$h;var Cy=128,iA=127,sA=~iA,aA=Math.pow(2,31);function $h(r,t,e){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw $h.bytes=0,new RangeError("Could not encode varint");t=t||[],e=e||0;for(var n=e;r>=aA;)t[e++]=r&255|Cy,r/=128;for(;r&sA;)t[e++]=r&255|Cy,r>>>=7;return t[e]=r|0,$h.bytes=e-n+1,t}});var Dy=ge((QO,Py)=>{Py.exports=zh;var cA=128,Ly=127;function zh(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a||o>49)throw zh.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&Ly)<<o:(s&Ly)*Math.pow(2,o),o+=7}while(s>=cA);return zh.bytes=i-n,e}});var Uy=ge((tU,Oy)=>{var lA=Math.pow(2,7),uA=Math.pow(2,14),fA=Math.pow(2,21),hA=Math.pow(2,28),dA=Math.pow(2,35),pA=Math.pow(2,42),mA=Math.pow(2,49),gA=Math.pow(2,56),yA=Math.pow(2,63);Oy.exports=function(r){return r<lA?1:r<uA?2:r<fA?3:r<hA?4:r<dA?5:r<pA?6:r<mA?7:r<gA?8:r<yA?9:10}});var Yc=ge((eU,Fy)=>{Fy.exports={encode:Ny(),decode:Dy(),encodingLength:Uy()}});var Cw=ge((OM,Tw)=>{"use strict";Tw.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(t,e){let n=this._internalPositionFor(t,!1);if(e===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(t),this._changedLength=!0,this._changedData=!0);else{let o=!1;n===-1?(n=this._data.length,this._setBit(t),this._changedData=!0):o=!0,this._setInternalPos(n,t,e,o),this._changedLength=!0}}unset(t){this.set(t,void 0)}get(t){this._sortData();let e=this._internalPositionFor(t,!0);if(e!==-1)return this._data[e][1]}push(t){return this.set(this.length,t),this.length}get length(){if(this._sortData(),this._changedLength){let t=this._data[this._data.length-1];this._length=t?t[0]+1:0,this._changedLength=!1}return this._length}forEach(t){let e=0;for(;e<this.length;)t(this.get(e),e,this),e++}map(t){let e=0,n=new Array(this.length);for(;e<this.length;)n[e]=t(this.get(e),e,this),e++;return n}reduce(t,e){let n=0,o=e;for(;n<this.length;){let i=this.get(n);o=t(o,i,n),n++}return o}find(t){let e=0,n,o;for(;e<this.length&&!n;)o=this.get(e),n=t(o),e++;return n?o:void 0}_internalPositionFor(t,e){let n=this._bytePosFor(t,e);if(n>=this._bitArrays.length)return-1;let o=this._bitArrays[n],i=t-n*7;if(!((o&1<<i)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(pI,0),c=~(4294967295<<i+1),l=Bw(o&c);return a+l-1}_bytePosFor(t,e){let n=Math.floor(t/7),o=n+1;for(;!e&&this._bitArrays.length<o;)this._bitArrays.push(0);return n}_setBit(t){let e=this._bytePosFor(t,!1);this._bitArrays[e]|=1<<t-e*7}_unsetBit(t){let e=this._bytePosFor(t,!1);this._bitArrays[e]&=~(1<<t-e*7)}_setInternalPos(t,e,n,o){let i=this._data,s=[e,n];if(o)this._sortData(),i[t]=s;else{if(i.length)if(i[i.length-1][0]>=e)i.push(s);else if(i[0][0]<=e)i.unshift(s);else{let a=Math.round(i.length/2);this._data=i.slice(0,a).concat(s).concat(i.slice(a))}else this._data.push(s);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(t){this._data.splice(t,1)}_sortData(){this._changedData&&this._data.sort(mI),this._changedData=!1}bitField(){let t=[],e=8,n=0,o=0,i,s=this._bitArrays.slice();for(;s.length||n;){n===0&&(i=s.shift(),n=7);let c=Math.min(n,e),l=~(255<<c),u=i&l;o|=u<<8-e,i=i>>>c,n-=c,e-=c,(!e||!n&&!s.length)&&(t.push(o),o=0,e=8)}for(var a=t.length-1;a>0&&t[a]===0;a--)t.pop();return t}compactArray(){return this._sortData(),this._data.map(gI)}};function pI(r,t){return r+Bw(t)}function Bw(r){let t=r;return t=t-(t>>1&1431655765),t=(t&858993459)+(t>>2&858993459),(t+(t>>4)&252645135)*16843009>>24}function mI(r,t){return r[0]-t[0]}function gI(r){return r[1]}});var ub=ge((Y9,lb)=>{"use strict";lb.exports={RTLD_LAZY:1,RTLD_NOW:2,RTLD_GLOBAL:256,RTLD_LOCAL:0,RTLD_DEEPBIND:8,E2BIG:7,EACCES:13,EADDRINUSE:98,EADDRNOTAVAIL:99,EAFNOSUPPORT:97,EAGAIN:11,EALREADY:114,EBADF:9,EBADMSG:74,EBUSY:16,ECANCELED:125,ECHILD:10,ECONNABORTED:103,ECONNREFUSED:111,ECONNRESET:104,EDEADLK:35,EDESTADDRREQ:89,EDOM:33,EDQUOT:122,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:113,EIDRM:43,EILSEQ:84,EINPROGRESS:115,EINTR:4,EINVAL:22,EIO:5,EISCONN:106,EISDIR:21,ELOOP:40,EMFILE:24,EMLINK:31,EMSGSIZE:90,EMULTIHOP:72,ENAMETOOLONG:36,ENETDOWN:100,ENETRESET:102,ENETUNREACH:101,ENFILE:23,ENOBUFS:105,ENODATA:61,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:37,ENOLINK:67,ENOMEM:12,ENOMSG:42,ENOPROTOOPT:92,ENOSPC:28,ENOSR:63,ENOSTR:60,ENOSYS:38,ENOTCONN:107,ENOTDIR:20,ENOTEMPTY:39,ENOTSOCK:88,ENOTSUP:95,ENOTTY:25,ENXIO:6,EOPNOTSUPP:95,EOVERFLOW:75,EPERM:1,EPIPE:32,EPROTO:71,EPROTONOSUPPORT:93,EPROTOTYPE:91,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:116,ETIME:62,ETIMEDOUT:110,ETXTBSY:26,EWOULDBLOCK:11,EXDEV:18,PRIORITY_LOW:19,PRIORITY_BELOW_NORMAL:10,PRIORITY_NORMAL:0,PRIORITY_ABOVE_NORMAL:-7,PRIORITY_HIGH:-14,PRIORITY_HIGHEST:-20,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:17,SIGSTKFLT:16,SIGCONT:18,SIGSTOP:19,SIGTSTP:20,SIGTTIN:21,SIGTTOU:22,SIGURG:23,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:29,SIGPOLL:29,SIGPWR:30,SIGSYS:31,UV_FS_SYMLINK_DIR:1,UV_FS_SYMLINK_JUNCTION:2,O_RDONLY:0,O_WRONLY:1,O_RDWR:2,UV_DIRENT_UNKNOWN:0,UV_DIRENT_FILE:1,UV_DIRENT_DIR:2,UV_DIRENT_LINK:3,UV_DIRENT_FIFO:4,UV_DIRENT_SOCKET:5,UV_DIRENT_CHAR:6,UV_DIRENT_BLOCK:7,EXTENSIONLESS_FORMAT_JAVASCRIPT:0,EXTENSIONLESS_FORMAT_WASM:1,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:64,O_EXCL:128,UV_FS_O_FILEMAP:0,O_NOCTTY:256,O_TRUNC:512,O_APPEND:1024,O_DIRECTORY:65536,O_NOATIME:262144,O_NOFOLLOW:131072,O_SYNC:1052672,O_DSYNC:4096,O_DIRECT:16384,O_NONBLOCK:2048,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,F_OK:0,R_OK:4,W_OK:2,X_OK:1,UV_FS_COPYFILE_EXCL:1,COPYFILE_EXCL:1,UV_FS_COPYFILE_FICLONE:2,COPYFILE_FICLONE:2,UV_FS_COPYFILE_FICLONE_FORCE:4,COPYFILE_FICLONE_FORCE:4,OPENSSL_VERSION_NUMBER:805306576,SSL_OP_ALL:2147485776,SSL_OP_ALLOW_NO_DHE_KEX:1024,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_ENCRYPT_THEN_MAC:524288,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_RENEGOTIATION:1073741824,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:0,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_NO_TLSv1_3:536870912,SSL_OP_PRIORITIZE_CHACHA:2097152,SSL_OP_TLS_ROLLBACK_BUG:8388608,ENGINE_METHOD_RSA:1,ENGINE_METHOD_DSA:2,ENGINE_METHOD_DH:4,ENGINE_METHOD_RAND:8,ENGINE_METHOD_EC:2048,ENGINE_METHOD_CIPHERS:64,ENGINE_METHOD_DIGESTS:128,ENGINE_METHOD_PKEY_METHS:512,ENGINE_METHOD_PKEY_ASN1_METHS:1024,ENGINE_METHOD_ALL:65535,ENGINE_METHOD_NONE:0,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,RSA_PKCS1_PADDING:1,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,RSA_PSS_SALTLEN_DIGEST:-1,RSA_PSS_SALTLEN_MAX_SIGN:-2,RSA_PSS_SALTLEN_AUTO:-2,defaultCoreCipherList:"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA",TLS1_VERSION:769,TLS1_1_VERSION:770,TLS1_2_VERSION:771,TLS1_3_VERSION:772,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}});var Pk={};vt(Pk,{createVerifiedFetch:()=>xd,verifiedFetch:()=>zl});var Wo=Symbol.for("@libp2p/content-routing");function Td(r){return r==null?!1:(r.type==="RSA"||r.type==="Ed25519"||r.type==="secp256k1")&&r.raw instanceof Uint8Array&&typeof r.equals=="function"&&typeof r.toMultihash=="function"&&typeof r.toCID=="function"&&typeof r.verify=="function"}var $n=Symbol.for("@libp2p/peer-id");var jo=Symbol.for("@libp2p/peer-routing");var Ne=class extends Error{static name="AbortError";constructor(t="The operation was aborted"){super(t),this.name="AbortError"}};var gt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},zn=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var _t=class extends Error{static name="NotFoundError";constructor(t="Not found"){super(t),this.name="NotFoundError"}};var Yo=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Ae=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var pn=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var mt=(r,...t)=>{try{[...t]}catch{}};var qn=class extends EventTarget{#t=new Map;constructor(){super(),mt(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:i})=>i!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};function Cd(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Vr(...r){let t=[];for(let e of r)Cd(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStart!=null&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{e.afterStart!=null&&await e.afterStart()}))}async function Hr(...r){let t=[];for(let e of r)Cd(e)&&t.push(e);await Promise.all(t.map(async e=>{e.beforeStop!=null&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{e.afterStop!=null&&await e.afterStop()}))}function Yt(r){let t=new globalThis.AbortController;function e(){t.abort();for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}for(let i of r){if(i?.aborted===!0){e();break}i?.addEventListener!=null&&i.addEventListener("abort",e)}function n(){for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}function ft(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var us=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Kn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new us(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new us(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Kl=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function We(r={}){return Vb(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Vb(r,t){t=t??{};let e=t.onEnd,n=new Kn,o,i,s,a=ft(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((y,g)=>{i=x=>{i=null,n.push(x);try{y(r(n))}catch(b){g(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ft()})}},l=y=>i!=null?i(y):(n.push(y),o),u=y=>(n=new Kn,i!=null?i({error:y}):(n.push({error:y}),o)),f=y=>{if(s)return o;if(t?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},d=y=>s?o:(s=!0,y!=null?u(y):l({done:!0})),h=()=>(n=new Kn,d(),{done:!0}),m=y=>(d(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:f,end:d,get readableLength(){return n.size},onEmpty:async y=>{let g=y?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,b;g!=null&&(x=new Promise((E,k)=>{b=()=>{k(new Kl)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,x])}finally{b!=null&&g!=null&&g?.removeEventListener("abort",b)}}},e==null)return o;let p=o;return o={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(y){return p.throw(y),e!=null&&(e(y),e=void 0),{done:!0}},return(){return p.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(y){return p.end(y),e!=null&&(e(y),e=void 0),o},get readableLength(){return p.readableLength},onEmpty:y=>p.onEmpty(y)},o}var Gl=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function fs(r,t,e,n){let o=new Gl(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((i,s)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),s(d);return}a(),i(f)},l=f=>{a(),s(f.detail)},u=()=>{a(),s(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var hs=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function Rd(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new hs(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new hs(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((i,s)=>{n=()=>{s(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}function Hb(r){return r[Symbol.asyncIterator]!=null}function $b(r){if(Hb(r))return(async()=>{for await(let t of r);})();for(let t of r);}var ur=$b;function re(r=0){return new Uint8Array(r)}function ne(r=0){return new Uint8Array(r)}var zb=Math.pow(2,7),qb=Math.pow(2,14),Kb=Math.pow(2,21),Wl=Math.pow(2,28),jl=Math.pow(2,35),Yl=Math.pow(2,42),Xl=Math.pow(2,49),it=128,$t=127;function oe(r){if(r<zb)return 1;if(r<qb)return 2;if(r<Kb)return 3;if(r<Wl)return 4;if(r<jl)return 5;if(r<Yl)return 6;if(r<Xl)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Zl(r,t,e=0){switch(oe(r)){case 8:t[e++]=r&255|it,r/=128;case 7:t[e++]=r&255|it,r/=128;case 6:t[e++]=r&255|it,r/=128;case 5:t[e++]=r&255|it,r/=128;case 4:t[e++]=r&255|it,r>>>=7;case 3:t[e++]=r&255|it,r>>>=7;case 2:t[e++]=r&255|it,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Gb(r,t,e=0){switch(oe(r)){case 8:t.set(e++,r&255|it),r/=128;case 7:t.set(e++,r&255|it),r/=128;case 6:t.set(e++,r&255|it),r/=128;case 5:t.set(e++,r&255|it),r/=128;case 4:t.set(e++,r&255|it),r>>>=7;case 3:t.set(e++,r&255|it),r>>>=7;case 2:t.set(e++,r&255|it),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Jl(r,t){let e=r[t],n=0;if(n+=e&$t,e<it||(e=r[t+1],n+=(e&$t)<<7,e<it)||(e=r[t+2],n+=(e&$t)<<14,e<it)||(e=r[t+3],n+=(e&$t)<<21,e<it)||(e=r[t+4],n+=(e&$t)*Wl,e<it)||(e=r[t+5],n+=(e&$t)*jl,e<it)||(e=r[t+6],n+=(e&$t)*Yl,e<it)||(e=r[t+7],n+=(e&$t)*Xl,e<it))return n;throw new RangeError("Could not decode varint")}function Wb(r,t){let e=r.get(t),n=0;if(n+=e&$t,e<it||(e=r.get(t+1),n+=(e&$t)<<7,e<it)||(e=r.get(t+2),n+=(e&$t)<<14,e<it)||(e=r.get(t+3),n+=(e&$t)<<21,e<it)||(e=r.get(t+4),n+=(e&$t)*Wl,e<it)||(e=r.get(t+5),n+=(e&$t)*jl,e<it)||(e=r.get(t+6),n+=(e&$t)*Yl,e<it)||(e=r.get(t+7),n+=(e&$t)*Xl,e<it))return n;throw new RangeError("Could not decode varint")}function Gn(r,t,e=0){return t==null&&(t=ne(oe(r))),t instanceof Uint8Array?Zl(r,t,e):Gb(r,t,e)}function mn(r,t=0){return r instanceof Uint8Array?Jl(r,t):Wb(r,t)}function ct(r,t){t==null&&(t=r.reduce((o,i)=>o+i.length,0));let e=ne(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function Z(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var Pd=Symbol.for("@achingbrain/uint8arraylist");function Ld(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function je(r){return!!r?.[Pd]}var fr=class r{bufs;length;[Pd]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(je(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(je(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Ld(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ld(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(je(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return ct(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:ct(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),i=new r;return i.length=o,i.bufs=[...n],i}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let i=0;i<this.bufs.length;i++){let s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(s);break}let f=t-a;n.push(s.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(s);continue}n.push(s.subarray(t-a));continue}if(u){if(e===c){n.push(s);break}n.push(s.subarray(0,e-a));break}n.push(s)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!je(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let i=256,s=new Int32Array(i);for(let f=0;f<i;f++)s[f]=-1;for(let f=0;f<o;f++)s[n[f]]=f;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=re(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=ne(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=re(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=re(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=re(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Z(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,i)=>o+i.byteLength,0)),n.length=e,n}};function jb(r){let[t,e]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[e](){return this}}}var Wn=jb;function Yb(r){return r[Symbol.asyncIterator]!=null}function Xb(r,t){let e=0;if(Yb(r))return async function*(){for await(let c of r)yield t(c,e++)}();let n=Wn(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=t(o,e++);if(typeof s.then=="function")return async function*(){yield await s;for await(let c of n)yield t(c,e++)}();let a=t;return function*(){yield s;for(let c of n)yield a(c,e++)}()}var zt=Xb;function Zb(r){return r[Symbol.asyncIterator]!=null}function Jb(...r){let t=[];for(let e of r)Zb(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=We({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var $r=Jb;function Ye(r,...t){if(r==null)throw new Error("Empty pipeline");if(Ql(r)){let n=r;r=()=>n.source}else if(Od(r)||Dd(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Ql(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)Ql(e[n])&&(e[n]=tx(e[n]));return Qb(...e)}var Qb=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Dd=r=>r?.[Symbol.asyncIterator]!=null,Od=r=>r?.[Symbol.iterator]!=null,Ql=r=>r==null?!1:r.sink!=null&&r.source!=null,tx=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=We({objectMode:!0});e.then(()=>{n.end()},s=>{n.end(s)});let o,i=r.source;if(Dd(i))o=async function*(){yield*i,n.end()};else if(Od(i))o=function*(){yield*i,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return $r(n,o())}return r.source};function ex(r){return r[Symbol.asyncIterator]!=null}function rx(r,t){return ex(r)?async function*(){let e=0;if(!(t<1)){for await(let n of r)if(yield n,e++,e===t)return}}():function*(){let e=0;if(!(t<1)){for(let n of r)if(yield n,e++,e===t)return}}()}var ds=rx;var H=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var tu=new Float32Array([-0]),zr=new Uint8Array(tu.buffer);function Ud(r,t,e){tu[0]=r,t[e]=zr[0],t[e+1]=zr[1],t[e+2]=zr[2],t[e+3]=zr[3]}function Fd(r,t){return zr[0]=r[t],zr[1]=r[t+1],zr[2]=r[t+2],zr[3]=r[t+3],tu[0]}var eu=new Float64Array([-0]),qt=new Uint8Array(eu.buffer);function Md(r,t,e){eu[0]=r,t[e]=qt[0],t[e+1]=qt[1],t[e+2]=qt[2],t[e+3]=qt[3],t[e+4]=qt[4],t[e+5]=qt[5],t[e+6]=qt[6],t[e+7]=qt[7]}function Vd(r,t){return qt[0]=r[t],qt[1]=r[t+1],qt[2]=r[t+2],qt[3]=r[t+3],qt[4]=r[t+4],qt[5]=r[t+5],qt[6]=r[t+6],qt[7]=r[t+7],eu[0]}var nx=BigInt(Number.MAX_SAFE_INTEGER),ox=BigInt(Number.MIN_SAFE_INTEGER),ye=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return gn;if(t<nx&&t>ox)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Hd&&(o=0n,++n>Hd&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return gn;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):gn}},gn=new ye(0,0);gn.toBigInt=function(){return 0n};gn.zzEncode=gn.zzDecode=function(){return this};gn.length=function(){return 1};var Hd=4294967296n;function $d(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function zd(r,t,e){if(e-t<1)return"";let o,i=[],s=0,a;for(;t<e;)a=r[t++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function ru(r,t,e){let n=e,o,i;for(let s=0;s<r.length;++s)o=r.charCodeAt(s),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((i=r.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function Le(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function ps(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var nu=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Le(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Le(this,4);return ps(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Le(this,4);return ps(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Le(this,4);let t=Fd(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Le(this,4);let t=Vd(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Le(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return zd(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Le(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Le(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new ye(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Le(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Le(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Le(this,8);let t=ps(this.buf,this.pos+=4),e=ps(this.buf,this.pos+=4);return new ye(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Jl(this.buf,this.pos);return this.pos+=oe(t),t}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 ou(r){return new nu(r instanceof Uint8Array?r:r.subarray())}function ie(r,t,e){let n=ou(r);return t.decode(n,void 0,e)}var hu={};vt(hu,{base10:()=>dx});var yn={};vt(yn,{coerce:()=>Ie,empty:()=>Kd,equals:()=>iu,fromHex:()=>sx,fromString:()=>su,isBinary:()=>ax,toHex:()=>ix,toString:()=>au});var Kd=new Uint8Array(0);function ix(r){return r.reduce((t,e)=>t+e.toString(16).padStart(2,"0"),"")}function sx(r){let t=r.match(/../g);return t!=null?new Uint8Array(t.map(e=>parseInt(e,16))):Kd}function iu(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ie(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 ax(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function su(r){return new TextEncoder().encode(r)}function au(r){return new TextDecoder().decode(r)}function cx(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var i=r.charAt(o),s=i.charCodeAt(0);if(e[s]!==255)throw new TypeError(i+" is ambiguous");e[s]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var p=0,y=0,g=0,x=m.length;g!==x&&m[g]===0;)g++,p++;for(var b=(x-g)*u+1>>>0,E=new Uint8Array(b);g!==x;){for(var k=m[g],T=0,S=b-1;(k!==0||T<y)&&S!==-1;S--,T++)k+=256*E[S]>>>0,E[S]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");y=T,g++}for(var v=b-y;v!==b&&E[v]===0;)v++;for(var _=c.repeat(p);v<b;++v)_+=r.charAt(E[v]);return _}function d(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var p=0;if(m[p]!==" "){for(var y=0,g=0;m[p]===c;)y++,p++;for(var x=(m.length-p)*l+1>>>0,b=new Uint8Array(x);m[p];){var E=e[m.charCodeAt(p)];if(E===255)return;for(var k=0,T=x-1;(E!==0||k<g)&&T!==-1;T--,k++)E+=a*b[T]>>>0,b[T]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");g=k,p++}if(m[p]!==" "){for(var S=x-g;S!==x&&b[S]===0;)S++;for(var v=new Uint8Array(y+(x-S)),_=y;S!==x;)v[_++]=b[S++];return v}}}function h(m){var p=d(m);if(p)return p;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var lx=cx,ux=lx,Gd=ux;var cu=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},lu=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Wd(this,t)}},uu=class{decoders;constructor(t){this.decoders=t}or(t){return Wd(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Wd(r,t){return new uu({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var fu=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new cu(t,e,n),this.decoder=new lu(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function jn({name:r,prefix:t,encode:e,decode:n}){return new fu(r,t,e,n)}function qr({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Gd(e,r);return jn({prefix:t,name:r,encode:n,decode:i=>Ie(o(i))})}function fx(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*e/8|0),a=0,c=0,l=0;for(let u=0;u<i;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,s[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s}function hx(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,i="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>e;)s-=e,i+=t[o&a>>s];if(s!==0&&(i+=t[o&a<<e-s]),n)for(;i.length*e&7;)i+="=";return i}function yt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return jn({prefix:t,name:r,encode(o){return hx(o,n,e)},decode(o){return fx(o,n,e,r)}})}var dx=qr({prefix:"9",name:"base10",alphabet:"0123456789"});var du={};vt(du,{base16:()=>px,base16upper:()=>mx});var px=yt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),mx=yt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var pu={};vt(pu,{base2:()=>gx});var gx=yt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var mu={};vt(mu,{base256emoji:()=>Ex});var jd=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}"),yx=jd.reduce((r,t,e)=>(r[e]=t,r),[]),wx=jd.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function bx(r){return r.reduce((t,e)=>(t+=yx[e],t),"")}function xx(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=wx[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Ex=jn({prefix:"\u{1F680}",name:"base256emoji",encode:bx,decode:xx});var gu={};vt(gu,{base32:()=>St,base32hex:()=>Ix,base32hexpad:()=>_x,base32hexpadupper:()=>Bx,base32hexupper:()=>kx,base32pad:()=>Sx,base32padupper:()=>Ax,base32upper:()=>vx,base32z:()=>Tx});var St=yt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),vx=yt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Sx=yt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ax=yt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ix=yt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),kx=yt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),_x=yt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Bx=yt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Tx=yt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var yu={};vt(yu,{base36:()=>Kt,base36upper:()=>Cx});var Kt=qr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Cx=qr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var wu={};vt(wu,{base58btc:()=>Y,base58flickr:()=>Rx});var Y=qr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Rx=qr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var xu={};vt(xu,{base64:()=>se,base64pad:()=>Nx,base64url:()=>bu,base64urlpad:()=>Lx});var se=yt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Nx=yt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),bu=yt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Lx=yt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Eu={};vt(Eu,{base8:()=>Px});var Px=yt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var vu={};vt(vu,{identity:()=>Dx});var Dx=jn({prefix:"\0",name:"identity",encode:r=>au(r),decode:r=>su(r)});var Yn={};vt(Yn,{code:()=>hr,decode:()=>Su,encode:()=>Mx,name:()=>Fx});var Ox=new TextEncoder,Ux=new TextDecoder,Fx="json",hr=512;function Mx(r){return Ox.encode(JSON.stringify(r))}function Su(r){return JSON.parse(Ux.decode(r))}var wn={};vt(wn,{code:()=>ae,decode:()=>$x,encode:()=>Hx,name:()=>Vx});var Vx="raw",ae=85;function Hx(r){return Ie(r)}function $x(r){return Ie(r)}var Iu={};vt(Iu,{identity:()=>bt});var zx=Zd,Yd=128,qx=127,Kx=~qx,Gx=Math.pow(2,31);function Zd(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Gx;)t[e++]=r&255|Yd,r/=128;for(;r&Kx;)t[e++]=r&255|Yd,r>>>=7;return t[e]=r|0,Zd.bytes=e-n+1,t}var Wx=Au,jx=128,Xd=127;function Au(r,n){var e=0,n=n||0,o=0,i=n,s,a=r.length;do{if(i>=a)throw Au.bytes=0,new RangeError("Could not decode varint");s=r[i++],e+=o<28?(s&Xd)<<o:(s&Xd)*Math.pow(2,o),o+=7}while(s>=jx);return Au.bytes=i-n,e}var Yx=Math.pow(2,7),Xx=Math.pow(2,14),Zx=Math.pow(2,21),Jx=Math.pow(2,28),Qx=Math.pow(2,35),t1=Math.pow(2,42),e1=Math.pow(2,49),r1=Math.pow(2,56),n1=Math.pow(2,63),o1=function(r){return r<Yx?1:r<Xx?2:r<Zx?3:r<Jx?4:r<Qx?5:r<t1?6:r<e1?7:r<r1?8:r<n1?9:10},i1={encode:zx,decode:Wx,encodingLength:o1},s1=i1,Xo=s1;function Zo(r,t=0){return[Xo.decode(r,t),Xo.decode.bytes]}function Xn(r,t,e=0){return Xo.encode(r,t,e),t}function Zn(r){return Xo.encodingLength(r)}function Pe(r,t){let e=t.byteLength,n=Zn(r),o=n+Zn(e),i=new Uint8Array(o+e);return Xn(r,i,0),Xn(e,i,n),i.set(t,o),new Jn(r,e,t,i)}function wt(r){let t=Ie(r),[e,n]=Zo(t),[o,i]=Zo(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Jn(e,o,s,t)}function Jd(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&iu(r.bytes,e.bytes)}}var Jn=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var Qd=0,a1="identity",tp=Ie;function c1(r){return Pe(Qd,tp(r))}var bt={code:Qd,name:a1,encode:tp,digest:c1};var _u={};vt(_u,{sha256:()=>Xe,sha512:()=>gs});function bn({name:r,code:t,encode:e}){return new ku(r,t,e)}var ku=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Pe(this.code,e):e.then(n=>Pe(this.code,n))}else throw Error("Unknown type, must be binary type")}};function rp(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Xe=bn({name:"sha2-256",code:18,encode:rp("SHA-256")}),gs=bn({name:"sha2-512",code:19,encode:rp("SHA-512")});function np(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return u1(e,Bu(r),t??Y.encoder);default:return f1(e,Bu(r),t??St.encoder)}}var op=new WeakMap;function Bu(r){let t=op.get(r);if(t==null){let e=new Map;return op.set(r,e),e}return t}var L=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,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:t,multihash:e}=this;if(t!==Jo)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==h1)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Pe(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Jd(t.multihash,n.multihash)}toString(t){return np(this,t)}toJSON(){return{"/":np(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:i,bytes:s}=e;return new r(n,o,i,s??ip(n,o,i.bytes))}else if(e[d1]===!0){let{version:n,multihash:o,code:i}=e,s=wt(o);return r.create(n,i,s)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Jo)throw new Error(`Version 0 CID must use dag-pb (code: ${Jo}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=ip(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Jo,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Ie(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let i=o.subarray(e.multihashSize-e.digestSize),s=new Jn(e.multihashCode,e.digestSize,i,o);return[e.version===0?r.createV0(s):r.createV1(e.codec,s),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=Zo(t.subarray(e));return e+=d,f},o=n(),i=Jo;if(o===18?(o=0,e=0):i=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=e,a=n(),c=n(),l=e+c,u=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=l1(t,e),i=r.decode(o);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Bu(i).set(n,t),i}};function l1(r,t){switch(r[0]){case"Q":{let e=t??Y;return[Y.prefix,e.decode(`${Y.prefix}${r}`)]}case Y.prefix:{let e=t??Y;return[Y.prefix,e.decode(r)]}case St.prefix:{let e=t??St;return[St.prefix,e.decode(r)]}case Kt.prefix:{let e=t??Kt;return[Kt.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function u1(r,t,e){let{prefix:n}=e;if(n!==Y.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let i=e.encode(r).slice(1);return t.set(n,i),i}else return o}function f1(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let i=e.encode(r);return t.set(n,i),i}else return o}var Jo=112,h1=18;function ip(r,t,e){let n=Zn(r),o=n+Zn(t),i=new Uint8Array(o+e.byteLength);return Xn(r,i,0),Xn(t,i,n),i.set(e,o),i}var d1=Symbol.for("@ipld/js-cid/CID");var Qo={...vu,...pu,...Eu,...hu,...du,...gu,...yu,...wu,...xu,...mu},h_={..._u,...Iu};function ap(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var sp=ap("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Tu=ap("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=ne(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),p1={utf8:sp,"utf-8":sp,hex:Qo.base16,latin1:Tu,ascii:Tu,binary:Tu,...Qo},ys=p1;function D(r,t="utf8"){let e=ys[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Cu(r){let t=r??8192,e=t>>>1,n,o=t;return function(s){if(s<1||s>e)return ne(s);o+s>t&&(n=ne(t),o=0);let a=n.subarray(o,o+=s);return o&7&&(o=(o|7)+1),a}}var xn=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Ru(){}var Lu=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},m1=Cu();function g1(r){return globalThis.Buffer!=null?ne(r):m1(r)}var ei=class{len;head;tail;states;constructor(){this.len=0,this.head=new xn(Ru,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new xn(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Pu((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ws,10,ye.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=ye.fromBigInt(t);return this._push(ws,e.length(),e)}uint64Number(t){return this._push(Zl,oe(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=ye.fromBigInt(t).zzEncode();return this._push(ws,e.length(),e)}sint64Number(t){let e=ye.fromNumber(t).zzEncode();return this._push(ws,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Nu,1,t?1:0)}fixed32(t){return this._push(ti,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=ye.fromBigInt(t);return this._push(ti,4,e.lo)._push(ti,4,e.hi)}fixed64Number(t){let e=ye.fromNumber(t);return this._push(ti,4,e.lo)._push(ti,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Ud,4,t)}double(t){return this._push(Md,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Nu,1,0):this.uint32(e)._push(w1,e,t)}string(t){let e=$d(t);return e!==0?this.uint32(e)._push(ru,e,t):this._push(Nu,1,0)}fork(){return this.states=new Lu(this),this.head=this.tail=new xn(Ru,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 xn(Ru,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=g1(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Nu(r,t,e){t[e]=r&255}function y1(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Pu=class extends xn{next;constructor(t,e){super(y1,t,e),this.next=void 0}};function ws(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function ti(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function w1(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(ei.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(b1,t,r),this},ei.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(x1,t,r),this});function b1(r,t,e){t.set(r,e)}function x1(r,t,e){r.length<40?ru(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(D(r),e)}function Du(){return new ei}function ce(r,t){let e=Du();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Qn;(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"})(Qn||(Qn={}));function bs(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function dr(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(i,s){let a=t(i);s.int32(a)},n=function(i){let s=i.int32();return t(s)};return bs("enum",Qn.VARINT,e,n)}function le(r,t){return bs("message",Qn.LENGTH_DELIMITED,r,t)}function cp(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function E1(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function to(r,...t){if(!E1(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function lp(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");cp(r.outputLen),cp(r.blockLen)}function eo(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function up(r,t){to(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var En=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var xs=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),De=(r,t)=>r<<32-t|r>>>t;var G_=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function fp(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function ri(r){return typeof r=="string"&&(r=fp(r)),to(r),r}function Ou(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];to(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}var ro=class{clone(){return this._cloneInto()}},W_={}.toString;function Es(r){let t=n=>r().update(ri(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function no(r=32){if(En&&typeof En.getRandomValues=="function")return En.getRandomValues(new Uint8Array(r));if(En&&typeof En.randomBytes=="function")return En.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function v1(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(e>>o&i),a=Number(e&i),c=n?4:0,l=n?0:4;r.setUint32(t+c,s,n),r.setUint32(t+l,a,n)}var hp=(r,t,e)=>r&t^~r&e,dp=(r,t,e)=>r&t^r&e^t&e,oo=class extends ro{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=xs(this.buffer)}update(t){eo(this);let{view:e,buffer:n,blockLen:o}=this;t=ri(t);let i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=xs(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){eo(this),up(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;e[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>o-s&&(this.process(n,0),s=0);for(let f=s;f<o;f++)e[f]=0;v1(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=xs(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],i)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return t.length=o,t.pos=a,t.finished=i,t.destroyed=s,o%e&&t.buffer.set(n),t}};var vs=BigInt(4294967295),Uu=BigInt(32);function pp(r,t=!1){return t?{h:Number(r&vs),l:Number(r>>Uu&vs)}:{h:Number(r>>Uu&vs)|0,l:Number(r&vs)|0}}function S1(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:i,l:s}=pp(r[o],t);[e[o],n[o]]=[i,s]}return[e,n]}var A1=(r,t)=>BigInt(r>>>0)<<Uu|BigInt(t>>>0),I1=(r,t,e)=>r>>>e,k1=(r,t,e)=>r<<32-e|t>>>e,_1=(r,t,e)=>r>>>e|t<<32-e,B1=(r,t,e)=>r<<32-e|t>>>e,T1=(r,t,e)=>r<<64-e|t>>>e-32,C1=(r,t,e)=>r>>>e-32|t<<64-e,R1=(r,t)=>t,N1=(r,t)=>r,L1=(r,t,e)=>r<<e|t>>>32-e,P1=(r,t,e)=>t<<e|r>>>32-e,D1=(r,t,e)=>t<<e-32|r>>>64-e,O1=(r,t,e)=>r<<e-32|t>>>64-e;function U1(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var F1=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),M1=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,V1=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),H1=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,$1=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),z1=(r,t,e,n,o,i)=>t+e+n+o+i+(r/2**32|0)|0;var q1={fromBig:pp,split:S1,toBig:A1,shrSH:I1,shrSL:k1,rotrSH:_1,rotrSL:B1,rotrBH:T1,rotrBL:C1,rotr32H:R1,rotr32L:N1,rotlSH:L1,rotlSL:P1,rotlBH:D1,rotlBL:O1,add:U1,add3L:F1,add3H:M1,add4L:V1,add4H:H1,add5H:z1,add5L:$1},j=q1;var[K1,G1]=j.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))),Kr=new Uint32Array(80),Gr=new Uint32Array(80),Fu=class extends oo{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:t,Al:e,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:h,Gl:m,Hh:p,Hl:y}=this;return[t,e,n,o,i,s,a,c,l,u,f,d,h,m,p,y]}set(t,e,n,o,i,s,a,c,l,u,f,d,h,m,p,y){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=m|0,this.Hh=p|0,this.Hl=y|0}process(t,e){for(let b=0;b<16;b++,e+=4)Kr[b]=t.getUint32(e),Gr[b]=t.getUint32(e+=4);for(let b=16;b<80;b++){let E=Kr[b-15]|0,k=Gr[b-15]|0,T=j.rotrSH(E,k,1)^j.rotrSH(E,k,8)^j.shrSH(E,k,7),S=j.rotrSL(E,k,1)^j.rotrSL(E,k,8)^j.shrSL(E,k,7),v=Kr[b-2]|0,_=Gr[b-2]|0,z=j.rotrSH(v,_,19)^j.rotrBH(v,_,61)^j.shrSH(v,_,6),F=j.rotrSL(v,_,19)^j.rotrBL(v,_,61)^j.shrSL(v,_,6),U=j.add4L(S,F,Gr[b-7],Gr[b-16]),P=j.add4H(U,T,z,Kr[b-7],Kr[b-16]);Kr[b]=P|0,Gr[b]=U|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:h,Fl:m,Gh:p,Gl:y,Hh:g,Hl:x}=this;for(let b=0;b<80;b++){let E=j.rotrSH(f,d,14)^j.rotrSH(f,d,18)^j.rotrBH(f,d,41),k=j.rotrSL(f,d,14)^j.rotrSL(f,d,18)^j.rotrBL(f,d,41),T=f&h^~f&p,S=d&m^~d&y,v=j.add5L(x,k,S,G1[b],Gr[b]),_=j.add5H(v,g,E,T,K1[b],Kr[b]),z=v|0,F=j.rotrSH(n,o,28)^j.rotrBH(n,o,34)^j.rotrBH(n,o,39),U=j.rotrSL(n,o,28)^j.rotrBL(n,o,34)^j.rotrBL(n,o,39),P=n&i^n&a^i&a,R=o&s^o&c^s&c;g=p|0,x=y|0,p=h|0,y=m|0,h=f|0,m=d|0,{h:f,l:d}=j.add(l|0,u|0,_|0,z|0),l=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let N=j.add3L(z,U,R);n=j.add3H(N,_,F,P),o=N|0}({h:n,l:o}=j.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=j.add(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=j.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=j.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=j.add(this.Eh|0,this.El|0,f|0,d|0),{h,l:m}=j.add(this.Fh|0,this.Fl|0,h|0,m|0),{h:p,l:y}=j.add(this.Gh|0,this.Gl|0,p|0,y|0),{h:g,l:x}=j.add(this.Hh|0,this.Hl|0,g|0,x|0),this.set(n,o,i,s,a,c,l,u,f,d,h,m,p,y,g,x)}roundClean(){Kr.fill(0),Gr.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 mp=Es(()=>new Fu);var As={};vt(As,{aInRange:()=>ue,abool:()=>Oe,abytes:()=>io,bitGet:()=>J1,bitLen:()=>zu,bitMask:()=>oi,bitSet:()=>Q1,bytesToHex:()=>mr,bytesToNumberBE:()=>gr,bytesToNumberLE:()=>jr,concatBytes:()=>yr,createHmacDrbg:()=>qu,ensureBytes:()=>xt,equalBytes:()=>X1,hexToBytes:()=>Sn,hexToNumber:()=>$u,inRange:()=>ni,isBytes:()=>Wr,memoized:()=>In,notImplemented:()=>eE,numberToBytesBE:()=>Yr,numberToBytesLE:()=>An,numberToHexUnpadded:()=>vn,numberToVarBytesBE:()=>Y1,utf8ToBytes:()=>Z1,validateObject:()=>Ze});var Hu=BigInt(0),Ss=BigInt(1),W1=BigInt(2);function Wr(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function io(r){if(!Wr(r))throw new Error("Uint8Array expected")}function Oe(r,t){if(typeof t!="boolean")throw new Error(`${r} must be valid boolean, got "${t}".`)}var j1=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function mr(r){io(r);let t="";for(let e=0;e<r.length;e++)t+=j1[r[e]];return t}function vn(r){let t=r.toString(16);return t.length&1?`0${t}`:t}function $u(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var pr={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function gp(r){if(r>=pr._0&&r<=pr._9)return r-pr._0;if(r>=pr._A&&r<=pr._F)return r-(pr._A-10);if(r>=pr._a&&r<=pr._f)return r-(pr._a-10)}function Sn(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,i=0;o<e;o++,i+=2){let s=gp(r.charCodeAt(i)),a=gp(r.charCodeAt(i+1));if(s===void 0||a===void 0){let c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function gr(r){return $u(mr(r))}function jr(r){return io(r),$u(mr(Uint8Array.from(r).reverse()))}function Yr(r,t){return Sn(r.toString(16).padStart(t*2,"0"))}function An(r,t){return Yr(r,t).reverse()}function Y1(r){return Sn(vn(r))}function xt(r,t,e){let n;if(typeof t=="string")try{n=Sn(t)}catch(i){throw new Error(`${r} must be valid hex string, got "${t}". Cause: ${i}`)}else if(Wr(t))n=Uint8Array.from(t);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(`${r} expected ${e} bytes, got ${o}`);return n}function yr(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];io(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let i=r[n];e.set(i,o),o+=i.length}return e}function X1(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function Z1(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Mu=r=>typeof r=="bigint"&&Hu<=r;function ni(r,t,e){return Mu(r)&&Mu(t)&&Mu(e)&&t<=r&&r<e}function ue(r,t,e,n){if(!ni(t,e,n))throw new Error(`expected valid ${r}: ${e} <= n < ${n}, got ${typeof t} ${t}`)}function zu(r){let t;for(t=0;r>Hu;r>>=Ss,t+=1);return t}function J1(r,t){return r>>BigInt(t)&Ss}function Q1(r,t,e){return r|(e?Ss:Hu)<<BigInt(t)}var oi=r=>(W1<<BigInt(r-1))-Ss,Vu=r=>new Uint8Array(r),yp=r=>Uint8Array.from(r);function qu(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=Vu(r),o=Vu(r),i=0,s=()=>{n.fill(1),o.fill(0),i=0},a=(...f)=>e(o,n,...f),c=(f=Vu())=>{o=a(yp([0]),f),n=a(),f.length!==0&&(o=a(yp([1]),f),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let h=n.slice();d.push(h),f+=n.length}return yr(...d)};return(f,d)=>{s(),c(f);let h;for(;!(h=d(l()));)c();return s(),h}}var tE={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"||Wr(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Ze(r,t,e={}){let n=(o,i,s)=>{let a=tE[i];if(typeof a!="function")throw new Error(`Invalid validator "${i}", expected function`);let c=r[o];if(!(s&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${i}`)};for(let[o,i]of Object.entries(t))n(o,i,!1);for(let[o,i]of Object.entries(e))n(o,i,!0);return r}var eE=()=>{throw new Error("not implemented")};function In(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let i=r(e,...n);return t.set(e,i),i}}var Bt=BigInt(0),ht=BigInt(1),kn=BigInt(2),rE=BigInt(3),Ku=BigInt(4),wp=BigInt(5),bp=BigInt(8),nE=BigInt(9),oE=BigInt(16);function at(r,t){let e=r%t;return e>=Bt?e:t+e}function iE(r,t,e){if(e<=Bt||t<Bt)throw new Error("Expected power/modulo > 0");if(e===ht)return Bt;let n=ht;for(;t>Bt;)t&ht&&(n=n*r%e),r=r*r%e,t>>=ht;return n}function dt(r,t,e){let n=r;for(;t-- >Bt;)n*=n,n%=e;return n}function Is(r,t){if(r===Bt||t<=Bt)throw new Error(`invert: expected positive integers, got n=${r} mod=${t}`);let e=at(r,t),n=t,o=Bt,i=ht,s=ht,a=Bt;for(;e!==Bt;){let l=n/e,u=n%e,f=o-s*l,d=i-a*l;n=e,e=u,o=s,i=a,s=f,a=d}if(n!==ht)throw new Error("invert: does not exist");return at(o,t)}function sE(r){let t=(r-ht)/kn,e,n,o;for(e=r-ht,n=0;e%kn===Bt;e/=kn,n++);for(o=kn;o<r&&iE(o,t,r)!==r-ht;o++);if(n===1){let s=(r+ht)/Ku;return function(c,l){let u=c.pow(l,s);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let i=(e+ht)/kn;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,i),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let h=1;for(let p=a.sqr(d);h<l&&!a.eql(p,a.ONE);h++)p=a.sqr(p);let m=a.pow(u,ht<<BigInt(l-h-1));u=a.sqr(m),f=a.mul(f,m),d=a.mul(d,u),l=h}return f}}function aE(r){if(r%Ku===rE){let t=(r+ht)/Ku;return function(n,o){let i=n.pow(o,t);if(!n.eql(n.sqr(i),o))throw new Error("Cannot find square root");return i}}if(r%bp===wp){let t=(r-wp)/bp;return function(n,o){let i=n.mul(o,kn),s=n.pow(i,t),a=n.mul(o,s),c=n.mul(n.mul(a,kn),s),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%oE,sE(r)}var xp=(r,t)=>(at(r,t)&ht)===ht,cE=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Gu(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=cE.reduce((n,o)=>(n[o]="function",n),t);return Ze(r,e)}function lE(r,t,e){if(e<Bt)throw new Error("Expected power > 0");if(e===Bt)return r.ONE;if(e===ht)return t;let n=r.ONE,o=t;for(;e>Bt;)e&ht&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ht;return n}function uE(r,t){let e=new Array(t.length),n=t.reduce((i,s,a)=>r.is0(s)?i:(e[a]=i,r.mul(i,s)),r.ONE),o=r.inv(n);return t.reduceRight((i,s,a)=>r.is0(s)?i:(e[a]=r.mul(i,e[a]),r.mul(i,s)),o),e}function Wu(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Xr(r,t,e=!1,n={}){if(r<=Bt)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:i}=Wu(r,t);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=aE(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:i,MASK:oi(o),ZERO:Bt,ONE:ht,create:c=>at(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Bt<=c&&c<r},is0:c=>c===Bt,isOdd:c=>(c&ht)===ht,neg:c=>at(-c,r),eql:(c,l)=>c===l,sqr:c=>at(c*c,r),add:(c,l)=>at(c+l,r),sub:(c,l)=>at(c-l,r),mul:(c,l)=>at(c*l,r),pow:(c,l)=>lE(a,c,l),div:(c,l)=>at(c*Is(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Is(c,r),sqrt:n.sqrt||(c=>s(a,c)),invertBatch:c=>uE(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?An(c,i):Yr(c,i),fromBytes:c=>{if(c.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${c.length}`);return e?jr(c):gr(c)}});return Object.freeze(a)}function Ep(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function ju(r){let t=Ep(r);return t+Math.ceil(t/2)}function vp(r,t,e=!1){let n=r.length,o=Ep(t),i=ju(t);if(n<16||n<i||n>1024)throw new Error(`expected ${i}-1024 bytes of input, got ${n}`);let s=e?gr(r):jr(r),a=at(s,t-ht)+ht;return e?An(a,o):Yr(a,o)}var hE=BigInt(0),Yu=BigInt(1),Xu=new WeakMap,Sp=new WeakMap;function ks(r,t){let e=(i,s)=>{let a=s.negate();return i?a:s},n=i=>{if(!Number.isSafeInteger(i)||i<=0||i>t)throw new Error(`Wrong window size=${i}, should be [1..${t}]`)},o=i=>{n(i);let s=Math.ceil(t/i)+1,a=2**(i-1);return{windows:s,windowSize:a}};return{constTimeNegate:e,unsafeLadder(i,s){let a=r.ZERO,c=i;for(;s>hE;)s&Yu&&(a=a.add(c)),c=c.double(),s>>=Yu;return a},precomputeWindow(i,s){let{windows:a,windowSize:c}=o(s),l=[],u=i,f=u;for(let d=0;d<a;d++){f=u,l.push(f);for(let h=1;h<c;h++)f=f.add(u),l.push(f);u=f.double()}return l},wNAF(i,s,a){let{windows:c,windowSize:l}=o(i),u=r.ZERO,f=r.BASE,d=BigInt(2**i-1),h=2**i,m=BigInt(i);for(let p=0;p<c;p++){let y=p*l,g=Number(a&d);a>>=m,g>l&&(g-=h,a+=Yu);let x=y,b=y+Math.abs(g)-1,E=p%2!==0,k=g<0;g===0?f=f.add(e(E,s[x])):u=u.add(e(k,s[b]))}return{p:u,f}},wNAFCached(i,s,a){let c=Sp.get(i)||1,l=Xu.get(i);return l||(l=this.precomputeWindow(i,c),c!==1&&Xu.set(i,a(l))),this.wNAF(c,l,s)},setWindowSize(i,s){n(s),Sp.set(i,s),Xu.delete(i)}}}function _s(r,t,e,n){if(!Array.isArray(e)||!Array.isArray(n)||n.length!==e.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((u,f)=>{if(!t.isValid(u))throw new Error(`wrong scalar at index ${f}`)}),e.forEach((u,f)=>{if(!(u instanceof r))throw new Error(`wrong point at index ${f}`)});let o=zu(BigInt(e.length)),i=o>12?o-3:o>4?o-2:o?2:1,s=(1<<i)-1,a=new Array(s+1).fill(r.ZERO),c=Math.floor((t.BITS-1)/i)*i,l=r.ZERO;for(let u=c;u>=0;u-=i){a.fill(r.ZERO);for(let d=0;d<n.length;d++){let h=n[d],m=Number(h>>BigInt(u)&BigInt(s));a[m]=a[m].add(e[d])}let f=r.ZERO;for(let d=a.length-1,h=r.ZERO;d>0;d--)h=h.add(a[d]),f=f.add(h);if(l=l.add(f),u!==0)for(let d=0;d<i;d++)l=l.double()}return l}function ii(r){return Gu(r.Fp),Ze(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Wu(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Ue=BigInt(0),fe=BigInt(1),Bs=BigInt(2),dE=BigInt(8),pE={zip215:!0};function mE(r){let t=ii(r);return Ze(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Ap(r){let t=mE(r),{Fp:e,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,l=Bs<<BigInt(a*8)-fe,u=e.create,f=Xr(t.n,t.nBitLength),d=t.uvRatio||((I,A)=>{try{return{isValid:!0,value:e.sqrt(I*e.inv(A))}}catch{return{isValid:!1,value:Ue}}}),h=t.adjustScalarBytes||(I=>I),m=t.domain||((I,A,C)=>{if(Oe("phflag",C),A.length||C)throw new Error("Contexts/pre-hash are not supported");return I});function p(I,A){ue("coordinate "+I,A,Ue,l)}function y(I){if(!(I instanceof b))throw new Error("ExtendedPoint expected")}let g=In((I,A)=>{let{ex:C,ey:V,ez:K}=I,G=I.is0();A==null&&(A=G?dE:e.inv(K));let J=u(C*A),et=u(V*A),Q=u(K*A);if(G)return{x:Ue,y:fe};if(Q!==fe)throw new Error("invZ was invalid");return{x:J,y:et}}),x=In(I=>{let{a:A,d:C}=t;if(I.is0())throw new Error("bad point: ZERO");let{ex:V,ey:K,ez:G,et:J}=I,et=u(V*V),Q=u(K*K),st=u(G*G),lt=u(st*st),Rt=u(et*A),Nt=u(st*u(Rt+Q)),Dt=u(lt+u(C*u(et*Q)));if(Nt!==Dt)throw new Error("bad point: equation left != right (1)");let jt=u(V*K),kt=u(G*J);if(jt!==kt)throw new Error("bad point: equation left != right (2)");return!0});class b{constructor(A,C,V,K){this.ex=A,this.ey=C,this.ez=V,this.et=K,p("x",A),p("y",C),p("z",V),p("t",K),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(A){if(A instanceof b)throw new Error("extended point not allowed");let{x:C,y:V}=A||{};return p("x",C),p("y",V),new b(C,V,fe,u(C*V))}static normalizeZ(A){let C=e.invertBatch(A.map(V=>V.ez));return A.map((V,K)=>V.toAffine(C[K])).map(b.fromAffine)}static msm(A,C){return _s(b,f,A,C)}_setWindowSize(A){T.setWindowSize(this,A)}assertValidity(){x(this)}equals(A){y(A);let{ex:C,ey:V,ez:K}=this,{ex:G,ey:J,ez:et}=A,Q=u(C*et),st=u(G*K),lt=u(V*et),Rt=u(J*K);return Q===st&&lt===Rt}is0(){return this.equals(b.ZERO)}negate(){return new b(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:A}=t,{ex:C,ey:V,ez:K}=this,G=u(C*C),J=u(V*V),et=u(Bs*u(K*K)),Q=u(A*G),st=C+V,lt=u(u(st*st)-G-J),Rt=Q+J,Nt=Rt-et,Dt=Q-J,jt=u(lt*Nt),kt=u(Rt*Dt),ee=u(lt*Dt),lr=u(Nt*Rt);return new b(jt,kt,lr,ee)}add(A){y(A);let{a:C,d:V}=t,{ex:K,ey:G,ez:J,et}=this,{ex:Q,ey:st,ez:lt,et:Rt}=A;if(C===BigInt(-1)){let Ed=u((G-K)*(st+Q)),vd=u((G+K)*(st-Q)),ql=u(vd-Ed);if(ql===Ue)return this.double();let Sd=u(J*Bs*Rt),Ad=u(et*Bs*lt),Id=Ad+Sd,kd=vd+Ed,_d=Ad-Sd,Cb=u(Id*ql),Rb=u(kd*_d),Nb=u(Id*_d),Lb=u(ql*kd);return new b(Cb,Rb,Lb,Nb)}let Nt=u(K*Q),Dt=u(G*st),jt=u(et*V*Rt),kt=u(J*lt),ee=u((K+G)*(Q+st)-Nt-Dt),lr=kt-jt,Ko=kt+jt,Go=u(Dt-C*Nt),kb=u(ee*lr),_b=u(Ko*Go),Bb=u(ee*Go),Tb=u(lr*Ko);return new b(kb,_b,Tb,Bb)}subtract(A){return this.add(A.negate())}wNAF(A){return T.wNAFCached(this,A,b.normalizeZ)}multiply(A){let C=A;ue("scalar",C,fe,n);let{p:V,f:K}=this.wNAF(C);return b.normalizeZ([V,K])[0]}multiplyUnsafe(A){let C=A;return ue("scalar",C,Ue,n),C===Ue?k:this.equals(k)||C===fe?this:this.equals(E)?this.wNAF(C).p:T.unsafeLadder(this,C)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return T.unsafeLadder(this,n).is0()}toAffine(A){return g(this,A)}clearCofactor(){let{h:A}=t;return A===fe?this:this.multiplyUnsafe(A)}static fromHex(A,C=!1){let{d:V,a:K}=t,G=e.BYTES;A=xt("pointHex",A,G),Oe("zip215",C);let J=A.slice(),et=A[G-1];J[G-1]=et&-129;let Q=jr(J),st=C?l:e.ORDER;ue("pointHex.y",Q,Ue,st);let lt=u(Q*Q),Rt=u(lt-fe),Nt=u(V*lt-K),{isValid:Dt,value:jt}=d(Rt,Nt);if(!Dt)throw new Error("Point.fromHex: invalid y coordinate");let kt=(jt&fe)===fe,ee=(et&128)!==0;if(!C&&jt===Ue&&ee)throw new Error("Point.fromHex: x=0 and x_0=1");return ee!==kt&&(jt=u(-jt)),b.fromAffine({x:jt,y:Q})}static fromPrivateKey(A){return _(A).point}toRawBytes(){let{x:A,y:C}=this.toAffine(),V=An(C,e.BYTES);return V[V.length-1]|=A&fe?128:0,V}toHex(){return mr(this.toRawBytes())}}b.BASE=new b(t.Gx,t.Gy,fe,u(t.Gx*t.Gy)),b.ZERO=new b(Ue,fe,fe,Ue);let{BASE:E,ZERO:k}=b,T=ks(b,a*8);function S(I){return at(I,n)}function v(I){return S(jr(I))}function _(I){let A=a;I=xt("private key",I,A);let C=xt("hashed private key",i(I),2*A),V=h(C.slice(0,A)),K=C.slice(A,2*A),G=v(V),J=E.multiply(G),et=J.toRawBytes();return{head:V,prefix:K,scalar:G,point:J,pointBytes:et}}function z(I){return _(I).pointBytes}function F(I=new Uint8Array,...A){let C=yr(...A);return v(i(m(C,xt("context",I),!!o)))}function U(I,A,C={}){I=xt("message",I),o&&(I=o(I));let{prefix:V,scalar:K,pointBytes:G}=_(A),J=F(C.context,V,I),et=E.multiply(J).toRawBytes(),Q=F(C.context,et,G,I),st=S(J+Q*K);ue("signature.s",st,Ue,n);let lt=yr(et,An(st,e.BYTES));return xt("result",lt,a*2)}let P=pE;function R(I,A,C,V=P){let{context:K,zip215:G}=V,J=e.BYTES;I=xt("signature",I,2*J),A=xt("message",A),G!==void 0&&Oe("zip215",G),o&&(A=o(A));let et=jr(I.slice(J,2*J)),Q,st,lt;try{Q=b.fromHex(C,G),st=b.fromHex(I.slice(0,J),G),lt=E.multiplyUnsafe(et)}catch{return!1}if(!G&&Q.isSmallOrder())return!1;let Rt=F(K,st.toRawBytes(),Q.toRawBytes(),A);return st.add(Q.multiplyUnsafe(Rt)).subtract(lt).clearCofactor().equals(b.ZERO)}return E._setWindowSize(8),{CURVE:t,getPublicKey:z,sign:U,verify:R,ExtendedPoint:b,utils:{getExtendedPublicKey:_,randomPrivateKey:()=>s(e.BYTES),precompute(I=8,A=b.BASE){return A._setWindowSize(I),A.multiply(BigInt(3)),A}}}}var Zu=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ip=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),gB=BigInt(0),gE=BigInt(1),kp=BigInt(2),yB=BigInt(3),yE=BigInt(5),wE=BigInt(8);function bE(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),i=Zu,a=r*r%i*r%i,c=dt(a,kp,i)*a%i,l=dt(c,gE,i)*r%i,u=dt(l,yE,i)*l%i,f=dt(u,t,i)*u%i,d=dt(f,e,i)*f%i,h=dt(d,n,i)*d%i,m=dt(h,o,i)*h%i,p=dt(m,o,i)*h%i,y=dt(p,t,i)*u%i;return{pow_p_5_8:dt(y,kp,i)*r%i,b2:a}}function xE(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function EE(r,t){let e=Zu,n=at(t*t*t,e),o=at(n*n*t,e),i=bE(r*o).pow_p_5_8,s=at(r*n*i,e),a=at(t*s*s,e),c=s,l=at(s*Ip,e),u=a===r,f=a===at(-r,e),d=a===at(-r*Ip,e);return u&&(s=c),(f||d)&&(s=l),xp(s,e)&&(s=at(-s,e)),{isValid:u||f,value:s}}var vE=Xr(Zu,void 0,!0),SE={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:vE,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:wE,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:mp,randomBytes:no,adjustScalarBytes:xE,uvRatio:EE},_p=Ap(SE);var Ts=32;function Bp(r,t,e){return _p.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var Cs=class{type="Ed25519";raw;constructor(t){this.raw=Ju(t,Ts)}toMultihash(){return bt.digest(so(this))}toCID(){return L.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}verify(t,e){return Bp(this.raw,e,t)}};function Qu(r){return r=Ju(r,Ts),new Cs(r)}function Ju(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new gt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Tt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(Tt||(Tt={}));var tf;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(tf||(tf={}));(function(r){r.codec=()=>dr(tf)})(Tt||(Tt={}));var Je;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),Tt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=Tt.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>ce(e,r.codec()),r.decode=(e,n)=>ie(e,r.codec(),n)})(Je||(Je={}));var ef;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),Tt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.Type=Tt.codec().decode(e);break}case 2:{i.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>ce(e,r.codec()),r.decode=(e,n)=>ie(e,r.codec(),n)})(ef||(ef={}));var mi={};vt(mi,{MAX_RSA_KEY_SIZE:()=>va,generateRSAKeyPair:()=>km,jwkToJWKKeyPair:()=>_m,jwkToPkcs1:()=>VE,jwkToPkix:()=>ff,jwkToRSAPrivateKey:()=>Im,pkcs1ToJwk:()=>vm,pkcs1ToRSAPrivateKey:()=>Am,pkixToJwk:()=>Sm,pkixToRSAPublicKey:()=>hf});var IE=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]),Zr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Jr=new Uint32Array(64),rf=class extends oo{constructor(){super(64,32,8,!1),this.A=Zr[0]|0,this.B=Zr[1]|0,this.C=Zr[2]|0,this.D=Zr[3]|0,this.E=Zr[4]|0,this.F=Zr[5]|0,this.G=Zr[6]|0,this.H=Zr[7]|0}get(){let{A:t,B:e,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,e,n,o,i,s,a,c]}set(t,e,n,o,i,s,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)Jr[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Jr[f-15],h=Jr[f-2],m=De(d,7)^De(d,18)^d>>>3,p=De(h,17)^De(h,19)^h>>>10;Jr[f]=p+Jr[f-7]+m+Jr[f-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=De(a,6)^De(a,11)^De(a,25),h=u+d+hp(a,c,l)+IE[f]+Jr[f]|0,p=(De(n,2)^De(n,13)^De(n,22))+dp(n,o,i)|0;u=l,l=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+p|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,i,s,a,c,l,u)}roundClean(){Jr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ao=Es(()=>new rf);var tt=Ot(Rp());function _n(r,t){let e=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)e+=r[r.length-1-n]*Math.pow(2,t*n);return e}function Qr(r,t,e=-1){let n=e,o=r,i=0,s=Math.pow(2,t);for(let a=1;a<8;a++){if(r<s){let c;if(n<0)c=new ArrayBuffer(a),i=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),i=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*t);l[i-u-1]=Math.floor(o/f),o-=l[i-u-1]*f}return c}s*=Math.pow(2,t)}return new ArrayBuffer(0)}function Ls(...r){let t=0,e=0;for(let i of r)t+=i.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let i of r)o.set(i,e),e+=i.length;return o}function of(){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 t=new ArrayBuffer(this.valueHex.byteLength),e=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)e[a]=0;e[0]=r[0]&128;let n=_n(e,8),o=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)i[a]=r[a];return i[0]&=127,_n(i,8)-n}function Np(r){let t=r<0?r*-1:r,e=128;for(let n=1;n<8;n++){if(t<=e){if(r<0){let s=e-t,a=Qr(s,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Qr(t,8,n),i=new Uint8Array(o);if(i[0]&128){let s=o.slice(0),a=new Uint8Array(s);o=new ArrayBuffer(o.byteLength+1),i=new Uint8Array(o);for(let c=0;c<s.byteLength;c++)i[c+1]=a[c];i[0]=0}return o}e*=Math.pow(2,8)}return new ArrayBuffer(0)}function Lp(r,t){if(r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}function he(r,t){let e=r.toString(10);if(t<e.length)return"";let n=t-e.length,o=new Array(n);for(let s=0;s<n;s++)o[s]="0";return o.join("").concat(e)}var VB=Math.log(2);function Ps(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function sf(r){let t=0,e=0;for(let o=0;o<r.length;o++){let i=r[o];t+=i.byteLength}let n=new Uint8Array(t);for(let o=0;o<r.length;o++){let i=r[o];n.set(new Uint8Array(i),e),e+=i.byteLength}return n.buffer}function vr(r,t,e,n){return t instanceof Uint8Array?t.byteLength?e<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-e-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 ai=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return sf(this.items)}},si=[new Uint8Array([1])],Pp="0123456789";var ho="",Fe=new ArrayBuffer(0),af=new Uint8Array(0),ci="EndOfContent",Op="OCTET STRING",Up="BIT STRING";function Sr(r){var t;return t=class extends r{constructor(...n){var o;super(...n);let i=n[0]||{};this.isHexOnly=(o=i.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=i.valueHex?tt.BufferSourceConverter.toUint8Array(i.valueHex):af}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,i){let s=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!vr(this,s,o,i))return-1;let a=o+i;return this.valueHexView=s.subarray(o,a),this.valueHexView.length?(this.blockLength=i,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",Fe)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:tt.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var br=class{constructor({blockLength:t=0,error:e=ho,warnings:n=[],valueBeforeDecode:o=af}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=tt.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:tt.Convert.ToHex(this.valueBeforeDecodeView)}}};br.NAME="baseBlock";var Gt=class extends br{fromBER(t,e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,e){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Gt.NAME="valueBlock";var Ds=class extends Sr(br){constructor({idBlock:t={}}={}){var e,n,o,i;super(),t?(this.isHexOnly=(e=t.isHexOnly)!==null&&e!==void 0?e:!1,this.valueHexView=t.valueHex?tt.BufferSourceConverter.toUint8Array(t.valueHex):af,this.tagClass=(n=t.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=t.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(i=t.isConstructed)!==null&&i!==void 0?i:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let e=0;switch(this.tagClass){case 1:e|=0;break;case 2:e|=64;break;case 3:e|=128;break;case 4:e|=192;break;default:return this.error="Unknown tag class",Fe}if(this.isConstructed&&(e|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!t){let i=this.tagNumber;i&=31,e|=i,o[0]=e}return o.buffer}if(!this.isHexOnly){let o=Qr(this.tagNumber,7),i=new Uint8Array(o),s=o.byteLength,a=new Uint8Array(s+1);if(a[0]=e|31,!t){for(let c=0;c<s-1;c++)a[c+1]=i[c]|128;a[s]=i[s-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=e|31,!t){let o=this.valueHexView;for(let i=0;i<o.length-1;i++)n[i+1]=o[i]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(t,e,n){let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;let i=o.subarray(e,e+n);if(i.length===0)return this.error="Zero buffer length",-1;switch(i[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(i[0]&32)===32,this.isHexOnly=!1;let a=i[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),u=255;for(;i[c]&128;){if(l[c-1]=i[c]&127,c++,c>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(c===u){u+=255;let d=new Uint8Array(u);for(let h=0;h<l.length;h++)d[h]=l[h];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=i[c]&127;let f=new Uint8Array(c);for(let d=0;d<c;d++)f[d]=l[d];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=_n(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 e+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Ds.NAME="identificationBlock";var Os=class extends br{constructor({lenBlock:t={}}={}){var e,n,o;super(),this.isIndefiniteForm=(e=t.isIndefiniteForm)!==null&&e!==void 0?e:!1,this.longFormUsed=(n=t.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=t.length)!==null&&o!==void 0?o:0}fromBER(t,e,n){let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;let i=o.subarray(e,e+n);if(i.length===0)return this.error="Zero buffer length",-1;if(i[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=i[0]===128,this.isIndefiniteForm)return this.blockLength=1,e+this.blockLength;if(this.longFormUsed=!!(i[0]&128),this.longFormUsed===!1)return this.length=i[0],this.blockLength=1,e+this.blockLength;let s=i[0]&127;if(s>8)return this.error="Too big integer",-1;if(s+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let a=e+1,c=o.subarray(a,a+s);return c[s-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=_n(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=s+1,e+this.blockLength}toBER(t=!1){let e,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=128),e;if(this.longFormUsed){let o=Qr(this.length,8);if(o.byteLength>127)return this.error="Too big length",Fe;if(e=new ArrayBuffer(o.byteLength+1),t)return e;let i=new Uint8Array(o);n=new Uint8Array(e),n[0]=o.byteLength|128;for(let s=0;s<o.byteLength;s++)n[s+1]=i[s];return e}return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=this.length),e}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Os.NAME="lengthBlock";var M={},Ut=class extends br{constructor({name:t=ho,optional:e=!1,primitiveSchema:n,...o}={},i){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new Ds(o),this.lenBlock=new Os(o),this.valueBlock=i?new i(o):new Gt(o)}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,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(t,e){let n=e||new ai;e||Fp(this);let o=this.idBlock.toBER(t);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,n),n.write(new ArrayBuffer(2));else{let i=this.valueBlock.toBER(t);this.lenBlock.length=i.byteLength;let s=this.lenBlock.toBER(t);n.write(s),n.write(i)}return e?Fe:n.final()}toJSON(){let t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():tt.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${tt.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;let e=this.toBER(),n=t.toBER();return Lp(e,n)}};Ut.NAME="BaseBlock";function Fp(r){if(r instanceof M.Constructed)for(let t of r.valueBlock.value)Fp(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Us=class extends Ut{constructor({value:t=ho,...e}={},n){super(e,n),t&&this.fromString(t)}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,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}'`}};Us.NAME="BaseStringBlock";var Fs=class extends Sr(Gt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};Fs.NAME="PrimitiveValueBlock";var Mp,Ms=class extends Ut{constructor(t={}){super(t,Fs),this.idBlock.isConstructed=!1}};Mp=Ms;M.Primitive=Mp;Ms.NAME="PRIMITIVE";function PE(r,t){if(r instanceof t)return r;let e=new t;return e.idBlock=r.idBlock,e.lenBlock=r.lenBlock,e.warnings=r.warnings,e.valueBeforeDecodeView=r.valueBeforeDecodeView,e}function ba(r,t=0,e=r.length){let n=t,o=new Ut({},Gt),i=new br;if(!vr(i,r,t,e))return o.error=i.error,{offset:-1,result:o};if(!r.subarray(t,t+e).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,t,e);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=a,e-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,t,e),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=a,e-=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=Ut;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=M.EndOfContent;break;case 1:c=M.Boolean;break;case 2:c=M.Integer;break;case 3:c=M.BitString;break;case 4:c=M.OctetString;break;case 5:c=M.Null;break;case 6:c=M.ObjectIdentifier;break;case 10:c=M.Enumerated;break;case 12:c=M.Utf8String;break;case 13:c=M.RelativeObjectIdentifier;break;case 14:c=M.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=M.Sequence;break;case 17:c=M.Set;break;case 18:c=M.NumericString;break;case 19:c=M.PrintableString;break;case 20:c=M.TeletexString;break;case 21:c=M.VideotexString;break;case 22:c=M.IA5String;break;case 23:c=M.UTCTime;break;case 24:c=M.GeneralizedTime;break;case 25:c=M.GraphicString;break;case 26:c=M.VisibleString;break;case 27:c=M.GeneralString;break;case 28:c=M.UniversalString;break;case 29:c=M.CharacterString;break;case 30:c=M.BmpString;break;case 31:c=M.DATE;break;case 32:c=M.TimeOfDay;break;case 33:c=M.DateTime;break;case 34:c=M.Duration;break;default:{let l=o.idBlock.isConstructed?new M.Constructed:new M.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?M.Constructed:M.Primitive}return o=PE(o,c),a=o.fromBER(r,t,o.lenBlock.isIndefiniteForm?e:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function cf(r){if(!r.byteLength){let t=new Ut({},Gt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return ba(tt.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function DE(r,t){return r?1:t}var Qe=class extends Gt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;if(this.valueBeforeDecodeView=o.subarray(e,e+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),e;let i=e;for(;DE(this.isIndefiniteForm,n)>0;){let s=ba(o,i,n);if(s.offset===-1)return this.error=s.result.error,this.warnings.concat(s.result.warnings),-1;if(i=s.offset,this.blockLength+=s.result.blockLength,n-=s.result.blockLength,this.value.push(s.result),this.isIndefiniteForm&&s.result.constructor.NAME===ci)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===ci?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(t,e){let n=e||new ai;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?Fe:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};Qe.NAME="ConstructedValueBlock";var Vp,tn=class extends Ut{constructor(t={}){super(t,Qe),this.idBlock.isConstructed=!0}fromBER(t,e,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(t,e,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 t=[];for(let n of this.valueBlock.value)t.push(n.toString("ascii").split(`
4
4
  `).map(o=>` ${o}`).join(`
5
- `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
6
- ${e.join(`
7
- `)}`:`${t} :`}};ap=Qr;F.Constructed=ap;Qr.NAME="CONSTRUCTED";var Ks=class extends Ge{fromBER(e,t,n){return t}toBER(e){return Ut}};Ks.override="EndOfContentValueBlock";var cp,qs=class extends Ue{constructor(e={}){super(e,Ks),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};cp=qs;F.EndOfContent=cp;qs.NAME=ii;var lp,en=class extends Ue{constructor(e={}){super(e,Ge),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}`}};lp=en;F.Null=lp;en.NAME="NULL";var Gs=class extends Sr(Ge){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=J.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=J.BufferSourceConverter.toUint8Array(e);return vr(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,yu.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Gs.NAME="BooleanValueBlock";var up,Ws=class extends Ue{constructor(e={}){super(e,Gs),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}`}};up=Ws;F.Boolean=up;Ws.NAME="BOOLEAN";var js=class extends Sr(tr){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=tr.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let i=0;i<this.value.length;i++){let s=this.value[i].constructor.NAME;if(s===ii){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(s!==np)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?tr.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};js.NAME="OctetStringValueBlock";var fp,xr=class r extends Ue{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},js),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let s=va(i,0,i.byteLength);s.offset!==-1&&s.offset===n&&(this.valueBlock.value=[s.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?Qr.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${J.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 J.BufferSourceConverter.concat(e)}};fp=xr;F.OctetString=fp;xr.NAME=np;var Ys=class extends Sr(tr){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=tr.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===ii){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==op)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let i=J.BufferSourceConverter.toUint8Array(e);if(!vr(this,i,t,n))return-1;let s=i.subarray(t,t+n);if(this.unusedBits=s[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=s.subarray(1);try{if(a.byteLength){let c=va(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,t+n}toBER(e,t){if(this.isConstructed)return tr.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Ut;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}}};Ys.NAME="BitStringValueBlock";var hp,ho=class extends Ue{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ys),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 Qr.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)}`}}};hp=ho;F.BitString=hp;ho.NAME=op;var dp;function cE(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l=0,f=c<s?s:c,u=0;for(let p=f;p>=0;p--,u++){switch(!0){case u<a.length:l=i[s-u]+a[c-u]+t[0];break;default:l=i[s-u]+t[0]}switch(t[0]=l/10,!0){case u>=i.length:i=Us(new Uint8Array([l%10]),i);break;default:i[s-u]=l%10}}return t[0]>0&&(i=Us(t,i)),i}function rp(r){if(r>=ni.length)for(let e=ni.length;e<=r;e++){let t=new Uint8Array([0]),n=ni[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let i=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=i[0]/10,n[o]=i[0]%10}t[0]>0&&(n=Us(t,n)),ni.push(n)}return ni[r]}function lE(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l,f=0;for(let u=c;u>=0;u--,f++)switch(l=i[s-f]-a[c-f]-t,!0){case l<0:t=1,i[s-f]=l+10;break;default:t=0,i[s-f]=l}if(t>0)for(let u=s-c+1;u>=0;u--,f++)if(l=i[s-f]-t,l<0)t=1,i[s-f]=l+10;else{t=0,i[s-f]=l;break}return i.slice()}var si=class extends Sr(Ge){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=yu.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Qd(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let i=this.fromBER(e,t,n);if(i===-1)return i;let s=this.valueHexView;return s[0]===0&&s[1]&128?this.valueHexView=s.subarray(1):o!==0&&s.length<o&&(o-s.length>1&&(o=s.length+1),this.valueHexView=s.subarray(o-s.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,i=this.valueHexView,s="",a=!1;for(let c=i.byteLength-1;c>=0;c--){o=i[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=lE(rp(n),t),s="-";break;default:t=cE(t,rp(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(s+=tp.charAt(t[c]));return a===!1&&(s+=tp.charAt(0)),s}};dp=si;si.NAME="IntegerValueBlock";Object.defineProperty(dp.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var pp,Ae=class r extends Ue{constructor(e={}){super(e,si),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Fs(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Fs();let t=BigInt(e),n=new oi,o=t.toString(16).replace(/^-/,""),i=new Uint8Array(J.Convert.FromHex(o));if(t<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${J.Convert.ToHex(a)}`)+t,f=J.BufferSourceConverter.toUint8Array(J.Convert.FromHex(l.toString(16)));f[0]|=128,n.write(f)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};pp=Ae;F.Integer=pp;Ae.NAME="INTEGER";var mp,Xs=class extends Ae{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};mp=Xs;F.Enumerated=mp;Xs.NAME="ENUMERATED";var ai=class extends Sr(Ge){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=J.BufferSourceConverter.toUint8Array(e);if(!vr(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Rn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Fs();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=Jr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Ut;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n}toString(){let e="";if(this.isHexOnly)e=J.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};ai.NAME="sidBlock";var Zs=class extends Ge{constructor({value:e=po,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new ai;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,Ut;t.push(o)}return wu(t)}fromString(e){this.value=[];let t=0,n=0,o="",i=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,i){let s=this.value[0],a=0;switch(s.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;s.valueDec=c+a,i=!1}else{let s=new ai;if(o>Number.MAX_SAFE_INTEGER){Fs();let a=BigInt(o);s.valueBigInt=a}else if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return;this.value.length||(s.isFirstSid=!0,i=!0),this.value.push(s)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Zs.NAME="ObjectIdentifierValueBlock";var gp,Pt=class extends Ue{constructor(e={}){super(e,Zs),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()}}};gp=Pt;F.ObjectIdentifier=gp;Pt.NAME="OBJECT IDENTIFIER";var ci=class extends Sr(br){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=J.BufferSourceConverter.toUint8Array(e);if(!vr(this,o,t,n))return-1;let i=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Rn(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let t=Jr(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",Ut;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),i=t.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n.buffer}toString(){let e="";return this.isHexOnly?e=J.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};ci.NAME="relativeSidBlock";var Js=class extends Ge{constructor({value:e=po,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let i=new ci;if(o=i.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let i=this.value[o].toBER(e);if(i.byteLength===0)return this.error=this.value[o].error,Ut;n.push(i)}return wu(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let i=new ci;if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Js.NAME="RelativeObjectIdentifierValueBlock";var yp,Qs=class extends Ue{constructor(e={}){super(e,Js),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()}}};yp=Qs;F.RelativeObjectIdentifier=yp;Qs.NAME="RelativeObjectIdentifier";var wp,Te=class extends Qr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};wp=Te;F.Sequence=wp;Te.NAME="SEQUENCE";var bp,ea=class extends Qr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};bp=ea;F.Set=bp;ea.NAME="SET";var ta=class extends Sr(Ge){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=po}toJSON(){return{...super.toJSON(),value:this.value}}};ta.NAME="StringValueBlock";var ra=class extends ta{};ra.NAME="SimpleStringValueBlock";var Je=class extends Hs{constructor({...e}={}){super(e,ra)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,J.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Je.NAME="SIMPLE STRING";var na=class extends Je{fromBuffer(e){this.valueBlock.valueHexView=J.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=J.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=J.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(J.Convert.FromUtf8String(e)),this.valueBlock.value=e}};na.NAME="Utf8StringValueBlock";var xp,Er=class extends na{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};xp=Er;F.Utf8String=xp;Er.NAME="UTF8String";var oa=class extends Je{fromBuffer(e){this.valueBlock.value=J.Convert.ToUtf16String(e),this.valueBlock.valueHexView=J.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(J.Convert.FromUtf16String(e))}};oa.NAME="BmpStringValueBlock";var Ep,ia=class extends oa{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Ep=ia;F.BmpString=Ep;ia.NAME="BMPString";var sa=class extends Je{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let i=Jr(e.charCodeAt(o),8),s=new Uint8Array(i);if(s.length>4)continue;let a=4-s.length;for(let c=s.length-1;c>=0;c--)n[o*4+c+a]=s[c]}this.valueBlock.value=e}};sa.NAME="UniversalStringValueBlock";var vp,aa=class extends sa{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};vp=aa;F.UniversalString=vp;aa.NAME="UniversalString";var Sp,ca=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Sp=ca;F.NumericString=Sp;ca.NAME="NumericString";var Ap,la=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Ap=la;F.PrintableString=Ap;la.NAME="PrintableString";var _p,ua=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};_p=ua;F.TeletexString=_p;ua.NAME="TeletexString";var Ip,fa=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Ip=fa;F.VideotexString=Ip;fa.NAME="VideotexString";var Rp,ha=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Rp=ha;F.IA5String=Rp;ha.NAME="IA5String";var kp,da=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};kp=da;F.GraphicString=kp;da.NAME="GraphicString";var Bp,li=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Bp=li;F.VisibleString=Bp;li.NAME="VisibleString";var Tp,pa=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Tp=pa;F.GeneralString=Tp;pa.NAME="GeneralString";var Np,ma=class extends Je{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Np=ma;F.CharacterString=Np;ma.NAME="CharacterString";var Cp,ui=class extends li{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,J.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=st(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=st(this.month,2),t[2]=st(this.day,2),t[3]=st(this.hour,2),t[4]=st(this.minute,2),t[5]=st(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}}};Cp=ui;F.UTCTime=Cp;ui.NAME="UTCTime";var Lp,ga=class extends ui{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",i=0,s,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let 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,p=n.indexOf("+"),h="";if(p===-1&&(p=n.indexOf("-"),u=-1),p!==-1){if(h=n.substring(p+1),n=n.substring(0,p),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let m=parseInt(h.substring(0,2),10);if(isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");if(a=u*m,h.length===4){if(m=parseInt(h.substring(2,4),10),isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");c=u*m}}}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");i=u.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=60*i;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(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=60*i;this.second=Math.floor(u),u=1e3*(u-this.second),this.millisecond=Math.floor(u)}break;case o.length===14:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let u=1e3*i;this.millisecond=Math.floor(u)}break;default:throw new Error("Wrong input string for conversion")}let f=s.exec(o);if(f===null)throw new Error("Wrong input string for conversion");for(let u=1;u<f.length;u++)switch(u){case 1:this.year=parseInt(f[u],10);break;case 2:this.month=parseInt(f[u],10);break;case 3:this.day=parseInt(f[u],10);break;case 4:this.hour=parseInt(f[u],10)+a;break;case 5:this.minute=parseInt(f[u],10)+c;break;case 6:this.second=parseInt(f[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(st(this.year,4)),t.push(st(this.month,2)),t.push(st(this.day,2)),t.push(st(this.hour,2)),t.push(st(this.minute,2)),t.push(st(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(st(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Lp=ga;F.GeneralizedTime=Lp;ga.NAME="GeneralizedTime";var Op,ya=class extends Er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Op=ya;F.DATE=Op;ya.NAME="DATE";var Dp,wa=class extends Er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Dp=wa;F.TimeOfDay=Dp;wa.NAME="TimeOfDay";var Pp,ba=class extends Er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Pp=ba;F.DateTime=Pp;ba.NAME="DateTime";var Up,xa=class extends Er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Up=xa;F.Duration=Up;xa.NAME="Duration";var Fp,Ea=class extends Er{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Fp=Ea;F.TIME=Fp;Ea.NAME="TIME";function fE(r){let{result:e}=mo(r),t=e.valueBlock.value;return{n:G(rr(t[1].toBigInt()),"base64url"),e:G(rr(t[2].toBigInt()),"base64url"),d:G(rr(t[3].toBigInt()),"base64url"),p:G(rr(t[4].toBigInt()),"base64url"),q:G(rr(t[5].toBigInt()),"base64url"),dp:G(rr(t[6].toBigInt()),"base64url"),dq:G(rr(t[7].toBigInt()),"base64url"),qi:G(rr(t[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function hE(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 N("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new Te({value:[new Ae({value:0}),Ae.fromBigInt(nr(P(r.n,"base64url"))),Ae.fromBigInt(nr(P(r.e,"base64url"))),Ae.fromBigInt(nr(P(r.d,"base64url"))),Ae.fromBigInt(nr(P(r.p,"base64url"))),Ae.fromBigInt(nr(P(r.q,"base64url"))),Ae.fromBigInt(nr(P(r.dp,"base64url"))),Ae.fromBigInt(nr(P(r.dq,"base64url"))),Ae.fromBigInt(nr(P(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function dE(r){let{result:e}=mo(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:G(rr(t[0].toBigInt()),"base64url"),e:G(rr(t[1].toBigInt()),"base64url")}}function pE(r){if(r.n==null||r.e==null)throw new N("JWK was missing components","ERR_INVALID_PARAMETERS");let t=new Te({value:[new Te({value:[new Pt({value:"1.2.840.113549.1.1.1"}),new en]}),new ho({valueHex:new Te({value:[Ae.fromBigInt(nr(P(r.n,"base64url"))),Ae.fromBigInt(nr(P(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function rr(r){let e=r.toString(16);e.length%2>0&&(e=`0${e}`);let t=e.length/2,n=new Uint8Array(t),o=0,i=0;for(;o<t;)n[o]=parseInt(e.slice(i,i+2),16),o+=1,i+=2;return n}function nr(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 mE=16,xu=32,Eu=1e4;async function gE(r,e){let t=Ze.get(),o=new Te({value:[new Ae({value:0}),new Te({value:[new Pt({value:"1.2.840.113549.1.1.1"}),new en]}),new xr({valueHex:r.marshal()})]}).toBER(),i=new Uint8Array(o,0,o.byteLength),s=er(mE),a=await mu(io,e,s,{c:Eu,dkLen:xu}),c=er(16),l=await t.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),f=await t.subtle.encrypt({name:"AES-CBC",iv:c},l,i),u=new Te({value:[new xr({valueHex:s}),new Ae({value:Eu}),new Ae({value:xu}),new Te({value:[new Pt({value:"1.2.840.113549.2.11"}),new en]})]}),p=new Te({value:[new Pt({value:"1.2.840.113549.1.5.13"}),new Te({value:[new Te({value:[new Pt({value:"1.2.840.113549.1.5.12"}),u]}),new Te({value:[new Pt({value:"2.16.840.1.101.3.4.1.42"}),new xr({valueHex:c})]})]})]}),m=new Te({value:[p,new xr({valueHex:f})]}).toBER(),d=new Uint8Array(m,0,m.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...G(d,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
8
- `)}async function yE(r,e){let t=Ze.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=P(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=mo(o),{iv:s,salt:a,iterations:c,keySize:l,cipherText:f}=wE(i),u=await mu(io,e,a,{c,dkLen:l}),p=await t.subtle.importKey("raw",u,"AES-CBC",!1,["decrypt"]),h=fi(await t.subtle.decrypt({name:"AES-CBC",iv:s},p,f)),{result:m}=mo(h);n=Mp(m)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=P(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:i}=mo(o);n=Mp(i)}else throw new N("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return vu(n)}function wE(r){let e=r.valueBlock.value[0];if(e.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new N("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 N("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let i=n.valueBlock.value[1],s=fi(i.valueBlock.value[0].getValue()),a=Eu,c=xu;if(i.valueBlock.value.length===3)a=Number(i.valueBlock.value[1].toBigInt()),c=Number(i.valueBlock.value[2].toBigInt());else if(i.valueBlock.value.length===2)throw new N("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],f=l.valueBlock.value[0].toString();if(f!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(f!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(f!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new N("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let u=fi(l.valueBlock.value[1].getValue());return{cipherText:fi(r.valueBlock.value[1].getValue()),salt:s,iterations:a,keySize:c,iv:u}}function Mp(r){return fi(r.valueBlock.value[2].getValue())}function fi(r){return new Uint8Array(r,0,r.byteLength)}async function Vp(r){let e=await Ze.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 zp(e);return{privateKey:t[0],publicKey:t[1]}}async function Su(r){let t=[await Ze.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await bE(r)],n=await zp({privateKey:t[0],publicKey:t[1]});return{privateKey:n[0],publicKey:n[1]}}async function Hp(r,e){let t=await Ze.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ze.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function $p(r,e,t){let n=await Ze.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ze.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function zp(r){if(r.privateKey==null||r.publicKey==null)throw new N("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ze.get().subtle.exportKey("jwk",r.privateKey),Ze.get().subtle.exportKey("jwk",r.publicKey)])}async function bE(r){return Ze.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 Sa(r){if(r.kty!=="RSA")throw new N("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new N("invalid key modulus","ERR_INVALID_KEY_MODULUS");return P(r.n,"base64url").length*8}var di=8192,hi=class{_key;constructor(e){this._key=e}verify(e,t){return $p(this._key,t,e)}marshal(){return tn.jwkToPkix(this._key)}get bytes(){return Jt.encode({Type:pe.RSA,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Rt(e)?e.then(({bytes:t})=>t):e.bytes}},go=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return er(16)}sign(e){return Hp(this._key,e)}get public(){if(this._publicKey==null)throw new N("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new hi(this._publicKey)}marshal(){return tn.jwkToPkcs1(this._key)}get bytes(){return Qt.encode({Type:pe.RSA,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Rt(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return G(e,"base58btc")}async export(e,t="pkcs-8"){if(t==="pkcs-8")return tn.exportToPem(this,e);if(t==="libp2p-key")return lo(this.bytes,e);throw new N(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function vu(r){let e=tn.pkcs1ToJwk(r);if(Sa(e)>di)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await Su(e);return new go(t.privateKey,t.publicKey)}function EE(r){let e=tn.pkixToJwk(r);if(Sa(e)>di)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new hi(e)}async function vE(r){if(Sa(r)>di)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Su(r);return new go(e.privateKey,e.publicKey)}async function SE(r){if(r>di)throw new N("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await Vp(r);return new go(e.privateKey,e.publicKey)}var Bu={};Se(Bu,{Secp256k1PrivateKey:()=>mi,Secp256k1PublicKey:()=>pi,generateKeyPair:()=>PE,unmarshalSecp256k1PrivateKey:()=>OE,unmarshalSecp256k1PublicKey:()=>DE});var AE=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]),rn=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),nn=new Uint32Array(64),_u=class extends oo{constructor(){super(64,32,8,!1),this.A=rn[0]|0,this.B=rn[1]|0,this.C=rn[2]|0,this.D=rn[3]|0,this.E=rn[4]|0,this.F=rn[5]|0,this.G=rn[6]|0,this.H=rn[7]|0}get(){let{A:e,B:t,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[e,t,n,o,i,s,a,c]}set(e,t,n,o,i,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let u=0;u<16;u++,t+=4)nn[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let p=nn[u-15],h=nn[u-2],m=Ot(p,7)^Ot(p,18)^p>>>3,d=Ot(h,17)^Ot(h,19)^h>>>10;nn[u]=d+nn[u-7]+m+nn[u-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:f}=this;for(let u=0;u<64;u++){let p=Ot(a,6)^Ot(a,11)^Ot(a,25),h=f+p+kd(a,c,l)+AE[u]+nn[u]|0,d=(Ot(n,2)^Ot(n,13)^Ot(n,22))+Bd(n,o,i)|0;f=l,l=c,c=a,a=s+h|0,s=i,i=o,o=n,n=h+d|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,f=f+this.H|0,this.set(n,o,i,s,a,c,l,f)}roundClean(){nn.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Kp=Ss(()=>new _u);function _E(r){let e=ei(r);Zt(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:IE,hexToBytes:RE}=Is,kn={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(r){let{Err:e}=kn;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:IE(n),l:r.subarray(t+2)}},toSig(r){let{Err:e}=kn,t=typeof r=="string"?RE(r):r;so(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:i}=kn._parseInt(t.subarray(2)),{d:s,l:a}=kn._parseInt(i);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s}},hexFromSig(r){let e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{let f=l.toString(16);return f.length&1?`0${f}`:f},n=e(t(r.s)),o=e(t(r.r)),i=n.length/2,s=o.length/2,a=t(i),c=t(s);return`30${t(s+i+4)}02${c}${o}02${a}${n}`}},Ar=BigInt(0),Bt=BigInt(1),ZB=BigInt(2),qp=BigInt(3),JB=BigInt(4);function kE(r){let e=_E(r),{Fp:t}=e,n=e.toBytes||((m,d,y)=>{let g=d.toAffine();return mr(Uint8Array.from([4]),t.toBytes(g.x),t.toBytes(g.y))}),o=e.fromBytes||(m=>{let d=m.subarray(1),y=t.fromBytes(d.subarray(0,t.BYTES)),g=t.fromBytes(d.subarray(t.BYTES,2*t.BYTES));return{x:y,y:g}});function i(m){let{a:d,b:y}=e,g=t.sqr(m),b=t.mul(g,m);return t.add(t.add(b,t.mul(m,d)),y)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function s(m){return typeof m=="bigint"&&Ar<m&&m<e.n}function a(m){if(!s(m))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(m){let{allowedPrivateKeyLengths:d,nByteLength:y,wrapPrivateKey:g,n:b}=e;if(d&&typeof m!="bigint"){if(Yr(m)&&(m=dr(m)),typeof m!="string"||!d.includes(m.length))throw new Error("Invalid key");m=m.padStart(y*2,"0")}let x;try{x=typeof m=="bigint"?m:pr(be("private key",m,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof m}`)}return g&&(x=ce(x,b)),a(x),x}let l=new Map;function f(m){if(!(m instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(d,y,g){if(this.px=d,this.py=y,this.pz=g,d==null||!t.isValid(d))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(g==null||!t.isValid(g))throw new Error("z required")}static fromAffine(d){let{x:y,y:g}=d||{};if(!d||!t.isValid(y)||!t.isValid(g))throw new Error("invalid affine point");if(d instanceof u)throw new Error("projective point not allowed");let b=x=>t.eql(x,t.ZERO);return b(y)&&b(g)?u.ZERO:new u(y,g,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){let y=t.invertBatch(d.map(g=>g.pz));return d.map((g,b)=>g.toAffine(y[b])).map(u.fromAffine)}static fromHex(d){let y=u.fromAffine(o(be("pointHex",d)));return y.assertValidity(),y}static fromPrivateKey(d){return u.BASE.multiply(c(d))}_setWindowSize(d){this._WINDOW_SIZE=d,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:d,y}=this.toAffine();if(!t.isValid(d)||!t.isValid(y))throw new Error("bad point: x or y not FE");let g=t.sqr(y),b=i(d);if(!t.eql(g,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:d}=this.toAffine();if(t.isOdd)return!t.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){f(d);let{px:y,py:g,pz:b}=this,{px:x,py:E,pz:v}=d,_=t.eql(t.mul(y,v),t.mul(x,b)),S=t.eql(t.mul(g,v),t.mul(E,b));return _&&S}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){let{a:d,b:y}=e,g=t.mul(y,qp),{px:b,py:x,pz:E}=this,v=t.ZERO,_=t.ZERO,S=t.ZERO,A=t.mul(b,b),L=t.mul(x,x),U=t.mul(E,E),O=t.mul(b,x);return O=t.add(O,O),S=t.mul(b,E),S=t.add(S,S),v=t.mul(d,S),_=t.mul(g,U),_=t.add(v,_),v=t.sub(L,_),_=t.add(L,_),_=t.mul(v,_),v=t.mul(O,v),S=t.mul(g,S),U=t.mul(d,U),O=t.sub(A,U),O=t.mul(d,O),O=t.add(O,S),S=t.add(A,A),A=t.add(S,A),A=t.add(A,U),A=t.mul(A,O),_=t.add(_,A),U=t.mul(x,E),U=t.add(U,U),A=t.mul(U,O),v=t.sub(v,A),S=t.mul(U,L),S=t.add(S,S),S=t.add(S,S),new u(v,_,S)}add(d){f(d);let{px:y,py:g,pz:b}=this,{px:x,py:E,pz:v}=d,_=t.ZERO,S=t.ZERO,A=t.ZERO,L=e.a,U=t.mul(e.b,qp),O=t.mul(y,x),$=t.mul(g,E),C=t.mul(b,v),ee=t.add(y,g),k=t.add(x,E);ee=t.mul(ee,k),k=t.add(O,$),ee=t.sub(ee,k),k=t.add(y,b);let T=t.add(x,v);return k=t.mul(k,T),T=t.add(O,C),k=t.sub(k,T),T=t.add(g,b),_=t.add(E,v),T=t.mul(T,_),_=t.add($,C),T=t.sub(T,_),A=t.mul(L,k),_=t.mul(U,C),A=t.add(_,A),_=t.sub($,A),A=t.add($,A),S=t.mul(_,A),$=t.add(O,O),$=t.add($,O),C=t.mul(L,C),k=t.mul(U,k),$=t.add($,C),C=t.sub(O,C),C=t.mul(L,C),k=t.add(k,C),O=t.mul($,k),S=t.add(S,O),O=t.mul(T,k),_=t.mul(ee,_),_=t.sub(_,O),O=t.mul(ee,$),A=t.mul(T,A),A=t.add(A,O),new u(_,S,A)}subtract(d){return this.add(d.negate())}is0(){return this.equals(u.ZERO)}wNAF(d){return h.wNAFCached(this,l,d,y=>{let g=t.invertBatch(y.map(b=>b.pz));return y.map((b,x)=>b.toAffine(g[x])).map(u.fromAffine)})}multiplyUnsafe(d){let y=u.ZERO;if(d===Ar)return y;if(a(d),d===Bt)return this;let{endo:g}=e;if(!g)return h.unsafeLadder(this,d);let{k1neg:b,k1:x,k2neg:E,k2:v}=g.splitScalar(d),_=y,S=y,A=this;for(;x>Ar||v>Ar;)x&Bt&&(_=_.add(A)),v&Bt&&(S=S.add(A)),A=A.double(),x>>=Bt,v>>=Bt;return b&&(_=_.negate()),E&&(S=S.negate()),S=new u(t.mul(S.px,g.beta),S.py,S.pz),_.add(S)}multiply(d){a(d);let y=d,g,b,{endo:x}=e;if(x){let{k1neg:E,k1:v,k2neg:_,k2:S}=x.splitScalar(y),{p:A,f:L}=this.wNAF(v),{p:U,f:O}=this.wNAF(S);A=h.constTimeNegate(E,A),U=h.constTimeNegate(_,U),U=new u(t.mul(U.px,x.beta),U.py,U.pz),g=A.add(U),b=L.add(O)}else{let{p:E,f:v}=this.wNAF(y);g=E,b=v}return u.normalizeZ([g,b])[0]}multiplyAndAddUnsafe(d,y,g){let b=u.BASE,x=(v,_)=>_===Ar||_===Bt||!v.equals(b)?v.multiplyUnsafe(_):v.multiply(_),E=x(this,y).add(x(d,g));return E.is0()?void 0:E}toAffine(d){let{px:y,py:g,pz:b}=this,x=this.is0();d==null&&(d=x?t.ONE:t.inv(b));let E=t.mul(y,d),v=t.mul(g,d),_=t.mul(b,d);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(_,t.ONE))throw new Error("invZ was invalid");return{x:E,y:v}}isTorsionFree(){let{h:d,isTorsionFree:y}=e;if(d===Bt)return!0;if(y)return y(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:d,clearCofactor:y}=e;return d===Bt?this:y?y(u,this):this.multiplyUnsafe(e.h)}toRawBytes(d=!0){return this.assertValidity(),n(u,this,d)}toHex(d=!0){return dr(this.toRawBytes(d))}}u.BASE=new u(e.Gx,e.Gy,t.ONE),u.ZERO=new u(t.ZERO,t.ONE,t.ZERO);let p=e.nBitLength,h=Bs(u,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:s}}function BE(r){let e=ei(r);return Zt(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Gp(r){let e=BE(r),{Fp:t,n}=e,o=t.BYTES+1,i=2*t.BYTES+1;function s(k){return Ar<k&&k<t.ORDER}function a(k){return ce(k,n)}function c(k){return Rs(k,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:f,weierstrassEquation:u,isWithinCurveOrder:p}=kE({...e,toBytes(k,T,q){let B=T.toAffine(),I=t.toBytes(B.x),M=mr;return q?M(Uint8Array.from([T.hasEvenY()?2:3]),I):M(Uint8Array.from([4]),I,t.toBytes(B.y))},fromBytes(k){let T=k.length,q=k[0],B=k.subarray(1);if(T===o&&(q===2||q===3)){let I=pr(B);if(!s(I))throw new Error("Point is not on curve");let M=u(I),K;try{K=t.sqrt(M)}catch(Z){let ie=Z instanceof Error?": "+Z.message:"";throw new Error("Point is not on curve"+ie)}let W=(K&Bt)===Bt;return(q&1)===1!==W&&(K=t.neg(K)),{x:I,y:K}}else if(T===i&&q===4){let I=t.fromBytes(B.subarray(0,t.BYTES)),M=t.fromBytes(B.subarray(t.BYTES,2*t.BYTES));return{x:I,y:M}}else throw new Error(`Point of length ${T} was invalid. Expected ${o} compressed bytes or ${i} uncompressed bytes`)}}),h=k=>dr(Zr(k,e.nByteLength));function m(k){let T=n>>Bt;return k>T}function d(k){return m(k)?a(-k):k}let y=(k,T,q)=>pr(k.slice(T,q));class g{constructor(T,q,B){this.r=T,this.s=q,this.recovery=B,this.assertValidity()}static fromCompact(T){let q=e.nByteLength;return T=be("compactSignature",T,q*2),new g(y(T,0,q),y(T,q,2*q))}static fromDER(T){let{r:q,s:B}=kn.toSig(be("DER",T));return new g(q,B)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(T){return new g(this.r,this.s,T)}recoverPublicKey(T){let{r:q,s:B,recovery:I}=this,M=S(be("msgHash",T));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");let K=I===2||I===3?q+e.n:q;if(K>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let W=I&1?"03":"02",X=l.fromHex(W+h(K)),Z=c(K),ie=a(-M*Z),Q=a(B*Z),te=l.BASE.multiplyAndAddUnsafe(X,ie,Q);if(!te)throw new Error("point at infinify");return te.assertValidity(),te}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Sn(this.toDERHex())}toDERHex(){return kn.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Sn(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let b={isValidPrivateKey(k){try{return f(k),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let k=au(e.n);return Vd(e.randomBytes(k),e.n)},precompute(k=8,T=l.BASE){return T._setWindowSize(k),T.multiply(BigInt(3)),T}};function x(k,T=!0){return l.fromPrivateKey(k).toRawBytes(T)}function E(k){let T=Yr(k),q=typeof k=="string",B=(T||q)&&k.length;return T?B===o||B===i:q?B===2*o||B===2*i:k instanceof l}function v(k,T,q=!0){if(E(k))throw new Error("first arg must be private key");if(!E(T))throw new Error("second arg must be public key");return l.fromHex(T).multiply(f(k)).toRawBytes(q)}let _=e.bits2int||function(k){let T=pr(k),q=k.length*8-e.nBitLength;return q>0?T>>BigInt(q):T},S=e.bits2int_modN||function(k){return a(_(k))},A=Qo(e.nBitLength);function L(k){if(typeof k!="bigint")throw new Error("bigint expected");if(!(Ar<=k&&k<A))throw new Error(`bigint expected < 2^${e.nBitLength}`);return Zr(k,e.nByteLength)}function U(k,T,q=O){if(["recovered","canonical"].some(ye=>ye in q))throw new Error("sign() legacy options not supported");let{hash:B,randomBytes:I}=e,{lowS:M,prehash:K,extraEntropy:W}=q;M==null&&(M=!0),k=be("msgHash",k),K&&(k=be("prehashed msgHash",B(k)));let X=S(k),Z=f(T),ie=[L(Z),L(X)];if(W!=null&&W!==!1){let ye=W===!0?I(t.BYTES):W;ie.push(be("extraEntropy",ye))}let Q=mr(...ie),te=X;function ve(ye){let Ce=_(ye);if(!p(Ce))return;let Le=c(Ce),Ie=l.BASE.multiply(Ce).toAffine(),$e=a(Ie.x);if($e===Ar)return;let cr=a(Le*a(te+$e*Z));if(cr===Ar)return;let yn=(Ie.x===$e?0:2)|Number(Ie.y&Bt),Ho=cr;return M&&m(cr)&&(Ho=d(cr),yn^=1),new g($e,Ho,yn)}return{seed:Q,k2sig:ve}}let O={lowS:e.lowS,prehash:!1},$={lowS:e.lowS,prehash:!1};function C(k,T,q=O){let{seed:B,k2sig:I}=U(k,T,q),M=e;return nu(M.hash.outputLen,M.nByteLength,M.hmac)(B,I)}l.BASE._setWindowSize(8);function ee(k,T,q,B=$){let I=k;if(T=be("msgHash",T),q=be("publicKey",q),"strict"in B)throw new Error("options.strict was renamed to lowS");let{lowS:M,prehash:K}=B,W,X;try{if(typeof I=="string"||Yr(I))try{W=g.fromDER(I)}catch(Ie){if(!(Ie instanceof kn.Err))throw Ie;W=g.fromCompact(I)}else if(typeof I=="object"&&typeof I.r=="bigint"&&typeof I.s=="bigint"){let{r:Ie,s:$e}=I;W=new g(Ie,$e)}else throw new Error("PARSE");X=l.fromHex(q)}catch(Ie){if(Ie.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(M&&W.hasHighS())return!1;K&&(T=e.hash(T));let{r:Z,s:ie}=W,Q=S(T),te=c(ie),ve=a(Q*te),ye=a(Z*te),Ce=l.BASE.multiplyAndAddUnsafe(X,ve,ye)?.toAffine();return Ce?a(Ce.x)===Z:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:v,sign:C,verify:ee,ProjectivePoint:l,Signature:g,utils:b}}function TE(r){return{hash:r,hmac:(e,...t)=>ri(r,e,vs(...t)),randomBytes:no}}function Wp(r,e){let t=n=>Gp({...r,...TE(n)});return Object.freeze({...t(e),create:t})}var Xp=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),jp=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),NE=BigInt(1),Iu=BigInt(2),Yp=(r,e)=>(r+e/Iu)/e;function CE(r){let e=Xp,t=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,f=l*l*r%e,u=de(f,t,e)*f%e,p=de(u,t,e)*f%e,h=de(p,Iu,e)*l%e,m=de(h,o,e)*h%e,d=de(m,i,e)*m%e,y=de(d,a,e)*d%e,g=de(y,c,e)*y%e,b=de(g,a,e)*d%e,x=de(b,t,e)*f%e,E=de(x,s,e)*m%e,v=de(E,n,e)*l%e,_=de(v,Iu,e);if(!Ru.eql(Ru.sqr(_),r))throw new Error("Cannot find square root");return _}var Ru=ks(Xp,void 0,void 0,{sqrt:CE}),Ft=Wp({a:BigInt(0),b:BigInt(7),Fp:Ru,n:jp,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=jp,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-NE*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=t,s=BigInt("0x100000000000000000000000000000000"),a=Yp(i*r,e),c=Yp(-n*r,e),l=ce(r-a*t-c*o,e),f=ce(-a*n-c*i,e),u=l>s,p=f>s;if(u&&(l=e-l),p&&(f=e-f),l>s||f>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:u,k1:l,k2neg:p,k2:f}}}},Kp),a8=BigInt(0);var c8=Ft.ProjectivePoint;function Zp(){return Ft.utils.randomPrivateKey()}function Jp(r,e){let t=Re.digest(e instanceof Uint8Array?e:e.subarray());if(Rt(t))return t.then(({digest:n})=>Ft.sign(n,r).toDERRawBytes()).catch(n=>{throw new N(String(n),"ERR_INVALID_INPUT")});try{return Ft.sign(t.digest,r).toDERRawBytes()}catch(n){throw new N(String(n),"ERR_INVALID_INPUT")}}function Qp(r,e,t){let n=Re.digest(t instanceof Uint8Array?t:t.subarray());if(Rt(n))return n.then(({digest:o})=>Ft.verify(e,o,r)).catch(o=>{throw new N(String(o),"ERR_INVALID_INPUT")});try{return Ft.verify(e,n.digest,r)}catch(o){throw new N(String(o),"ERR_INVALID_INPUT")}}function em(r){return Ft.ProjectivePoint.fromHex(r).toRawBytes(!0)}function tm(r){try{Ft.getPublicKey(r,!0)}catch(e){throw new N(String(e),"ERR_INVALID_PRIVATE_KEY")}}function ku(r){try{Ft.ProjectivePoint.fromHex(r)}catch(e){throw new N(String(e),"ERR_INVALID_PUBLIC_KEY")}}function rm(r){try{return Ft.getPublicKey(r,!0)}catch(e){throw new N(String(e),"ERR_INVALID_PRIVATE_KEY")}}var pi=class{_key;constructor(e){ku(e),this._key=e}verify(e,t){return Qp(this._key,t,e)}marshal(){return em(this._key)}get bytes(){return Jt.encode({Type:pe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}async hash(){let e=Re.digest(this.bytes),t;return Rt(e)?{bytes:t}=await e:t=e.bytes,t}},mi=class{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??rm(e),tm(this._key),ku(this._publicKey)}sign(e){return Jp(this._key,e)}get public(){return new pi(this._publicKey)}marshal(){return this._key}get bytes(){return Qt.encode({Type:pe.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return ne(this.bytes,e.bytes)}hash(){let e=Re.digest(this.bytes);return Rt(e)?e.then(({bytes:t})=>t):e.bytes}async id(){let e=await this.public.hash();return G(e,"base58btc")}async export(e,t="libp2p-key"){if(t==="libp2p-key")return lo(this.bytes,e);throw new N(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function OE(r){return new mi(r)}function DE(r){return new pi(r)}async function PE(){let r=Zp();return new mi(r)}var Bn={rsa:Au,ed25519:pu,secp256k1:Bu};function nm(r){let e=Object.keys(Bn).join(" / ");return new N(`invalid or unsupported key type ${r}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Tu(r){let e=Jt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case pe.RSA:return Bn.rsa.unmarshalRsaPublicKey(t);case pe.Ed25519:return Bn.ed25519.unmarshalEd25519PublicKey(t);case pe.Secp256k1:return Bn.secp256k1.unmarshalSecp256k1PublicKey(t);default:throw nm(e.Type??"unknown")}}async function om(r){let e=Qt.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case pe.RSA:return Bn.rsa.unmarshalRsaPrivateKey(t);case pe.Ed25519:return Bn.ed25519.unmarshalEd25519PrivateKey(t);case pe.Secp256k1:return Bn.secp256k1.unmarshalSecp256k1PrivateKey(t);default:throw nm(e.Type??"RSA")}}var mt=re(fm(),1);mt.default.formatters.b=r=>r==null?"undefined":ge.baseEncode(r);mt.default.formatters.t=r=>r==null?"undefined":Pe.baseEncode(r);mt.default.formatters.m=r=>r==null?"undefined":it.baseEncode(r);mt.default.formatters.p=r=>r==null?"undefined":r.toString();mt.default.formatters.c=r=>r==null?"undefined":r.toString();mt.default.formatters.k=r=>r==null?"undefined":r.toString();mt.default.formatters.a=r=>r==null?"undefined":r.toString();function YE(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 hm(){return{forComponent(r){return Qe(r)}}}function Qe(r){let e=YE(`${r}:trace`);return mt.default.enabled(`${r}:trace`)&&mt.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,mt.default)(`${r}:trace`)),Object.assign((0,mt.default)(r),{error:(0,mt.default)(`${r}:error`),trace:e})}var Lu=re(pm(),1);var wi=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Ou=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},mm=r=>globalThis.DOMException===void 0?new Ou(r):new DOMException(r),gm=r=>{let e=r.reason===void 0?mm("This operation was aborted."):r.reason;return e instanceof Error?e:mm(e)};function bi(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,s,c=new Promise((l,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:p}=e;p.aborted&&f(gm(p)),p.addEventListener("abort",()=>{f(gm(p))})}if(t===Number.POSITIVE_INFINITY){r.then(l,f);return}let u=new wi;s=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(p){f(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?f(o):(u.message=o??`Promise timed out after ${t} milliseconds`,f(u))},t),(async()=>{try{l(await r)}catch(p){f(p)}})()}).finally(()=>{c.clear()});return c.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},c}function Du(r,e,t){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;t(r[s],e)<=0?(n=++s,o-=i+1):o=i}return n}var xi=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=Du(this.#e,n,(i,s)=>s.priority-i.priority);this.#e.splice(o,0,n)}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var at=class extends Lu.default{#e;#n;#s=0;#u;#g;#a=0;#f;#c;#r;#t;#i=0;#m;#l;#h;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:xi,...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.#n=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#u=e.intervalCap,this.#g=e.interval,this.#r=new e.queueClass,this.#t=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#h=e.throwOnTimeout===!0,this.#l=e.autoStart===!1}get#b(){return this.#n||this.#s<this.#u}get#d(){return this.#i<this.#m}#x(){this.#i--,this.#w(),this.emit("next")}#E(){this.#p(),this.#A(),this.#c=void 0}get#y(){let e=Date.now();if(this.#f===void 0){let t=this.#a-e;if(t<0)this.#s=this.#e?this.#i:0;else return this.#c===void 0&&(this.#c=setTimeout(()=>{this.#E()},t)),!0}return!1}#w(){if(this.#r.size===0)return this.#f&&clearInterval(this.#f),this.#f=void 0,this.emit("empty"),this.#i===0&&this.emit("idle"),!1;if(!this.#l){let e=!this.#y;if(this.#b&&this.#d){let t=this.#r.dequeue();return t?(this.emit("active"),t(),e&&this.#A(),!0):!1}}return!1}#A(){this.#n||this.#f!==void 0||(this.#f=setInterval(()=>{this.#p()},this.#g),this.#a=Date.now()+this.#g)}#p(){this.#s===0&&this.#i===0&&this.#f&&(clearInterval(this.#f),this.#f=void 0),this.#s=this.#e?this.#i:0,this.#R()}#R(){for(;this.#w(););}get concurrency(){return this.#m}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.#m=e,this.#R()}async#k(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.#h,...t},new Promise((n,o)=>{this.#r.enqueue(async()=>{this.#i++,this.#s++;try{t.signal?.throwIfAborted();let i=e({signal:t.signal});t.timeout&&(i=bi(Promise.resolve(i),{milliseconds:t.timeout})),t.signal&&(i=Promise.race([i,this.#k(t.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof wi&&!t.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#x()}},t),this.emit("add"),this.#w()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#l?(this.#l=!1,this.#R(),this):this}pause(){this.#l=!0}clear(){this.#r=new this.#t}async onEmpty(){this.#r.size!==0&&await this.#v("empty")}async onSizeLessThan(e){this.#r.size<e||await this.#v("next",()=>this.#r.size<e)}async onIdle(){this.#i===0&&this.#r.size===0||await this.#v("idle")}async#v(e,t){return new Promise(n=>{let o=()=>{t&&!t()||(this.off(e,o),n())};this.on(e,o)})}get size(){return this.#r.size}sizeBy(e){return this.#r.filter(e).length}get pending(){return this.#i}get isPaused(){return this.#l}};function ka(r){let e=[ct.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Pu=60;function Ba(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:ct[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:ct[e.type],TTL:e.TTL??e.ttl??Pu,data:e.data instanceof Uint8Array?G(e.data):e.data}))}}var JE=4;function Uu(r,e={}){let t=new at({concurrency:e.queryConcurrency??JE});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),ka(o.types).forEach(a=>{i.append("type",ct[a])}),o.onProgress?.(new V("dns:query",{detail:n}));let s=await t.add(async()=>{let a=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=Ba(await a.json());return o.onProgress?.(new V("dns:response",{detail:c})),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function ym(){return[Uu("https://cloudflare-dns.com/dns-query"),Uu("https://dns.google/resolve")]}var bm=re(Fu(),1);var Mu=class{lru;constructor(e){this.lru=(0,bm.default)(e)}get(e,t){let n=!0,o=[];for(let i of t){let s=this.getAnswers(e,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return Ba({answers:o})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:ct[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(t.TTL??Pu)*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 xm(r){return new Mu(r)}var QE=1e3,Ta=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=xm(e.cacheSize??QE),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["."]=ym())}async query(e,t={}){let n=ka(t.types),o=t.cached!==!1?this.cache.get(e,n):void 0;if(o!=null)return t.onProgress?.(new V("dns:cache",{detail:o})),o;let i=`${e.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let f of l.Answer)this.cache.add(e,f);return l}catch(l){a.push(l),t.onProgress?.(new V("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var ct;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(ct||(ct={}));function Ei(r={}){return new Ta(r)}var ev=["string","number","bigint","symbol"],tv=["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 Em(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(ev.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(rv(r))return"Buffer";let t=nv(r);return t||"Object"}function rv(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function nv(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(tv.includes(e))return e}var w=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};w.uint=new w(0,"uint",!0);w.negint=new w(1,"negint",!0);w.bytes=new w(2,"bytes",!0);w.string=new w(3,"string",!0);w.array=new w(4,"array",!1);w.map=new w(5,"map",!1);w.tag=new w(6,"tag",!1);w.float=new w(7,"float",!0);w.false=new w(7,"false",!0);w.true=new w(7,"true",!0);w.null=new w(7,"null",!0);w.undefined=new w(7,"undefined",!0);w.break=new w(7,"break",!0);var R=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 xo=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",ov=new TextDecoder,iv=new TextEncoder;function Na(r){return xo&&globalThis.Buffer.isBuffer(r)}function vi(r){return r instanceof Uint8Array?Na(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var _m=xo?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):Sm(r,e,t):(r,e,t)=>t-e>64?ov.decode(r.subarray(e,t)):Sm(r,e,t),Ca=xo?r=>r.length>64?globalThis.Buffer.from(r):vm(r):r=>r.length>64?iv.encode(r):vm(r),or=r=>Uint8Array.from(r),Eo=xo?(r,e,t)=>Na(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),Im=xo?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),vi(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},Rm=xo?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function km(r,e){if(Na(r)&&Na(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 vm(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 Sm(r,e,t){let n=[];for(;e<t;){let o=r[e],i=null,s=o>239?4:o>223?3:o>191?2:1;if(e+s<=t){let a,c,l,f;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[e+1],(a&192)===128&&(f=(o&31)<<6|a&63,f>127&&(i=f));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(f=(o&15)<<12|(a&63)<<6|c&63,f>2047&&(f<55296||f>57343)&&(i=f));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(f=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,f>65535&&f<1114112&&(i=f))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),e+=s}return Vu(n)}var Am=4096;function Vu(r){let e=r.length;if(e<=Am)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=Am));return t}var sv=256,Si=class{constructor(e=sv){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=Rm(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=Eo(n,0,this.cursor)}else t=Im(this.chunks,this.cursor);return e&&this.reset(),t}};var H="CBOR decode error:",_r="CBOR encode error:",Ai=[];Ai[23]=1;Ai[24]=2;Ai[25]=3;Ai[26]=5;Ai[27]=9;function Ir(r,e,t){if(r.length-e<t)throw new Error(`${H} not enough data for type`)}var Ne=[24,256,65536,4294967296,BigInt("18446744073709551616")];function gt(r,e,t){Ir(r,e,1);let n=r[e];if(t.strict===!0&&n<Ne[0])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function yt(r,e,t){Ir(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Ne[1])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function wt(r,e,t){Ir(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Ne[2])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);return n}function bt(r,e,t){Ir(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&i<Ne[3])throw new Error(`${H} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(t.allowBigInt===!0)return i;throw new Error(`${H} integers outside of the safe integer range are not supported`)}function Bm(r,e,t,n){return new R(w.uint,gt(r,e+1,n),2)}function Tm(r,e,t,n){return new R(w.uint,yt(r,e+1,n),3)}function Nm(r,e,t,n){return new R(w.uint,wt(r,e+1,n),5)}function Cm(r,e,t,n){return new R(w.uint,bt(r,e+1,n),9)}function Tt(r,e){return Fe(r,0,e.value)}function Fe(r,e,t){if(t<Ne[0]){let n=Number(t);r.push([e|n])}else if(t<Ne[1]){let n=Number(t);r.push([e|24,n])}else if(t<Ne[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Ne[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<Ne[4]){let o=[e|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${H} encountered BigInt larger than allowable range`)}}Tt.encodedSize=function(e){return Fe.encodedSize(e.value)};Fe.encodedSize=function(e){return e<Ne[0]?1:e<Ne[1]?2:e<Ne[2]?3:e<Ne[3]?5:9};Tt.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function Lm(r,e,t,n){return new R(w.negint,-1-gt(r,e+1,n),2)}function Om(r,e,t,n){return new R(w.negint,-1-yt(r,e+1,n),3)}function Dm(r,e,t,n){return new R(w.negint,-1-wt(r,e+1,n),5)}var Hu=BigInt(-1),Pm=BigInt(1);function Um(r,e,t,n){let o=bt(r,e+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new R(w.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${H} integers outside of the safe integer range are not supported`);return new R(w.negint,Hu-BigInt(o),9)}function La(r,e){let t=e.value,n=typeof t=="bigint"?t*Hu-Pm:t*-1-1;Fe(r,e.type.majorEncoded,n)}La.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*Hu-Pm:t*-1-1;return n<Ne[0]?1:n<Ne[1]?2:n<Ne[2]?3:n<Ne[3]?5:9};La.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function _i(r,e,t,n){Ir(r,e,t+n);let o=Eo(r,e+t,e+t+n);return new R(w.bytes,o,t+n)}function Fm(r,e,t,n){return _i(r,e,1,t)}function Mm(r,e,t,n){return _i(r,e,2,gt(r,e+1,n))}function Vm(r,e,t,n){return _i(r,e,3,yt(r,e+1,n))}function Hm(r,e,t,n){return _i(r,e,5,wt(r,e+1,n))}function $m(r,e,t,n){let o=bt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer bytes lengths not supported`);return _i(r,e,9,o)}function Oa(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===w.string?Ca(r.value):r.value),r.encodedBytes}function vo(r,e){let t=Oa(e);Fe(r,e.type.majorEncoded,t.length),r.push(t)}vo.encodedSize=function(e){let t=Oa(e);return Fe.encodedSize(t.length)+t.length};vo.compareTokens=function(e,t){return cv(Oa(e),Oa(t))};function cv(r,e){return r.length<e.length?-1:r.length>e.length?1:km(r,e)}function Ii(r,e,t,n,o){let i=t+n;Ir(r,e,i);let s=new R(w.string,_m(r,e+t,e+i),i);return o.retainStringBytes===!0&&(s.byteValue=Eo(r,e+t,e+i)),s}function zm(r,e,t,n){return Ii(r,e,1,t,n)}function Km(r,e,t,n){return Ii(r,e,2,gt(r,e+1,n),n)}function qm(r,e,t,n){return Ii(r,e,3,yt(r,e+1,n),n)}function Gm(r,e,t,n){return Ii(r,e,5,wt(r,e+1,n),n)}function Wm(r,e,t,n){let o=bt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer string lengths not supported`);return Ii(r,e,9,o,n)}var jm=vo;function So(r,e,t,n){return new R(w.array,n,t)}function Ym(r,e,t,n){return So(r,e,1,t)}function Xm(r,e,t,n){return So(r,e,2,gt(r,e+1,n))}function Zm(r,e,t,n){return So(r,e,3,yt(r,e+1,n))}function Jm(r,e,t,n){return So(r,e,5,wt(r,e+1,n))}function Qm(r,e,t,n){let o=bt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer array lengths not supported`);return So(r,e,9,o)}function eg(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return So(r,e,1,1/0)}function Da(r,e){Fe(r,w.array.majorEncoded,e.value)}Da.compareTokens=Tt.compareTokens;Da.encodedSize=function(e){return Fe.encodedSize(e.value)};function Ao(r,e,t,n){return new R(w.map,n,t)}function tg(r,e,t,n){return Ao(r,e,1,t)}function rg(r,e,t,n){return Ao(r,e,2,gt(r,e+1,n))}function ng(r,e,t,n){return Ao(r,e,3,yt(r,e+1,n))}function og(r,e,t,n){return Ao(r,e,5,wt(r,e+1,n))}function ig(r,e,t,n){let o=bt(r,e+1,n);if(typeof o=="bigint")throw new Error(`${H} 64-bit integer map lengths not supported`);return Ao(r,e,9,o)}function sg(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return Ao(r,e,1,1/0)}function Pa(r,e){Fe(r,w.map.majorEncoded,e.value)}Pa.compareTokens=Tt.compareTokens;Pa.encodedSize=function(e){return Fe.encodedSize(e.value)};function ag(r,e,t,n){return new R(w.tag,t,1)}function cg(r,e,t,n){return new R(w.tag,gt(r,e+1,n),2)}function lg(r,e,t,n){return new R(w.tag,yt(r,e+1,n),3)}function ug(r,e,t,n){return new R(w.tag,wt(r,e+1,n),5)}function fg(r,e,t,n){return new R(w.tag,bt(r,e+1,n),9)}function Ua(r,e){Fe(r,w.tag.majorEncoded,e.value)}Ua.compareTokens=Tt.compareTokens;Ua.encodedSize=function(e){return Fe.encodedSize(e.value)};var pv=20,mv=21,gv=22,yv=23;function hg(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${H} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new R(w.null,null,1):new R(w.undefined,void 0,1)}function dg(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${H} indefinite length items not allowed`);return new R(w.break,void 0,1)}function $u(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${H} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${H} Infinity values are not supported`)}return new R(w.float,r,e)}function pg(r,e,t,n){return $u(zu(r,e+1),3,n)}function mg(r,e,t,n){return $u(Ku(r,e+1),5,n)}function gg(r,e,t,n){return $u(xg(r,e+1),9,n)}function Fa(r,e,t){let n=e.value;if(n===!1)r.push([w.float.majorEncoded|pv]);else if(n===!0)r.push([w.float.majorEncoded|mv]);else if(n===null)r.push([w.float.majorEncoded|gv]);else if(n===void 0)r.push([w.float.majorEncoded|yv]);else{let o,i=!1;(!t||t.float64!==!0)&&(wg(n),o=zu(Mt,1),n===o||Number.isNaN(n)?(Mt[0]=249,r.push(Mt.slice(0,3)),i=!0):(bg(n),o=Ku(Mt,1),n===o&&(Mt[0]=250,r.push(Mt.slice(0,5)),i=!0))),i||(wv(n),o=xg(Mt,1),Mt[0]=251,r.push(Mt.slice(0,9)))}}Fa.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){wg(n);let o=zu(Mt,1);if(n===o||Number.isNaN(n))return 3;if(bg(n),o=Ku(Mt,1),n===o)return 5}return 9};var yg=new ArrayBuffer(9),Nt=new DataView(yg,1),Mt=new Uint8Array(yg,0);function wg(r){if(r===1/0)Nt.setUint16(0,31744,!1);else if(r===-1/0)Nt.setUint16(0,64512,!1);else if(Number.isNaN(r))Nt.setUint16(0,32256,!1);else{Nt.setFloat32(0,r);let e=Nt.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Nt.setUint16(0,31744,!1);else if(t===0)Nt.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=t-127;o<-24?Nt.setUint16(0,0):o<-14?Nt.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):Nt.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function zu(r,e){if(r.length-e<2)throw new Error(`${H} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,o=t&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,t&32768?-i:i}function bg(r){Nt.setFloat32(0,r,!1)}function Ku(r,e){if(r.length-e<4)throw new Error(`${H} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function wv(r){Nt.setFloat64(0,r,!1)}function xg(r,e){if(r.length-e<8)throw new Error(`${H} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}Fa.compareTokens=Tt.compareTokens;function oe(r,e,t){throw new Error(`${H} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function Ma(r){return()=>{throw new Error(`${H} ${r}`)}}var D=[];for(let r=0;r<=23;r++)D[r]=oe;D[24]=Bm;D[25]=Tm;D[26]=Nm;D[27]=Cm;D[28]=oe;D[29]=oe;D[30]=oe;D[31]=oe;for(let r=32;r<=55;r++)D[r]=oe;D[56]=Lm;D[57]=Om;D[58]=Dm;D[59]=Um;D[60]=oe;D[61]=oe;D[62]=oe;D[63]=oe;for(let r=64;r<=87;r++)D[r]=Fm;D[88]=Mm;D[89]=Vm;D[90]=Hm;D[91]=$m;D[92]=oe;D[93]=oe;D[94]=oe;D[95]=Ma("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)D[r]=zm;D[120]=Km;D[121]=qm;D[122]=Gm;D[123]=Wm;D[124]=oe;D[125]=oe;D[126]=oe;D[127]=Ma("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)D[r]=Ym;D[152]=Xm;D[153]=Zm;D[154]=Jm;D[155]=Qm;D[156]=oe;D[157]=oe;D[158]=oe;D[159]=eg;for(let r=160;r<=183;r++)D[r]=tg;D[184]=rg;D[185]=ng;D[186]=og;D[187]=ig;D[188]=oe;D[189]=oe;D[190]=oe;D[191]=sg;for(let r=192;r<=215;r++)D[r]=ag;D[216]=cg;D[217]=lg;D[218]=ug;D[219]=fg;D[220]=oe;D[221]=oe;D[222]=oe;D[223]=oe;for(let r=224;r<=243;r++)D[r]=Ma("simple values are not supported");D[244]=oe;D[245]=oe;D[246]=oe;D[247]=hg;D[248]=Ma("simple values are not supported");D[249]=pg;D[250]=mg;D[251]=gg;D[252]=oe;D[253]=oe;D[254]=oe;D[255]=dg;var Vt=[];for(let r=0;r<24;r++)Vt[r]=new R(w.uint,r,1);for(let r=-1;r>=-24;r--)Vt[31-r]=new R(w.negint,r,1);Vt[64]=new R(w.bytes,new Uint8Array(0),1);Vt[96]=new R(w.string,"",1);Vt[128]=new R(w.array,0,1);Vt[160]=new R(w.map,0,1);Vt[244]=new R(w.false,!1,1);Vt[245]=new R(w.true,!0,1);Vt[246]=new R(w.null,null,1);function qu(r){switch(r.type){case w.false:return or([244]);case w.true:return or([245]);case w.null:return or([246]);case w.bytes:return r.value.length?void 0:or([64]);case w.string:return r.value===""?or([96]):void 0;case w.array:return r.value===0?or([128]):void 0;case w.map:return r.value===0?or([160]):void 0;case w.uint:return r.value<24?or([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return or([31-Number(r.value)])}}var xv={float64:!1,mapSorter:vv,quickEncodeToken:qu};function Wu(){let r=[];return r[w.uint.major]=Tt,r[w.negint.major]=La,r[w.bytes.major]=vo,r[w.string.major]=jm,r[w.array.major]=Da,r[w.map.major]=Pa,r[w.tag.major]=Ua,r[w.float.major]=Fa,r}var Eg=Wu(),Gu=new Si,Va=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(`${_r} object contains circular references`);return new r(t,e)}},on={null:new R(w.null,null),undefined:new R(w.undefined,void 0),true:new R(w.true,!0),false:new R(w.false,!1),emptyArray:new R(w.array,0),emptyMap:new R(w.map,0)},sn={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new R(w.float,r):r>=0?new R(w.uint,r):new R(w.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new R(w.uint,r):new R(w.negint,r)},Uint8Array(r,e,t,n){return new R(w.bytes,r)},string(r,e,t,n){return new R(w.string,r)},boolean(r,e,t,n){return r?on.true:on.false},null(r,e,t,n){return on.null},undefined(r,e,t,n){return on.undefined},ArrayBuffer(r,e,t,n){return new R(w.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new R(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[on.emptyArray,new R(w.break)]:on.emptyArray;n=Va.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Ri(s,t,n);return t.addBreakTokens?[new R(w.array,r.length),o,new R(w.break)]:[new R(w.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return t.addBreakTokens===!0?[on.emptyMap,new R(w.break)]:on.emptyMap;n=Va.createCheck(n,r);let a=[],c=0;for(let l of i)a[c++]=[Ri(l,t,n),Ri(o?r.get(l):r[l],t,n)];return Ev(a,t),t.addBreakTokens?[new R(w.map,s),a,new R(w.break)]:[new R(w.map,s),a]}};sn.Map=sn.Object;sn.Buffer=sn.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))sn[`${r}Array`]=sn.DataView;function Ri(r,e={},t){let n=Em(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||sn[n];if(typeof o=="function"){let s=o(r,n,e,t);if(s!=null)return s}let i=sn[n];if(!i)throw new Error(`${_r} unsupported type: ${n}`);return i(r,n,e,t)}function Ev(r,e){e.mapSorter&&r.sort(e.mapSorter)}function vv(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let o=t.type.major,i=Eg[o].compareTokens(t,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function vg(r,e,t,n){if(Array.isArray(e))for(let o of e)vg(r,o,t,n);else t[e.type.major](r,e,n)}function ju(r,e,t){let n=Ri(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let o=t.quickEncodeToken(n);if(o)return o;let i=e[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,t),a=new Si(s);if(i(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return vi(a.chunks[0])}}return Gu.reset(),vg(Gu,n,e,t),Gu.toBytes(!0)}function an(r,e){return e=Object.assign({},xv,e),ju(r,Eg,e)}var Sv={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Ha=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=Vt[e];if(t===void 0){let n=D[e];if(!n)throw new Error(`${H} 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}},ki=Symbol.for("DONE"),$a=Symbol.for("BREAK");function Av(r,e,t){let n=[];for(let o=0;o<r.value;o++){let i=_o(e,t);if(i===$a){if(r.value===1/0)break;throw new Error(`${H} got unexpected break to lengthed array`)}if(i===ki)throw new Error(`${H} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function _v(r,e,t){let n=t.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=_o(e,t);if(a===$a){if(r.value===1/0)break;throw new Error(`${H} got unexpected break to lengthed map`)}if(a===ki)throw new Error(`${H} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${H} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${H} found repeat map key "${a}"`);let c=_o(e,t);if(c===ki)throw new Error(`${H} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(a,c):o[a]=c}return n?i:o}function _o(r,e){if(r.done())return ki;let t=r.next();if(t.type===w.break)return $a;if(t.type.terminal)return t.value;if(t.type===w.array)return Av(t,r,e);if(t.type===w.map)return _v(t,r,e);if(t.type===w.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=_o(r,e);return e.tags[t.value](n)}throw new Error(`${H} tag not supported (${t.value})`)}throw new Error("unsupported")}function Yu(r,e){if(!(r instanceof Uint8Array))throw new Error(`${H} data to decode must be a Uint8Array`);e=Object.assign({},Sv,e);let t=e.tokenizer||new Ha(r,e),n=_o(t,e);if(n===ki)throw new Error(`${H} did not find any content to decode`);if(n===$a)throw new Error(`${H} got unexpected break`);return[n,r.subarray(t.pos())]}function tt(r,e){let[t,n]=Yu(r,e);if(n.length>0)throw new Error(`${H} too many terminals, data makes no sense`);return t}var Rr="/",Sg=new TextEncoder().encode(Rr),Ka=Sg[0],xe=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=P(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]!==Ka)throw new Error("Invalid key")}toString(e="utf8"){return G(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Rr))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=Sg),this._buf[0]!==Ka){let e=new Uint8Array(this._buf.byteLength+1);e.fill(Ka,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Ka;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let o=0;o<t.length;o++){if(n.length<o+1)return!1;let i=t[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Rr).slice(1)}type(){return Iv(this.baseNamespace())}name(){return Rv(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Rr)||(e+=Rr),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Rr):new r(e.slice(0,-1).join(Rr))}child(e){return this.toString()===Rr?e:e.toString()===Rr?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...kv(e.map(t=>t.namespaces()))])}};function Iv(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Rv(r){let e=r.split(":");return e[e.length-1]}function kv(r){return[].concat(...r)}var Rg="/pin/",Ag="/pinned-block/",Xu=zr,_g=1;function Ig(r){return r.version===0&&(r=r.toV1()),new xe(`${Rg}${r.toString(Xu)}`)}var qa=class{datastore;blockstore;dagWalkers;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.dagWalkers=n}async*add(e,t={}){let n=Ig(e);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(t.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let i=new lr({concurrency:_g});for await(let a of this.#e(e,i,{...t,depth:o}))await this.#n(a,c=>c.pinnedBy.find(l=>ne(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:o,metadata:t.metadata??{}};await this.datastore.put(n,an(s),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 i=await this.blockstore.get(e,n);yield e;for await(let s of o.walk(i))yield*await t.add(async()=>this.#e(s,t,{...n,depth:n.depth-1}))}async#n(e,t,n){let o=new xe(`${Ag}${Xu.encode(e.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=tt(await this.datastore.get(o,n))}catch(a){if(a.code!=="ERR_NOT_FOUND")throw a}if(t(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,an(i),n),n.onProgress?.(new V("helia:pin:add",e))}}async*rm(e,t={}){let n=Ig(e),o=await this.datastore.get(n,t),i=tt(o);await this.datastore.delete(n,t);let s=new lr({concurrency:_g});for await(let a of this.#e(e,s,{...t,depth:i.depth}))await this.#n(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>ne(l,e.bytes)),!0),{...t,depth:i.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:Rg+(e.cid!=null?`${e.cid.toString(zr)}`:"")},e)){let o=z.parse(t.toString().substring(5),zr),i=tt(n);yield{cid:o,...i}}}async isPinned(e,t={}){let n=new xe(`${Ag}${Xu.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}};var Bv=5,Ga=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??Bv}async start(){await Fr(...this.routers)}async stop(){await Mr(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new N("No content routers available","ERR_NO_ROUTERS_AVAILABLE");let n=new hs({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of Vr(n.toGenerator(),...Io(this.routers,"findProviders").map(i=>i.findProviders(e,t))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,t);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer %p",o.id,i),null}},{peerId:o.id,signal:t.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer %p",o.id,i)})}yield o}}async provide(e,t={}){if(this.routers.length===0)throw new N("No content routers available","ERR_NO_ROUTERS_AVAILABLE");await Promise.all(Io(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async put(e,t,n){await Promise.all(Io(this.routers,"put").map(async o=>{await o.put(e,t,n)}))}async get(e,t){return Promise.any(Io(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new N("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");let n=this,o=Vr(...Io(this.routers,"findPeer").map(i=>async function*(){try{yield await i.findPeer(e,t)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i;throw new N("Could not find peer in routing","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new N("No peer routers available","ERR_NO_ROUTERS_AVAILABLE");for await(let n of Vr(...Io(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(e,t))))n!=null&&(yield n)}};function Io(r,e){return r.filter(t=>t[e]!=null)}var cn={},Ro=r=>{r.addEventListener("message",e=>{Ro.dispatchEvent("message",r,e)}),r.port!=null&&r.port.addEventListener("message",e=>{Ro.dispatchEvent("message",r,e)})};Ro.addEventListener=(r,e)=>{cn[r]==null&&(cn[r]=[]),cn[r].push(e)};Ro.removeEventListener=(r,e)=>{cn[r]!=null&&(cn[r]=cn[r].filter(t=>t===e))};Ro.dispatchEvent=function(r,e,t){cn[r]!=null&&cn[r].forEach(n=>n(e,t))};var Zu=Ro;var Ju="lock:worker:request-read",Qu="lock:worker:release-read",ef="lock:master:grant-read",tf="lock:worker:request-write",rf="lock:worker:release-write",nf="lock:master:grant-write";var kg=(r=21)=>Math.random().toString().substring(2);var Bg=(r,e,t,n,o)=>(i,s)=>{if(s.data.type!==t)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(e,{data:{name:a.name,handler:async()=>{i.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=f=>{if(f==null||f.data==null)return;let u={type:f.data.type,name:f.data.name,identifier:f.data.identifier};u.type===n&&u.identifier===a.identifier&&(i.removeEventListener("message",l),c())};i.addEventListener("message",l)})}}}))},Tg=(r,e,t,n)=>async()=>{let o=kg();return globalThis.postMessage({type:e,identifier:o,name:r}),new Promise(i=>{let s=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",s),i(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",s)})},Tv={singleProcess:!1},Ng=r=>{if(r=Object.assign({},Tv,r),!!globalThis.document||r.singleProcess){let t=new EventTarget;return Zu.addEventListener("message",Bg(t,"requestReadLock",Ju,Qu,ef)),Zu.addEventListener("message",Bg(t,"requestWriteLock",tf,rf,nf)),t}return{isWorker:!0,readLock:t=>Tg(t,Ju,ef,Qu),writeLock:t=>Tg(t,tf,nf,rf)}};var Cn={},ln;async function of(r,e){let t,n=new Promise(o=>{t=o});return r.add(async()=>bi((async()=>{await new Promise(o=>{t(()=>{o()})})})(),{milliseconds:e.timeout})),n}var Nv=(r,e)=>{if(ln.isWorker===!0)return{readLock:ln.readLock(r,e),writeLock:ln.writeLock(r,e)};let t=new at({concurrency:1}),n;return{async readLock(){if(n!=null)return of(n,e);n=new at({concurrency:e.concurrency,autoStart:!1});let o=n,i=of(n,e);return t.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,of(t,e)}}},Cv={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function sf(r){let e=Object.assign({},Cv,r);return ln==null&&(ln=Ng(e),ln.isWorker!==!0&&(ln.addEventListener("requestReadLock",t=>{Cn[t.data.name]!=null&&Cn[t.data.name].readLock().then(async n=>t.data.handler().finally(()=>{n()}))}),ln.addEventListener("requestWriteLock",async t=>{Cn[t.data.name]!=null&&Cn[t.data.name].writeLock().then(async n=>t.data.handler().finally(()=>{n()}))}))),Cn[e.name]==null&&(Cn[e.name]=Nv(e.name,e)),Cn[e.name]}var Wa=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=sf({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await Fr(this.child),this.started=!0}async stop(){await Mr(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{o()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let i of e){if(await o.pins.isPinned(i))throw new Error("CID was pinned");yield i}}(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var Cg=42;function Lv(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Ov(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=z.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new R(w.tag,Cg),new R(w.bytes,t)]}function Dv(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Pv(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 af={float64:!0,typeEncoders:{Object:Ov,undefined:Dv,number:Pv}},MN={...af,typeEncoders:{...af.typeEncoders}};function Uv(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return z.decode(r.subarray(1))}var ja={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};ja.tags[Cg]=Uv;var VN={...ja,tags:ja.tags.slice()};var un=113,Bi=r=>an(r,af),Ln=r=>tt(Lv(r),ja);var cf=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===w.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===w.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[w.uint.major](e,t){this.prefix(e);let n=String(t.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);e.push(o)}[w.negint.major](e,t){this[w.uint.major](e,t)}[w.bytes.major](e,t){throw new Error(`${_r} unsupported type: Uint8Array`)}[w.string.major](e,t){this.prefix(e);let n=Ca(JSON.stringify(t.value));e.push(n.length>32?vi(n):n)}[w.array.major](e,t){this.prefix(e),this.inRecursive.push({type:w.array,elements:0}),e.push([91])}[w.map.major](e,t){this.prefix(e),this.inRecursive.push({type:w.map,elements:0}),e.push([123])}[w.tag.major](e,t){}[w.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===w.array)e.push([93]);else if(s.type===w.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(`${_r} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),e.push(o)}};function Fv(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${_r} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==w.string||n.type!==w.string)throw new Error(`${_r} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${_r} unexpected duplicate map keys, this is not supported`)}var Mv={addBreakTokens:!0,mapSorter:Fv};function Ni(r,e){return e=Object.assign({},Mv,e),ju(r,new cf,e)}var fn=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(`${H} 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(`${H} 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 R(w.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(`${H} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${H} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(i);return n?new R(w.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new R(s>=0?w.uint:w.negint,s,this._pos-e):new R(s>=0?w.uint:w.negint,BigInt(i),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${H} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new R(w.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${H} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${H} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${H} unexpected unicode sequence at position ${this._pos}`);let c,l,f,u;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(u=(i&31)<<6|c&63,u>127&&(s=u));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(u=(i&15)<<12|(c&63)<<6|l&63,u>2047&&(u<55296||u>57343)&&(s=u));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],f=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(f&192)===128&&(u=(i&15)<<18|(c&63)<<12|(l&63)<<6|f&63,u>65535&&u<1114112&&(s=u))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${H} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${H} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new R(w.string,Vu(t),this._pos-e);default:if(i<32)throw new Error(`${H} invalid control character at position ${this._pos}`);i<128?(t.push(i),this._pos++):o()}}throw new Error(`${H} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new R(w.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new R(w.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new R(w.null,null,4);case 102:return this.expect([102,97,108,115,101]),new R(w.false,!1,5);case 116:return this.expect([116,114,117,101]),new R(w.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(`${H} 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 R(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${H} 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 R(w.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 R(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${H} 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 R(w.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${H} 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(`${H} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Ci(r,e){return e=Object.assign({tokenizer:new fn(r,e)},e),tt(r,e)}function Vv(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Hv(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=z.asCID(r);if(!e)return null;let t=e.toString();return[new R(w.map,1/0,1),new R(w.string,"/",1),new R(w.string,t,t.length),new R(w.break,void 0,1)]}function Ya(r){let e=it.encode(r).slice(1);return[new R(w.map,1/0,1),new R(w.string,"/",1),new R(w.map,1/0,1),new R(w.string,"bytes",5),new R(w.string,e,e.length),new R(w.break,void 0,1),new R(w.break,void 0,1)]}function Ht(r){return Ya(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function $v(r){return Ya(new Uint8Array(r))}function zv(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Kv(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 qv={typeEncoders:{Object:Hv,Buffer:Ya,Uint8Array:Ya,Int8Array:Ht,Uint16Array:Ht,Int16Array:Ht,Uint32Array:Ht,Int32Array:Ht,Float32Array:Ht,Float64Array:Ht,Uint8ClampedArray:Ht,BigInt64Array:Ht,BigUint64Array:Ht,DataView:Ht,ArrayBuffer:$v,undefined:zv,number:Kv}},lf=class extends fn{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===w.map){let t=this._next();if(t.type===w.string&&t.value==="/"){let n=this._next();if(n.type===w.string){if(this._next().type!==w.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new R(w.tag,42,0)}if(n.type===w.map){let o=this._next();if(o.type===w.string&&o.value==="bytes"){let i=this._next();if(i.type===w.string){for(let a=0;a<2;a++)if(this._next().type!==w.break)throw new Error("Invalid encoded Bytes form");let s=it.decode(`m${i.value}`);return new R(w.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},uf={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};uf.tags[42]=z.parse;var hn=297,Og=r=>Ni(r,qv),Xa=r=>{let e=Vv(r),t=Object.assign(uf,{tokenizer:new lf(e,uf)});return Ci(e,t)};var nC=new TextDecoder;var oC=new TextEncoder;var Gv=new TextDecoder;function ff(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 Ja(r,e){let t;[t,e]=ff(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 Dg(r,e){let t;return[t,e]=ff(r,e),[t&7,t>>3,e]}function Wv(r){let e={},t=r.length,n=0;for(;n<t;){let o,i;if([o,i,n]=Dg(r,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Ja(r,n)}else if(i===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=Ja(r,n),e.Name=Gv.decode(s)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[e.Tsize,n]=ff(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Pg(r){let e=r.length,t=0,n,o=!1,i;for(;t<e;){let a,c;if([a,c,t]=Dg(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=Ja(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]=Ja(r,t),n.push(Wv(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var sC=new TextEncoder,aC=2**32,cC=2**31;var fC=new TextEncoder;function Ug(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var $t=112;function ir(r){let e=Ug(r),t=Pg(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(o=>{let i={};try{i.Hash=z.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}var jv={codec:$t,*walk(r){yield*ir(r).Links.map(t=>t.Hash)}},Yv={codec:ht,*walk(){}},Fg=42,Xv={codec:un,*walk(r){let e=[],t=[];t[Fg]=n=>{if(n[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");let o=z.decode(n.subarray(1));return e.push(o),o},tt(r,{tags:t}),yield*e}},df=class extends fn{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===w.map){let t=this._next();if(t.type===w.string&&t.value==="/"){let n=this._next();if(n.type===w.string){if(this._next().type!==w.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new R(w.tag,42,0)}if(n.type===w.map){let o=this._next();if(o.type===w.string&&o.value==="bytes"){let i=this._next();if(i.type===w.string){for(let a=0;a<2;a++)if(this._next().type!==w.break)throw new Error("Invalid encoded Bytes form");let s=it.decode(`m${i.value}`);return new R(w.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},Zv={codec:hn,*walk(r){let e=[],t=[];t[Fg]=n=>{let o=z.parse(n);return e.push(o),o},Ci(r,{tags:t,tokenizer:new df(r,{tags:t,allowIndefinite:!0,allowUndefined:!0,allowNaN:!0,allowInfinity:!0,allowBigInt:!0,strict:!1,rejectDuplicateMapKeys:!1})}),yield*e}},Jv={codec:Kr,*walk(){}};function Mg(r=[]){let e={};return[jv,Yv,Xv,Zv,Jv,...r].forEach(t=>{e[t.codec]=t}),e}var pf=new xe("/version"),Vg=1;async function Hg(r){if(!await r.has(pf)){await r.put(pf,P(`${Vg}`));return}let e=await r.get(pf),t=G(e);if(parseInt(t,10)!==Vg)throw new Error("Unknown datastore version, a datastore migration may be required")}function $g(r=[]){let e={};return[Re,Vl,Be,...r].forEach(t=>{e[t.code]=t}),e}var kr=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 ko={};Se(ko,{abortedError:()=>n2,closeFailedError:()=>e2,deleteFailedError:()=>Kg,getFailedError:()=>t2,hasFailedError:()=>r2,notFoundError:()=>Li,openFailedError:()=>Qv,putFailedError:()=>zg});var Br=re(De(),1);function Qv(r){return r=r??new Error("Open failed"),(0,Br.default)(r,"ERR_OPEN_FAILED")}function e2(r){return r=r??new Error("Close failed"),(0,Br.default)(r,"ERR_CLOSE_FAILED")}function zg(r){return r=r??new Error("Put failed"),(0,Br.default)(r,"ERR_PUT_FAILED")}function t2(r){return r=r??new Error("Get failed"),(0,Br.default)(r,"ERR_GET_FAILED")}function Kg(r){return r=r??new Error("Delete failed"),(0,Br.default)(r,"ERR_DELETE_FAILED")}function r2(r){return r=r??new Error("Has failed"),(0,Br.default)(r,"ERR_HAS_FAILED")}function Li(r){return r=r??new Error("Not Found"),(0,Br.default)(r,"ERR_NOT_FOUND")}function n2(r){return r=r??new Error("Aborted"),(0,Br.default)(r,"ERR_ABORTED")}var Oi=class extends kr{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(Pe.encode(e.multihash.bytes),t),e}get(e){let t=this.data.get(Pe.encode(e.multihash.bytes));if(t==null)throw Li();return t}has(e){return this.data.has(Pe.encode(e.multihash.bytes))}async delete(e){this.data.delete(Pe.encode(e.multihash.bytes))}async*getAll(){for(let[e,t]of this.data.entries())yield{cid:z.createV1(ht,Xe(Pe.decode(e))),block:t}}};function o2(r){return r[Symbol.asyncIterator]!=null}function i2(r,e){let t=0;if(o2(r))return async function*(){for await(let c of r)await e(c,t++)&&(yield c)}();let n=$n(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=e(o,t++);if(typeof s.then=="function")return async function*(){await s&&(yield o);for await(let c of n)await e(c,t++)&&(yield c)}();let a=e;return function*(){s===!0&&(yield o);for(let c of n)a(c,t++)&&(yield c)}()}var xt=i2;var jC=Qe("blockstore:core:tiered");var qg={...ko};var Qa=0,ec=class extends kr{child;constructor(e){super(),this.child=e}put(e,t){return e.multihash.code===Qa||this.child==null?e:this.child.put(e,t)}get(e){if(e.multihash.code===Qa)return e.multihash.digest;if(this.child==null)throw qg.notFoundError();return this.child.get(e)}has(e){return e.multihash.code===Qa?!0:this.child==null?!1:this.child.has(e)}delete(e){if(e.code!==Qa&&this.child!=null)return this.child.delete(e)}getAll(e){return this.child!=null?this.child.getAll(e):[]}};function s2(r){return r[Symbol.asyncIterator]!=null}function Gg(r){return r?.then!=null}function a2(r,e){let t=0;if(s2(r))return async function*(){for await(let c of r){let l=e(c,t++);Gg(l)&&await l,yield c}}();let n=$n(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof e(o,t++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=e(c,t++);Gg(l)&&await l,yield c}}();let a=e;return function*(){yield o;for(let c of n)a(c,t++),yield c}()}var mf=a2;var tc=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 ec(e.blockstore),this.hashers=e.hashers??{}}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new V("blocks:put:duplicate",e)),e):(n.onProgress?.(new V("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,t,n))),n.onProgress?.(new V("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=xt(e,async({cid:i})=>{let s=await this.child.has(i,t);return s&&t.onProgress?.(new V("blocks:put-many:duplicate",i)),!s}),o=mf(n,async({cid:i,block:s})=>{t.onProgress?.(new V("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(i,s,t)))});t.onProgress?.(new V("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 V("blocks:get:providers:get",e));let n=await Wg(e,this.components.blockBrokers,this.hashers[e.multihash.code],{...t,log:this.log});return t.onProgress?.(new V("blocks:get:blockstore:put",e)),await this.child.put(e,n,t),t.onProgress?.(new V("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,n,t))),n}return t.onProgress?.(new V("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new V("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(mf(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){t.onProgress?.(new V("blocks:get-many:providers:get",n));let o=await Wg(n,this.components.blockBrokers,this.hashers[n.multihash.code],{...t,log:this.log});t.onProgress?.(new V("blocks:get-many:blockstore:put",n)),await this.child.put(n,o,t),t.onProgress?.(new V("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(n,o,t)))}}))}async delete(e,t={}){t.onProgress?.(new V("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new V("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 V("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},rc=class extends tc{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await Fr(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await Mr(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(t));return new gf({blockstore:this.child,blockBrokers:n,hashers:this.hashers,logger:this.logger},{root:e})}},gf=class extends tc{closeController;constructor(e,t){super(e),this.closeController=new AbortController,me(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=Ye([this.closeController.signal,n.signal]);me(1/0,o);try{return await super.put(e,t,{...n,signal:o})}finally{o.clear()}}async*putMany(e,t={}){let n=Ye([this.closeController.signal,t.signal]);me(1/0,n);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=Ye([this.closeController.signal,t.signal]);me(1/0,n);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Ye([this.closeController.signal,t.signal]);me(1/0,n);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Ye([this.closeController.signal,t.signal]);me(1/0,n);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Ye([this.closeController.signal,t.signal]);me(1/0,n);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Ye([this.closeController.signal,t.signal]);me(1/0,n);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Ye([this.closeController.signal,e.signal]);me(1/0,t);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function c2(r){return typeof r.retrieve=="function"}var l2=(r,e)=>{if(e==null)throw new N(`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(!ne(n.digest,r.multihash.digest))throw new N("Hash of downloaded block did not match multihash from passed CID","ERR_HASH_MISMATCH")}};async function Wg(r,e,t,n){let o=l2(r,t),i=new AbortController,s=Ye([i.signal,n.signal]);me(1/0,i.signal,s);let a=[];for(let c of e)c2(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,f=await c.retrieve(r,{...n,signal:s,validateFn:async u=>{await o(u),l=!0}});return l||await o(f),f}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{i.abort(),s.clear()}}var yf=re(Nu(),1);var u2=Math.LN2*Math.LN2,nc=class r{static create(e,t=.005){let n=f2(e,t);return new r(n)}seeds;bits;buffer;constructor(e={}){e.seeds!=null?this.seeds=e.seeds:this.seeds=h2(e.hashes??8),this.bits=e.bits??1024,this.buffer=rt(Math.ceil(this.bits/8))}add(e){typeof e=="string"&&(e=P(e));for(let t=0;t<this.seeds.length;t++){let o=yf.default.x86.hash32(e,this.seeds[t])%this.bits;this.setbit(o)}}has(e){typeof e=="string"&&(e=P(e));for(let t=0;t<this.seeds.length;t++){let o=yf.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 f2(r,e=.005){let t=Math.round(-1*r*Math.log(e)/u2),n=Math.round(t/r*Math.LN2);return{bits:t,hashes:n}}function h2(r){let e,t,n=[];for(let o=0;o<r;o++)for(e=new fr(er(4)),n[o]=e.getUint32(0,!0),t=0;t<o;t++)if(n[o]===n[t]){o--;break}return n}var Di=class extends Mn{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(e,t){super(),me(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=nc.create(this.maxProviders)}async retrieve(e,t={}){let n=it.encode(e.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",e),o;let i=fe();if(this.requests.set(n,i.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.intialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",e)}let s=!1,a=new lr({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{s=!0,i.resolve(l.detail.result)}),a.addEventListener("idle",()=>{s||t.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let f=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(f)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),i.resolve(await this.retrieve(e,t))}).catch(l=>{this.log.error("could not find new providers for %c",e,l),i.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(e,l.detail,t),{provider:l.detail}).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,f)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(e,l,t),{provider:l}))).catch(l=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,l)});try{return await i.promise}finally{this.removeEventListener("provider",c),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let o=fe(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e);for await(let s of this.findNewProviders(e,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===t&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<t)throw new N(`Found ${i} of ${t} ${this.name} providers for ${e}`,"ERR_INSUFFICIENT_PROVIDERS_FOUND")}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",e,s.errors??s),o.reject(s)}),o.promise}};var oc=class{blockstore;datastore;pins;logger;routing;dagWalkers;hashers;dns;metrics;log;constructor(e){this.logger=e.logger??hm(),this.log=this.logger.forComponent("helia"),this.hashers=$g(e.hashers),this.dagWalkers=Mg(e.dagWalkers),this.dns=e.dns??Ei(),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 Ga(t,{routers:(e.routers??[]).flatMap(o=>{let i=[o];return o[$o]!=null&&i.push(o[$o]),o[Ko]!=null&&i.push(o[Ko]),i}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new rc(t);this.pins=new qa(e.datastore,n,this.dagWalkers),this.blockstore=new Wa(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(o=>o(t))}async start(){await Hg(this.datastore),await Fr(this.blockstore,this.datastore,this.routing)}async stop(){await Mr(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 ur(o.deleteMany(async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,e))continue;yield i,e.onProgress?.(new V("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new V("helia:gc:error",s))}}()))}finally{t()}this.log("gc finished")}};var ic=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let p=Number.parseInt(u,e);if(!Number.isNaN(p))return p});if(f===void 0)break;if(i*=e,i+=f,i>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[o]=s[0],t[o+1]=s[1],t[o+2]=s[2],t[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];t[o]=i>>8,t[o+1]=i&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=e(i.subarray(0,s));return t.set(i.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var jg=45,d2=15,Bo=new ic;function wf(r){if(!(r.length>d2))return Bo.new(r).parseWith(()=>Bo.readIPv4Addr())}function bf(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>jg))return Bo.new(r).parseWith(()=>Bo.readIPv6Addr())}function sc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>jg))return Bo.new(r).parseWith(()=>Bo.readIPAddr())}function To(r){return!!wf(r)}function No(r){return!!bf(r)}function ac(r){return!!sc(r)}var Xg=re(Yg(),1),p2=["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"],m2=p2.map(r=>new Xg.Netmask(r));function g2(r){for(let e of m2)if(e.contains(r))return!0;return!1}function y2(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 Zg(r){return To(r)?g2(r):No(r)?y2(r):void 0}var o3=parseInt("0xFFFF",16),i3=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var e0=To,v2=No,xf=function(r){let e=0;if(r=r.toString().trim(),e0(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(v2(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let i=e0(t[n]),s;i&&(s=xf(t[n]),t[n]=G(s.slice(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,G(s.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let i=[n,1];for(n=9-t.length;n>0;n--)i.push("0");t.splice.apply(t,i)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let i=parseInt(t[n],16);o[e++]=i>>8&255,o[e++]=i&255}return o}throw new Error("invalid ip address")},t0=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let i=0;i<t;i++)o.push(r[e+i]);return o.join(".")}if(t===16){let o=[];for(let i=0;i<t;i+=2)o.push(n.getUint16(e+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Co={},Ef={},A2=[[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"]];A2.forEach(r=>{let e=_2(...r);Ef[e.code]=e,Co[e.name]=e});function _2(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function Y(r){if(typeof r=="number"){if(Ef[r]!=null)return Ef[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Co[r]!=null)return Co[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var V3=Y("ip4"),H3=Y("ip6"),$3=Y("ipcidr");function Sf(r,e){switch(Y(r).code){case 4:case 41:return R2(e);case 42:return o0(e);case 6:case 273:case 33:case 132:return s0(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return o0(e);case 421:return N2(e);case 444:return i0(e);case 445:return i0(e);case 466:return T2(e);default:return G(e,"base16")}}function Af(r,e){switch(Y(r).code){case 4:return r0(e);case 41:return r0(e);case 42:return n0(e);case 6:case 273:case 33:case 132:return _f(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return n0(e);case 421:return k2(e);case 444:return C2(e);case 445:return L2(e);case 466:return B2(e);default:return P(e,"base16")}}var vf=Object.values(qr).map(r=>r.decoder),I2=function(){let r=vf[0].or(vf[1]);return vf.slice(2).forEach(e=>r=r.or(e)),r}();function r0(r){if(!ac(r))throw new Error("invalid ip address");return xf(r)}function R2(r){let e=t0(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!ac(e))throw new Error("invalid ip address");return e}function _f(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function s0(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function n0(r){let e=P(r),t=Uint8Array.from(Hn(e.length));return ue([t,e],t.length+e.length)}function o0(r){let e=wn(r);if(r=r.slice(ot(e)),r.length!==e)throw new Error("inconsistent lengths");return G(r)}function k2(r){let e;r[0]==="Q"||r[0]==="1"?e=Xe(ge.decode(`z${r}`)).bytes:e=z.parse(r).multihash.bytes;let t=Uint8Array.from(Hn(e.length));return ue([t,e],t.length+e.length)}function B2(r){let e=I2.decode(r),t=Uint8Array.from(Hn(e.length));return ue([t,e],t.length+e.length)}function T2(r){let e=wn(r),t=r.slice(ot(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+G(t,"base64url")}function N2(r){let e=wn(r),t=r.slice(ot(e));if(t.length!==e)throw new Error("inconsistent lengths");return G(t,"base58btc")}function C2(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=Pe.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=_f(n);return ue([t,o],t.length+o.length)}function L2(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=Pe.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=_f(n);return ue([t,o],t.length+o.length)}function i0(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=G(e,"base32"),o=s0(t);return`${n}:${o}`}function a0(r){r=If(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<o.length;i++){let s=o[i],a=Y(s);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(i++,i>=o.length)throw l0("invalid address: "+r);if(a.path===!0){n=If(o.slice(i).join("/")),e.push([a.code,Af(a.code,n)]),t.push([a.code,n]);break}let c=Af(a.code,o[i]);e.push([a.code,c]),t.push([a.code,Sf(a.code,c)])}return{string:c0(t),bytes:kf(e),tuples:e,stringTuples:t,path:n}}function Rf(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let i=wn(r,o),s=ot(i),a=Y(i),c=O2(a,r.slice(o+s));if(c===0){e.push([i]),t.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw l0("Invalid address Uint8Array: "+G(r,"base16"));e.push([i,l]);let f=Sf(i,l);if(t.push([i,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(r),string:c0(t),tuples:e,stringTuples:t,path:n}}function c0(r){let e=[];return r.map(t=>{let n=Y(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),If(e.join("/"))}function kf(r){return ue(r.map(e=>{let t=Y(e[0]),n=Uint8Array.from(Hn(t.code));return e.length>1&&e[1]!=null&&(n=ue([n,e[1]])),n}))}function O2(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=wn(e instanceof Uint8Array?e:Uint8Array.from(e));return t+ot(t)}}function If(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}function l0(r){return new Error("Error parsing address: "+r)}var D2=Symbol.for("nodejs.util.inspect.custom"),Bf=Symbol.for("@multiformats/js-multiaddr/multiaddr"),P2=[Y("dns").code,Y("dns4").code,Y("dns6").code,Y("dnsaddr").code],cc=class r{bytes;#e;#n;#s;#u;[Bf]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=Rf(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=a0(e)}else if(f0(e))t=Rf(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#n=t.tuples,this.#s=t.stringTuples,this.#u=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,i="",s=Y("tcp"),a=Y("udp"),c=Y("ip4"),l=Y("ip6"),f=Y("dns6"),u=Y("ip6zone");for(let[h,m]of this.stringTuples())h===u.code&&(i=`%${m??""}`),P2.includes(h)&&(t=s.name,o=443,n=`${m??""}${i}`,e=h===f.code?6:4),(h===s.code||h===a.code)&&(t=Y(h).name,o=parseInt(m??"")),(h===c.code||h===l.code)&&(t=Y(h).name,n=`${m??""}${i}`,e=h===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.#n.map(([e])=>Object.assign({},Y(e)))}protoCodes(){return this.#n.map(([e])=>e)}protoNames(){return this.#n.map(([e])=>Y(e).name)}tuples(){return this.#n}stringTuples(){return this.#s}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(kf(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===Co.p2p.code&&e.push([n,o]),n===Co["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?G(ge.decode(`z${n}`),"base58btc"):G(z.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#u}equals(e){return ne(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(i=>i.resolvable);if(t==null)return[this];let n=u0.get(t.name);if(n==null)throw new N(`no available resolver for ${t.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(i=>Tr(i))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[D2](){return`Multiaddr(${this.#e})`}};var u0=new Map;function f0(r){return!!r?.[Bf]}function Tr(r){return new cc(r)}var U2=r=>r.toString().split("/").slice(1),Ui=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),se=r=>({match:e=>Ui(t=>t===r).match(e),pattern:r}),fc=()=>({match:r=>Ui(e=>typeof e=="string").match(r),pattern:"{string}"}),hc=()=>({match:r=>Ui(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),Me=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ge.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),lc=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Ll.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Ve=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),Et=(...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(", ")})`}),le=(...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 Ee(...r){function e(o){let i=U2(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function t(o){return e(o)!==!1}function n(o){let i=e(o);return i===!1?!1:i.length===0}return{matches:t,exactMatch:n}}var Nf=le(se("dns4"),fc()),Cf=le(se("dns6"),fc()),Lf=le(se("dnsaddr"),fc()),h0=le(se("dns"),fc()),y4=Ee(Nf),w4=Ee(Cf),b4=Ee(Lf),d0=Ee(Et(h0,Lf,Nf,Cf)),p0=le(se("ip4"),Ui(To)),m0=le(se("ip6"),Ui(No)),g0=Et(p0,m0),sr=Et(g0,h0,Nf,Cf,Lf),x4=Ee(sr),E4=Ee(p0),v4=Ee(m0),S4=Ee(g0),dc=le(sr,se("tcp"),hc()),Fi=le(sr,se("udp"),hc()),F2=Et(dc,Fi),A4=Ee(dc),_4=Ee(Fi),Of=le(Fi,se("quic")),pc=le(Fi,se("quic-v1")),M2=Et(Of,pc),I4=Ee(Of),R4=Ee(pc),Tf=Et(sr,dc,Fi,Of,pc),y0=Et(le(Tf,se("ws"),Ve(Me()))),k4=Ee(y0),w0=Et(le(Tf,se("wss"),Ve(Me())),le(Tf,se("tls"),se("ws"),Ve(Me()))),B4=Ee(w0),b0=le(F2,se("webrtc-direct"),lc(),Ve(lc()),Ve(Me())),T4=Ee(b0),x0=le(pc,se("webtransport"),Ve(lc()),Ve(lc()),Ve(Me())),N4=Ee(x0),uc=Et(y0,w0,le(dc,Ve(Me())),le(M2,Ve(Me())),le(sr,Ve(Me())),b0,x0,Me()),C4=Ee(uc),V2=le(uc,se("p2p-circuit"),Me()),L4=Ee(V2),H2=Et(le(uc,se("p2p-circuit"),se("webrtc"),Me()),le(uc,se("webrtc"),Ve(Me())),se("webrtc")),O4=Ee(H2),$2=Et(le(sr,se("tcp"),hc(),se("http"),Ve(Me())),le(sr,se("http"),Ve(Me()))),E0=Ee($2),z2=Et(le(sr,se("tcp"),Et(le(se("443"),se("http")),le(hc(),se("https"))),Ve(Me())),le(sr,se("tls"),se("http"),Ve(Me())),le(sr,se("https"),Ve(Me()))),v0=Ee(z2);var K2=[Y("tcp").code,Y("dns").code,Y("dnsaddr").code,Y("dns4").code,Y("dns6").code];function S0(r){let e;try{e=Y("sni").code}catch{return null}for(let[t,n]of r)if(t===e&&n!==void 0)return n;return null}function A0(r){return r.some(([e,t])=>e===Y("tls").code)}function vt(r,e,t){let n=_0[Y(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${Y(r).name}`);let o=n(e,t);return r===Y("ip6").code?`[${o}]`:o}var _0={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://${vt(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://${vt(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`${vt(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`${vt(t[0],t[1]??"",e)}/p2p/${r}`},http:(r,e)=>{let t=A0(e),n=S0(e);if(t&&n!==null)return`https://${n}`;let o=t?"https://":"http://",i=e.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=vt(i[0],i[1]??"",e);return s=s.replace("tcp://",""),`${o}${s}`},tls:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return vt(t[0],t[1]??"",e)},sni:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");return vt(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=vt(t[0],t[1]??"",e);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=A0(e),n=S0(e);if(t&&n!==null)return`wss://${n}`;let o=t?"wss://":"ws://",i=e.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=vt(i[0],i[1]??"",e);return s=s.replace("tcp://",""),`${o}${s}`},wss:(r,e)=>{let t=e.pop();if(t===void 0)throw new Error("Unexpected end of multiaddr");let n=vt(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`${vt(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`${vt(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`${vt(t[0],t[1]??"",e)}/p2p-webrtc-direct`}};function I0(r,e){let n=Tr(r).stringTuples(),o=n.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let i=Y(o[0]),s=_0[i.name];if(s==null)throw new Error(`No interpreter found for ${i.name}`);let a=s(o[1]??"",n);return e?.assumeHttp!==!1&&K2.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 mc=class{url;#e=0;#n=0;#s=0;#u=0;#g=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}`)}#a(e){let t=e.multihash.bytes;return it.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.#a(e),i=new AbortController,s=()=>{i.abort()};t?.addEventListener("abort",s);try{let a=this.#g.get(o);return a==null&&(this.#e++,a=fetch(n.toString(),{signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async c=>{if(this.log("GET %s %d",n,c.status),!c.ok)throw this.#n++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);return this.#u++,new Uint8Array(await c.arrayBuffer())}),this.#g.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.#n++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",s),this.#g.delete(o)}}reliability(){return this.#e===0?1:this.#s>0?-1/0:this.#u/(this.#e+this.#n*3)}incrementInvalidBlocks(){this.#s++}getStats(){return{attempts:this.#e,errors:this.#n,invalidBlocks:this.#s,successes:this.#u,pendingResponses:this.#g.size}}};function q2(r,e,t){return r.filter(n=>v0.matches(n)||e&&E0.matches(n)?t||d0.matches(n)?!0:Zg(n.toOptions().host)===!1:!1)}async function*gc(r,e,t,n,o,i){for await(let s of e.findProviders(r,i)){let a=q2(s.multiaddrs,n,o);if(a.length===0)continue;let c=I0(a[0]);yield new mc(c,t)}}var Df=class extends Di{routing;allowInsecure;allowLocal;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??yc,this.allowLocal=t.allowLocal??wc}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*gc(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 R0(r,e){return new Df(r,e)}var bc=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??yc,this.allowLocal=t.allowLocal??wc}async retrieve(e,t={}){let n=[];for await(let o of gc(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,t)){this.log("getting block for %c from %s",e,o.url);try{let i=await o.getRawBlock(e,t.signal);this.log.trace("got block for %c from %s",e,o.url);try{await t.validateFn?.(i)}catch(s){this.log.error("failed to validate block for %c from %s",e,o.url,s);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s",e,o.url,i),i instanceof Error?n.push(i):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${o.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return R0({logger:this.logger,routing:this.routing},e)}};var yc=!1,wc=!1;function Mi(r={}){return e=>new bc(e,r)}async function*xc(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 Vf=re(De(),1);var H0=re(Ec(),1);var k0="ERR_IPNS_EXPIRED_RECORD",Vi="ERR_UNRECOGNIZED_VALIDITY",B0="ERR_SIGNATURE_CREATION",Nr="ERR_SIGNATURE_VERIFICATION";var Uf="ERR_UNDEFINED_PARAMETER",T0="ERR_INVALID_RECORD_DATA",N0="ERR_INVALID_VALUE",C0="ERR_INVALID_EMBEDDED_KEY",L0="ERR_MISSING_PRIVATE_KEY",O0="ERR_RECORD_TOO_LARGE";var He;(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=()=>vn(t)}(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=It((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.value!=null&&(i.uint32(10),i.bytes(o.value)),o.signatureV1!=null&&(i.uint32(18),i.bytes(o.signatureV1)),o.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(o.validityType,i)),o.validity!=null&&(i.uint32(34),i.bytes(o.validity)),o.sequence!=null&&(i.uint32(40),i.uint64(o.sequence)),o.ttl!=null&&(i.uint32(48),i.uint64(o.ttl)),o.pubKey!=null&&(i.uint32(58),i.bytes(o.pubKey)),o.signatureV2!=null&&(i.uint32(66),i.bytes(o.signatureV2)),o.data!=null&&(i.uint32(74),i.bytes(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i)=>{let s={},a=i==null?o.len:o.pos+i;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:s.value=o.bytes();break;case 2:s.signatureV1=o.bytes();break;case 3:s.validityType=r.ValidityType.codec().decode(o);break;case 4:s.validity=o.bytes();break;case 5:s.sequence=o.uint64();break;case 6:s.ttl=o.uint64();break;case 7:s.pubKey=o.bytes();break;case 8:s.signatureV2=o.bytes();break;case 9:s.data=o.bytes();break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>_t(o,r.codec()),r.decode=o=>St(o,r.codec())})(He||(He={}));var lt=re(De(),1);var D0=Qe("ipns:utils"),P0=P("/ipns/"),G2=114,U0=async(r,e)=>{if(e==null||r==null){let n=new Error("one or more of the provided parameters are not defined");throw D0.error(n),(0,lt.default)(n,Uf)}let t;if(e.pubKey!=null){try{t=Tu(e.pubKey)}catch(o){throw D0.error(o),o}if(!(await Ad(e.pubKey)).equals(r))throw(0,lt.default)(new Error("Embedded public key did not match PeerID"),C0)}else r.publicKey!=null&&(t=Tu(r.publicKey));if(t!=null)return t;throw(0,lt.default)(new Error("no public key is available"),Uf)},F0=(r,e,t)=>{let n=P(e);return ue([r,t,n])},vc=r=>{let e=P("ipns-signature:");return ue([e,r])},Cr=r=>"signatureV1"in r?He.encode({value:P(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:P(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):He.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data});function je(r){let e=He.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,lt.default)(new Error("missing data or signatureV2"),Nr);let t=V0(e.data),n=Mf(t.Value),o=G(t.Validity);if(e.value!=null&&e.signatureV1!=null)return W2(e),{value:n,validityType:He.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:He.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 Lo=r=>ue([P0,r.toBytes()]),Oo=r=>Jo(r.slice(P0.length)),M0=(r,e,t,n,o)=>{let i;if(e===He.ValidityType.EOL)i=0;else throw(0,lt.default)(new Error("Unknown validity type"),Vi);return an({Value:r,Validity:t,ValidityType:i,Sequence:n,TTL:o})},V0=r=>{let e=tt(r);if(e.ValidityType===0)e.ValidityType=He.ValidityType.EOL;else throw(0,lt.default)(new Error("Unknown validity type"),Vi);return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e},Mf=r=>{if(r!=null){if(Mh(r))return`/ipns/${r.toCID().toString(zr)}`;if(r instanceof Uint8Array){let n=G(r);n.startsWith("/")&&(r=n)}let e=r.toString().trim();if(e.startsWith("/")&&e.length>1)return e;let t=z.asCID(r);if(t!=null)return t.code===G2?`/ipns/${t.toString(zr)}`:`/ipfs/${t.toV1().toString()}`;try{return r instanceof Uint8Array?`/ipfs/${z.decode(r).toV1().toString()}`:`/ipfs/${z.parse(e).toV1().toString()}`}catch{}}throw(0,lt.default)(new Error("Value must be a valid content path starting with /"),N0)},W2=r=>{if(r.data==null)throw(0,lt.default)(new Error("Record data is missing"),T0);let e=V0(r.data);if(!ne(e.Value,r.value??new Uint8Array(0)))throw(0,lt.default)(new Error('Field "value" did not match between protobuf and CBOR'),Nr);if(!ne(e.Validity,r.validity??new Uint8Array(0)))throw(0,lt.default)(new Error('Field "validity" did not match between protobuf and CBOR'),Nr);if(e.ValidityType!==r.validityType)throw(0,lt.default)(new Error('Field "validityType" did not match between protobuf and CBOR'),Nr);if(e.Sequence!==r.sequence)throw(0,lt.default)(new Error('Field "sequence" did not match between protobuf and CBOR'),Nr);if(e.TTL!==r.ttl)throw(0,lt.default)(new Error('Field "ttl" did not match between protobuf and CBOR'),Nr)};var j2=Qe("ipns"),Y2=Be.code,$0=60*60*1e9,X2="/ipns/",NL=X2.length,z0={v1Compatible:!0,ttlNs:$0};async function K0(r,e,t,n,o=z0){let i=new H0.default(Date.now()+Number(n)),s=He.ValidityType.EOL,a=BigInt(o.ttlNs!=null?o.ttlNs:$0);return Z2(r,e,t,s,i.toString(),a,o)}var Z2=async(r,e,t,n,o,i,s=z0)=>{t=BigInt(t);let a=P(o),c=Mf(e),l=P(c);if(r.privateKey==null)throw(0,Vf.default)(new Error("Missing private key"),L0);let f=await om(r.privateKey),u=M0(l,n,a,t,i),p=vc(u),h=await f.sign(p),m;if(r.publicKey!=null){let d=Xe(r.toBytes());(d.code!==Y2||!ne(r.publicKey,d.digest))&&(m=r.publicKey)}if(s.v1Compatible===!0){let d=await J2(f,l,n,a),y={value:c,signatureV1:d,validity:o,validityType:n,sequence:t,ttl:i,signatureV2:h,data:u};return m!=null&&(y.pubKey=m),y}else{let d={value:c,validity:o,validityType:n,sequence:t,ttl:i,signatureV2:h,data:u};return m!=null&&(d.pubKey=m),d}};var J2=async(r,e,t,n)=>{try{let o=F0(e,t,n);return await r.sign(o)}catch(o){throw j2.error("record signature creation failed",o),(0,Vf.default)(new Error("record signature creation failed"),B0)}};var Hi=re(De(),1),q0=re(Ec(),1);var Sc=Qe("ipns:validator"),Q2=1024*10,eS=async(r,e)=>{let t=je(e),n;try{let o=vc(t.data);n=await r.verify(o,t.signatureV2)}catch{n=!1}if(!n)throw Sc.error("record signature verification failed"),(0,Hi.default)(new Error("record signature verification failed"),Nr);if(t.validityType===He.ValidityType.EOL){if(q0.default.fromString(t.validity).toDate().getTime()<Date.now())throw Sc.error("record has expired"),(0,Hi.default)(new Error("record has expired"),k0)}else if(t.validityType!=null)throw Sc.error("unrecognized validity type"),(0,Hi.default)(new Error("unrecognized validity type"),Vi);Sc("ipns record for %s is valid",t.value)};async function $i(r,e){if(e.byteLength>Q2)throw(0,Hi.default)(new Error("record too large"),O0);let t=Oo(r),n=je(e),o=await U0(t,n);await eS(o,e)}async function*zi(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 i=n.split(e);n=i.pop()??"";for(let s=0;s<i.length;s++)yield JSON.parse(i[s])}n+=t.decode(),n!==""&&(yield JSON.parse(n))}function tS(r){return r[Symbol.asyncIterator]!=null}function rS(r){if(tS(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var Ac=rS;var Hf=P("/ipns/");function G0(r){return ne(r.subarray(0,Hf.byteLength),Hf)}var W0=r=>Jo(r.slice(Hf.length)),_c=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*Ke(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async put(e,t,n){if(!G0(e))return;let o=W0(e),i=je(t);await this.client.putIPNS(o,i,n)}async get(e,t){if(!G0(e))throw new N("Not found","ERR_NOT_FOUND");let n=W0(e);try{let o=await this.client.getIPNS(n,t);return Cr(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new N("Not found","ERR_NOT_FOUND"):o}}},Ic=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await Ac(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new N("Not found","ERR_NOT_FOUND")}async*getClosestPeers(e,t={}){}};var ut=Qe("delegated-routing-v1-http-api-client"),j0={concurrentRequests:4,timeout:3e4},Rc=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,me(1/0,this.shutDownController.signal),this.httpQueue=new at({concurrency:t.concurrentRequests??j0.concurrentRequests}),this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??j0.timeout,this.contentRouting=new _c(this),this.peerRouting=new Ic(this)}get[$o](){return this.contentRouting}get[Ko](){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={}){ut("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ye([this.shutDownController.signal,n,t.signal]);me(1/0,n,o);let i=fe(),s=fe();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.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 N("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new N("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let p of u.Providers){let h=this.#e(p);h!=null&&(yield h)}}else for await(let u of zi(xc(l.body))){let p=this.#e(u);p!=null&&(yield p)}}catch(a){ut.error("getProviders errored:",a)}finally{o.clear(),s.resolve(),ut("getProviders finished: %c",e)}}async*getPeers(e,t={}){ut("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ye([this.shutDownController.signal,n,t.signal]);me(1/0,n,o);let i=fe(),s=fe();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.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 N("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new N("Routing response had no body","ERR_BAD_RESPONSE");if(l.headers.get("Content-Type")==="application/json"){let u=await l.json();for(let p of u.Peers){let h=this.#e(p);h!=null&&(yield h)}}else for await(let u of zi(xc(l.body))){let p=this.#e(u);p!=null&&(yield p)}}catch(a){ut.error("getPeers errored:",a)}finally{o.clear(),s.resolve(),ut("getPeers finished: %c",e)}}async getIPNS(e,t={}){ut("getIPNS starts: %c",e);let n=AbortSignal.timeout(this.timeout),o=Ye([this.shutDownController.signal,n,t.signal]);me(1/0,n,o);let i=fe(),s=fe();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await i.promise;let l=await fetch(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(ut("getIPNS GET %s %d",a,l.status),l.status===404)throw new N("No matching records found.","ERR_NOT_FOUND");if(l.status===422)throw new N("Request does not conform to schema or semantic constraints.","ERR_INVALID_REQUEST");if(l.body==null)throw new N("GET ipns response had no body","ERR_BAD_RESPONSE");let f=await l.arrayBuffer(),u=new Uint8Array(f,0,f.byteLength);return t.validate!==!1&&await $i(Lo(e),u),je(u)}catch(c){throw ut.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),s.resolve(),ut("getIPNS finished: %c",e)}}async putIPNS(e,t,n={}){ut("putIPNS starts: %c",e);let o=AbortSignal.timeout(this.timeout),i=Ye([this.shutDownController.signal,o,n.signal]);me(1/0,o,i);let s=fe(),a=fe();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e.toCID().toString()}`;try{await s.promise;let l=Cr(t),u=await fetch(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i});if(ut("putIPNS PUT %s %d",c,u.status),u.status!==200)throw new N("PUT ipns response had status other than 200","ERR_BAD_RESPONSE")}catch(l){throw ut.error("putIPNS PUT %s error:",c,l.stack),l}finally{i.clear(),a.resolve(),ut("putIPNS finished: %c",e)}}#e(e){let t=[],n=e.Addrs?.map(Tr)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:Lt(e.ID),Addrs:n,Protocols:t}}};function Y0(r,e={}){return new Rc(new URL(r),e)}var X0=P("/ipns/");function Z0(r){return ne(r.subarray(0,X0.byteLength),X0)}var $f=class{client;constructor(e){this.client=Y0(e)}async provide(e,t){}async*findProviders(e,t){yield*Ke(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols}))}async put(e,t,n){if(!Z0(e))return;let o=Oo(e),i=je(t);await this.client.putIPNS(o,i,n)}async get(e,t){if(!Z0(e))throw new N("Not found","ERR_NOT_FOUND");let n=Oo(e);try{let o=await this.client.getIPNS(n,t);return Cr(o)}catch(o){throw o.code==="ERR_BAD_RESPONSE"?new N("Not found","ERR_NOT_FOUND"):o}}async findPeer(e,t){let n=await Ac(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new N("Not found","ERR_NOT_FOUND")}async*getClosestPeers(e,t){}};function Ki(r){return new $f(new URL(r))}var J0="[a-fA-F\\d:]",dn=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${J0})|(?<=${J0})(?=\\s|$))`:"",zt="(?: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}",_e="[a-fA-F\\d]{1,4}",kc=`
5
+ `));let e=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return t.length?`${e} :
6
+ ${t.join(`
7
+ `)}`:`${e} :`}};Vp=tn;M.Constructed=Vp;tn.NAME="CONSTRUCTED";var Vs=class extends Gt{fromBER(t,e,n){return e}toBER(t){return Fe}};Vs.override="EndOfContentValueBlock";var Hp,Hs=class extends Ut{constructor(t={}){super(t,Vs),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Hp=Hs;M.EndOfContent=Hp;Hs.NAME=ci;var $p,lo=class extends Ut{constructor(t={}){super(t,Gt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,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,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};$p=lo;M.Null=$p;lo.NAME="NULL";var $s=class extends Sr(Gt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=tt.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=tt.BufferSourceConverter.toUint8Array(t);return vr(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,of.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};$s.NAME="BooleanValueBlock";var zp,zs=class extends Ut{constructor(t={}){super(t,$s),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};zp=zs;M.Boolean=zp;zs.NAME="BOOLEAN";var qs=class extends Sr(Qe){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=Qe.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let i=0;i<this.value.length;i++){let s=this.value[i].constructor.NAME;if(s===ci){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(s!==Op)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?Qe.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};qs.NAME="OctetStringValueBlock";var qp,Ks=class r extends Ut{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},qs),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,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),e;if(!this.valueBlock.isConstructed){let i=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(i.byteLength){let s=ba(i,0,i.byteLength);s.offset!==-1&&s.offset===n&&(this.valueBlock.value=[s.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?tn.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${tt.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return tt.BufferSourceConverter.concat(t)}};qp=Ks;M.OctetString=qp;Ks.NAME=Op;var Gs=class extends Sr(Qe){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=Qe.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===ci){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Up)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let i=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,i,e,n))return-1;let s=i.subarray(e,e+n);if(this.unusedBits=s[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=s.subarray(1);try{if(a.byteLength){let c=ba(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,e+n}toBER(t,e){if(this.isConstructed)return Qe.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Fe;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}}};Gs.NAME="BitStringValueBlock";var Kp,uo=class extends Ut{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,i;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((i=n.value)===null||i===void 0)&&i.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Gs),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return tn.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};Kp=uo;M.BitString=Kp;uo.NAME=Up;var Gp;function OE(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<s?s:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=i[s-f]+a[c-f]+e[0];break;default:l=i[s-f]+e[0]}switch(e[0]=l/10,!0){case f>=i.length:i=Ls(new Uint8Array([l%10]),i);break;default:i[s-f]=l%10}}return e[0]>0&&(i=Ls(e,i)),i}function Dp(r){if(r>=si.length)for(let t=si.length;t<=r;t++){let e=new Uint8Array([0]),n=si[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let i=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=i[0]/10,n[o]=i[0]%10}e[0]>0&&(n=Ls(e,n)),si.push(n)}return si[r]}function UE(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),i=n.slice(0),s=i.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=i[s-u]-a[c-u]-e,!0){case l<0:e=1,i[s-u]=l+10;break;default:e=0,i[s-u]=l}if(e>0)for(let f=s-c+1;f>=0;f--,u++)if(l=i[s-u]-e,l<0)e=1,i[s-u]=l+10;else{e=0,i[s-u]=l;break}return i.slice()}var li=class extends Sr(Gt){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}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=of.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Np(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let i=this.fromBER(t,e,n);if(i===-1)return i;let s=this.valueHexView;return s[0]===0&&s[1]&128?this.valueHexView=s.subarray(1):o!==0&&s.length<o&&(o-s.length>1&&(o=s.length+1),this.valueHexView=s.subarray(o-s.length)),i}toDER(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=new Uint8Array(this.valueHexView.length*8/3),n=0,o,i=this.valueHexView,s="",a=!1;for(let c=i.byteLength-1;c>=0;c--){o=i[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case t:e=UE(Dp(n),e),s="-";break;default:e=OE(e,Dp(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(s+=Pp.charAt(e[c]));return a===!1&&(s+=Pp.charAt(0)),s}};Gp=li;li.NAME="IntegerValueBlock";Object.defineProperty(Gp.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Wp,Ft=class r extends Ut{constructor(t={}){super(t,li),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Ps(),BigInt(this.valueBlock.toString())}static fromBigInt(t){Ps();let e=BigInt(t),n=new ai,o=e.toString(16).replace(/^-/,""),i=new Uint8Array(tt.Convert.FromHex(o));if(e<0){let a=new Uint8Array(i.length+(i[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${tt.Convert.ToHex(a)}`)+e,u=tt.BufferSourceConverter.toUint8Array(tt.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else i[0]&128&&n.write(new Uint8Array([0])),n.write(i);return new r({valueHex:n.final()})}convertToDER(){let t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}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()}`}};Wp=Ft;M.Integer=Wp;Ft.NAME="INTEGER";var jp,Ws=class extends Ft{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};jp=Ws;M.Enumerated=jp;Ws.NAME="ENUMERATED";var ui=class extends Sr(Gt){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;let i=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=_n(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){Ps();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let e=Qr(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",Fe;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),i=e.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n}toString(){let t="";if(this.isHexOnly)t=tt.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};ui.NAME="sidBlock";var js=class extends Gt{constructor({value:t=ho,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let i=new ui;if(o=i.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.value.length===0&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,Fe;e.push(o)}return sf(e)}fromString(t){this.value=[];let e=0,n=0,o="",i=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1,i){let s=this.value[0],a=0;switch(s.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;s.valueDec=c+a,i=!1}else{let s=new ui;if(o>Number.MAX_SAFE_INTEGER){Ps();let a=BigInt(o);s.valueBigInt=a}else if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return;this.value.length||(s.isFirstSid=!0,i=!0),this.value.push(s)}while(n!==-1)}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};js.NAME="ObjectIdentifierValueBlock";var Yp,fo=class extends Ut{constructor(t={}){super(t,js),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Yp=fo;M.ObjectIdentifier=Yp;fo.NAME="OBJECT IDENTIFIER";var fi=class extends Sr(br){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=tt.BufferSourceConverter.toUint8Array(t);if(!vr(this,o,e,n))return-1;let i=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=i[a]&127,this.blockLength++,!!(i[a]&128));a++);let s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)s[a]=this.valueHexView[a];return this.valueHexView=s,i[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=_n(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,i=new Uint8Array(this.blockLength);for(let s=0;s<this.blockLength-1;s++)i[s]=o[s]|128;return i[this.blockLength-1]=o[this.blockLength-1],i.buffer}let e=Qr(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",Fe;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),i=e.byteLength-1;for(let s=0;s<i;s++)n[s]=o[s]|128;n[i]=o[i]}return n.buffer}toString(){let t="";return this.isHexOnly?t=tt.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};fi.NAME="relativeSidBlock";var Ys=class extends Gt{constructor({value:t=ho,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let i=new fi;if(o=i.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=i.error,o;this.blockLength+=i.blockLength,n-=i.blockLength,this.value.push(i)}return o}toBER(t,e){let n=[];for(let o=0;o<this.value.length;o++){let i=this.value[o].toBER(t);if(i.byteLength===0)return this.error=this.value[o].error,Fe;n.push(i)}return sf(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let i=new fi;if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Ys.NAME="RelativeObjectIdentifierValueBlock";var Xp,Xs=class extends Ut{constructor(t={}){super(t,Ys),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Xp=Xs;M.RelativeObjectIdentifier=Xp;Xs.NAME="RelativeObjectIdentifier";var Zp,xr=class extends tn{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Zp=xr;M.Sequence=Zp;xr.NAME="SEQUENCE";var Jp,Zs=class extends tn{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Jp=Zs;M.Set=Jp;Zs.NAME="SET";var Js=class extends Sr(Gt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=ho}toJSON(){return{...super.toJSON(),value:this.value}}};Js.NAME="StringValueBlock";var Qs=class extends Js{};Qs.NAME="SimpleStringValueBlock";var Zt=class extends Us{constructor({...t}={}){super(t,Qs)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,tt.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Zt.NAME="SIMPLE STRING";var ta=class extends Zt{fromBuffer(t){this.valueBlock.valueHexView=tt.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=tt.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=tt.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(tt.Convert.FromUtf8String(t)),this.valueBlock.value=t}};ta.NAME="Utf8StringValueBlock";var Qp,Er=class extends ta{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Qp=Er;M.Utf8String=Qp;Er.NAME="UTF8String";var ea=class extends Zt{fromBuffer(t){this.valueBlock.value=tt.Convert.ToUtf16String(t),this.valueBlock.valueHexView=tt.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(tt.Convert.FromUtf16String(t))}};ea.NAME="BmpStringValueBlock";var tm,ra=class extends ea{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};tm=ra;M.BmpString=tm;ra.NAME="BMPString";var na=class extends Zt{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);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(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let i=Qr(t.charCodeAt(o),8),s=new Uint8Array(i);if(s.length>4)continue;let a=4-s.length;for(let c=s.length-1;c>=0;c--)n[o*4+c+a]=s[c]}this.valueBlock.value=t}};na.NAME="UniversalStringValueBlock";var em,oa=class extends na{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};em=oa;M.UniversalString=em;oa.NAME="UniversalString";var rm,ia=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};rm=ia;M.NumericString=rm;ia.NAME="NumericString";var nm,sa=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};nm=sa;M.PrintableString=nm;sa.NAME="PrintableString";var om,aa=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};om=aa;M.TeletexString=om;aa.NAME="TeletexString";var im,ca=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};im=ca;M.VideotexString=im;ca.NAME="VideotexString";var sm,la=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};sm=la;M.IA5String=sm;la.NAME="IA5String";var am,ua=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};am=ua;M.GraphicString=am;ua.NAME="GraphicString";var cm,hi=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};cm=hi;M.VisibleString=cm;hi.NAME="VisibleString";var lm,fa=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};lm=fa;M.GeneralString=lm;fa.NAME="GeneralString";var um,ha=class extends Zt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};um=ha;M.CharacterString=um;ha.NAME="CharacterString";var fm,di=class extends hi{constructor({value:t,valueDate:e,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,tt.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);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(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=he(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=he(this.month,2),e[2]=he(this.day,2),e[3]=he(this.hour,2),e[4]=he(this.minute,2),e[5]=he(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}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}}};fm=di;M.UTCTime=fm;di.NAME="UTCTime";var hm,da=class extends di{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",i=0,s,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let f=new Number(t[t.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),h="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(h=n.substring(d+1),n=n.substring(0,d),h.length!==2&&h.length!==4)throw new Error("Wrong input string for conversion");let m=parseInt(h.substring(0,2),10);if(isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*m,h.length===4){if(m=parseInt(h.substring(2,4),10),isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");c=f*m}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");i=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(s=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*i;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===12:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*i;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(s=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*i;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=s.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push(he(this.year,4)),e.push(he(this.month,2)),e.push(he(this.day,2)),e.push(he(this.hour,2)),e.push(he(this.minute,2)),e.push(he(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(he(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};hm=da;M.GeneralizedTime=hm;da.NAME="GeneralizedTime";var dm,pa=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};dm=pa;M.DATE=dm;pa.NAME="DATE";var pm,ma=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};pm=ma;M.TimeOfDay=pm;ma.NAME="TimeOfDay";var mm,ga=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};mm=ga;M.DateTime=mm;ga.NAME="DateTime";var gm,ya=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};gm=ya;M.Duration=gm;ya.NAME="Duration";var ym,wa=class extends Er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};ym=wa;M.TIME=ym;wa.NAME="TIME";function q(r,t="utf8"){let e=ys[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function xa(r){if(isNaN(r)||r<=0)throw new gt("random bytes length must be a Number bigger than 0");return no(r)}var pi=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Ea=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var wm={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Ea("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var en=wm;async function bm(r){let t=await en.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await ME(t);return{privateKey:e[0],publicKey:e[1]}}async function xm(r,t){let e=await en.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await en.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Em(r,t,e){let n=await en.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return en.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function ME(r){if(r.privateKey==null||r.publicKey==null)throw new gt("Private and public key are required");return Promise.all([en.get().subtle.exportKey("jwk",r.privateKey),en.get().subtle.exportKey("jwk",r.publicKey)])}function lf(r){if(r.kty!=="RSA")throw new gt("invalid key type");if(r.n==null)throw new gt("invalid key modulus");return D(r.n,"base64url").length*8}var po=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=mi.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return L.createV1(114,this._multihash)}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}verify(t,e){return Em(this._key,e,t)}},gi=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=mi.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}sign(t){return xm(this._key,t)}};var va=8192,uf=18;function vm(r){let{result:t}=cf(r),e=t.valueBlock.value;return{n:q(tr(e[1].toBigInt()),"base64url"),e:q(tr(e[2].toBigInt()),"base64url"),d:q(tr(e[3].toBigInt()),"base64url"),p:q(tr(e[4].toBigInt()),"base64url"),q:q(tr(e[5].toBigInt()),"base64url"),dp:q(tr(e[6].toBigInt()),"base64url"),dq:q(tr(e[7].toBigInt()),"base64url"),qi:q(tr(e[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function VE(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 gt("JWK was missing components");let e=new xr({value:[new Ft({value:0}),Ft.fromBigInt(er(D(r.n,"base64url"))),Ft.fromBigInt(er(D(r.e,"base64url"))),Ft.fromBigInt(er(D(r.d,"base64url"))),Ft.fromBigInt(er(D(r.p,"base64url"))),Ft.fromBigInt(er(D(r.q,"base64url"))),Ft.fromBigInt(er(D(r.dp,"base64url"))),Ft.fromBigInt(er(D(r.dq,"base64url"))),Ft.fromBigInt(er(D(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function Sm(r){let{result:t}=cf(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:q(tr(e[0].toBigInt()),"base64url"),e:q(tr(e[1].toBigInt()),"base64url")}}function ff(r){if(r.n==null||r.e==null)throw new gt("JWK was missing components");let e=new xr({value:[new xr({value:[new fo({value:"1.2.840.113549.1.1.1"}),new lo]}),new uo({valueHex:new xr({value:[Ft.fromBigInt(er(D(r.n,"base64url"))),Ft.fromBigInt(er(D(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function tr(r){let t=r.toString(16);t.length%2>0&&(t=`0${t}`);let e=t.length/2,n=new Uint8Array(e),o=0,i=0;for(;o<e;)n[o]=parseInt(t.slice(i,i+2),16),o+=1,i+=2;return n}function er(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}function Am(r){let t=vm(r);return Im(t)}function hf(r){let t=Sm(r);if(lf(t)>va)throw new zn("Key size is too large");let e=ao(Je.encode({Type:Tt.RSA,Data:r})),n=Pe(uf,e);return new po(t,n)}function Im(r){if(lf(r)>va)throw new gt("Key size is too large");let t=_m(r),e=ao(Je.encode({Type:Tt.RSA,Data:ff(t.publicKey)})),n=Pe(uf,e);return new gi(t.privateKey,new po(t.publicKey,n))}async function km(r){if(r>va)throw new gt("Key size is too large");let t=await bm(r),e=ao(Je.encode({Type:Tt.RSA,Data:ff(t.publicKey)})),n=Pe(uf,e);return new gi(t.privateKey,new po(t.publicKey,n))}function _m(r){if(r==null)throw new gt("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var Sa=class extends ro{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,lp(t);let n=ri(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(n.length>o?t.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=t.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),i.fill(0)}update(t){return eo(this),this.iHash.update(t),this}digestInto(t){eo(this),to(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},df=(r,t,e)=>new Sa(r,t).update(e).digest();df.create=(r,t)=>new Sa(r,t);function Bm(r){r.lowS!==void 0&&Oe("lowS",r.lowS),r.prehash!==void 0&&Oe("prehash",r.prehash)}function HE(r){let t=ii(r);Ze(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:$E,hexToBytes:zE}=As,Ar={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=Ar;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=vn(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let i=n>127?vn(o.length/2|128):"";return`${vn(r)}${i}${o}${t}`},decode(r,t){let{Err:e}=Ar,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(r){let{Err:t}=Ar;if(r<Ir)throw new t("integer: negative integers are not allowed");let e=vn(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected assertion");return e},decode(r){let{Err:t}=Ar;if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return $E(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Ar,o=typeof r=="string"?zE(r):r;io(o);let{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("Invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=Ar,n=`${t.encode(2,e.encode(r.r))}${t.encode(2,e.encode(r.s))}`;return t.encode(48,n)}},Ir=BigInt(0),Lt=BigInt(1),ET=BigInt(2),Tm=BigInt(3),vT=BigInt(4);function qE(r){let t=HE(r),{Fp:e}=t,n=Xr(t.n,t.nBitLength),o=t.toBytes||((p,y,g)=>{let x=y.toAffine();return yr(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),i=t.fromBytes||(p=>{let y=p.subarray(1),g=e.fromBytes(y.subarray(0,e.BYTES)),x=e.fromBytes(y.subarray(e.BYTES,2*e.BYTES));return{x:g,y:x}});function s(p){let{a:y,b:g}=t,x=e.sqr(p),b=e.mul(x,p);return e.add(e.add(b,e.mul(p,y)),g)}if(!e.eql(e.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function a(p){return ni(p,Lt,t.n)}function c(p){let{allowedPrivateKeyLengths:y,nByteLength:g,wrapPrivateKey:x,n:b}=t;if(y&&typeof p!="bigint"){if(Wr(p)&&(p=mr(p)),typeof p!="string"||!y.includes(p.length))throw new Error("Invalid key");p=p.padStart(g*2,"0")}let E;try{E=typeof p=="bigint"?p:gr(xt("private key",p,g))}catch{throw new Error(`private key must be ${g} bytes, hex or bigint, not ${typeof p}`)}return x&&(E=at(E,b)),ue("private key",E,Lt,b),E}function l(p){if(!(p instanceof d))throw new Error("ProjectivePoint expected")}let u=In((p,y)=>{let{px:g,py:x,pz:b}=p;if(e.eql(b,e.ONE))return{x:g,y:x};let E=p.is0();y==null&&(y=E?e.ONE:e.inv(b));let k=e.mul(g,y),T=e.mul(x,y),S=e.mul(b,y);if(E)return{x:e.ZERO,y:e.ZERO};if(!e.eql(S,e.ONE))throw new Error("invZ was invalid");return{x:k,y:T}}),f=In(p=>{if(p.is0()){if(t.allowInfinityPoint&&!e.is0(p.py))return;throw new Error("bad point: ZERO")}let{x:y,y:g}=p.toAffine();if(!e.isValid(y)||!e.isValid(g))throw new Error("bad point: x or y not FE");let x=e.sqr(g),b=s(y);if(!e.eql(x,b))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(y,g,x){if(this.px=y,this.py=g,this.pz=x,y==null||!e.isValid(y))throw new Error("x required");if(g==null||!e.isValid(g))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(y){let{x:g,y:x}=y||{};if(!y||!e.isValid(g)||!e.isValid(x))throw new Error("invalid affine point");if(y instanceof d)throw new Error("projective point not allowed");let b=E=>e.eql(E,e.ZERO);return b(g)&&b(x)?d.ZERO:new d(g,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){let g=e.invertBatch(y.map(x=>x.pz));return y.map((x,b)=>x.toAffine(g[b])).map(d.fromAffine)}static fromHex(y){let g=d.fromAffine(i(xt("pointHex",y)));return g.assertValidity(),g}static fromPrivateKey(y){return d.BASE.multiply(c(y))}static msm(y,g){return _s(d,n,y,g)}_setWindowSize(y){m.setWindowSize(this,y)}assertValidity(){f(this)}hasEvenY(){let{y}=this.toAffine();if(e.isOdd)return!e.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){l(y);let{px:g,py:x,pz:b}=this,{px:E,py:k,pz:T}=y,S=e.eql(e.mul(g,T),e.mul(E,b)),v=e.eql(e.mul(x,T),e.mul(k,b));return S&&v}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:y,b:g}=t,x=e.mul(g,Tm),{px:b,py:E,pz:k}=this,T=e.ZERO,S=e.ZERO,v=e.ZERO,_=e.mul(b,b),z=e.mul(E,E),F=e.mul(k,k),U=e.mul(b,E);return U=e.add(U,U),v=e.mul(b,k),v=e.add(v,v),T=e.mul(y,v),S=e.mul(x,F),S=e.add(T,S),T=e.sub(z,S),S=e.add(z,S),S=e.mul(T,S),T=e.mul(U,T),v=e.mul(x,v),F=e.mul(y,F),U=e.sub(_,F),U=e.mul(y,U),U=e.add(U,v),v=e.add(_,_),_=e.add(v,_),_=e.add(_,F),_=e.mul(_,U),S=e.add(S,_),F=e.mul(E,k),F=e.add(F,F),_=e.mul(F,U),T=e.sub(T,_),v=e.mul(F,z),v=e.add(v,v),v=e.add(v,v),new d(T,S,v)}add(y){l(y);let{px:g,py:x,pz:b}=this,{px:E,py:k,pz:T}=y,S=e.ZERO,v=e.ZERO,_=e.ZERO,z=t.a,F=e.mul(t.b,Tm),U=e.mul(g,E),P=e.mul(x,k),R=e.mul(b,T),N=e.add(g,x),I=e.add(E,k);N=e.mul(N,I),I=e.add(U,P),N=e.sub(N,I),I=e.add(g,b);let A=e.add(E,T);return I=e.mul(I,A),A=e.add(U,R),I=e.sub(I,A),A=e.add(x,b),S=e.add(k,T),A=e.mul(A,S),S=e.add(P,R),A=e.sub(A,S),_=e.mul(z,I),S=e.mul(F,R),_=e.add(S,_),S=e.sub(P,_),_=e.add(P,_),v=e.mul(S,_),P=e.add(U,U),P=e.add(P,U),R=e.mul(z,R),I=e.mul(F,I),P=e.add(P,R),R=e.sub(U,R),R=e.mul(z,R),I=e.add(I,R),U=e.mul(P,I),v=e.add(v,U),U=e.mul(A,I),S=e.mul(N,S),S=e.sub(S,U),U=e.mul(N,P),_=e.mul(A,_),_=e.add(_,U),new d(S,v,_)}subtract(y){return this.add(y.negate())}is0(){return this.equals(d.ZERO)}wNAF(y){return m.wNAFCached(this,y,d.normalizeZ)}multiplyUnsafe(y){ue("scalar",y,Ir,t.n);let g=d.ZERO;if(y===Ir)return g;if(y===Lt)return this;let{endo:x}=t;if(!x)return m.unsafeLadder(this,y);let{k1neg:b,k1:E,k2neg:k,k2:T}=x.splitScalar(y),S=g,v=g,_=this;for(;E>Ir||T>Ir;)E&Lt&&(S=S.add(_)),T&Lt&&(v=v.add(_)),_=_.double(),E>>=Lt,T>>=Lt;return b&&(S=S.negate()),k&&(v=v.negate()),v=new d(e.mul(v.px,x.beta),v.py,v.pz),S.add(v)}multiply(y){let{endo:g,n:x}=t;ue("scalar",y,Lt,x);let b,E;if(g){let{k1neg:k,k1:T,k2neg:S,k2:v}=g.splitScalar(y),{p:_,f:z}=this.wNAF(T),{p:F,f:U}=this.wNAF(v);_=m.constTimeNegate(k,_),F=m.constTimeNegate(S,F),F=new d(e.mul(F.px,g.beta),F.py,F.pz),b=_.add(F),E=z.add(U)}else{let{p:k,f:T}=this.wNAF(y);b=k,E=T}return d.normalizeZ([b,E])[0]}multiplyAndAddUnsafe(y,g,x){let b=d.BASE,E=(T,S)=>S===Ir||S===Lt||!T.equals(b)?T.multiplyUnsafe(S):T.multiply(S),k=E(this,g).add(E(y,x));return k.is0()?void 0:k}toAffine(y){return u(this,y)}isTorsionFree(){let{h:y,isTorsionFree:g}=t;if(y===Lt)return!0;if(g)return g(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:y,clearCofactor:g}=t;return y===Lt?this:g?g(d,this):this.multiplyUnsafe(t.h)}toRawBytes(y=!0){return Oe("isCompressed",y),this.assertValidity(),o(d,this,y)}toHex(y=!0){return Oe("isCompressed",y),mr(this.toRawBytes(y))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let h=t.nBitLength,m=ks(d,t.endo?Math.ceil(h/2):h);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:a}}function KE(r){let t=ii(r);return Ze(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Cm(r){let t=KE(r),{Fp:e,n}=t,o=e.BYTES+1,i=2*e.BYTES+1;function s(R){return at(R,n)}function a(R){return Is(R,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=qE({...t,toBytes(R,N,I){let A=N.toAffine(),C=e.toBytes(A.x),V=yr;return Oe("isCompressed",I),I?V(Uint8Array.from([N.hasEvenY()?2:3]),C):V(Uint8Array.from([4]),C,e.toBytes(A.y))},fromBytes(R){let N=R.length,I=R[0],A=R.subarray(1);if(N===o&&(I===2||I===3)){let C=gr(A);if(!ni(C,Lt,e.ORDER))throw new Error("Point is not on curve");let V=u(C),K;try{K=e.sqrt(V)}catch(et){let Q=et instanceof Error?": "+et.message:"";throw new Error("Point is not on curve"+Q)}let G=(K&Lt)===Lt;return(I&1)===1!==G&&(K=e.neg(K)),{x:C,y:K}}else if(N===i&&I===4){let C=e.fromBytes(A.subarray(0,e.BYTES)),V=e.fromBytes(A.subarray(e.BYTES,2*e.BYTES));return{x:C,y:V}}else throw new Error(`Point of length ${N} was invalid. Expected ${o} compressed bytes or ${i} uncompressed bytes`)}}),d=R=>mr(Yr(R,t.nByteLength));function h(R){let N=n>>Lt;return R>N}function m(R){return h(R)?s(-R):R}let p=(R,N,I)=>gr(R.slice(N,I));class y{constructor(N,I,A){this.r=N,this.s=I,this.recovery=A,this.assertValidity()}static fromCompact(N){let I=t.nByteLength;return N=xt("compactSignature",N,I*2),new y(p(N,0,I),p(N,I,2*I))}static fromDER(N){let{r:I,s:A}=Ar.toSig(xt("DER",N));return new y(I,A)}assertValidity(){ue("r",this.r,Lt,n),ue("s",this.s,Lt,n)}addRecoveryBit(N){return new y(this.r,this.s,N)}recoverPublicKey(N){let{r:I,s:A,recovery:C}=this,V=T(xt("msgHash",N));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");let K=C===2||C===3?I+t.n:I;if(K>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let G=C&1?"03":"02",J=c.fromHex(G+d(K)),et=a(K),Q=s(-V*et),st=s(A*et),lt=c.BASE.multiplyAndAddUnsafe(J,Q,st);if(!lt)throw new Error("point at infinify");return lt.assertValidity(),lt}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return Sn(this.toDERHex())}toDERHex(){return Ar.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Sn(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let g={isValidPrivateKey(R){try{return l(R),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let R=ju(t.n);return vp(t.randomBytes(R),t.n)},precompute(R=8,N=c.BASE){return N._setWindowSize(R),N.multiply(BigInt(3)),N}};function x(R,N=!0){return c.fromPrivateKey(R).toRawBytes(N)}function b(R){let N=Wr(R),I=typeof R=="string",A=(N||I)&&R.length;return N?A===o||A===i:I?A===2*o||A===2*i:R instanceof c}function E(R,N,I=!0){if(b(R))throw new Error("first arg must be private key");if(!b(N))throw new Error("second arg must be public key");return c.fromHex(N).multiply(l(R)).toRawBytes(I)}let k=t.bits2int||function(R){let N=gr(R),I=R.length*8-t.nBitLength;return I>0?N>>BigInt(I):N},T=t.bits2int_modN||function(R){return s(k(R))},S=oi(t.nBitLength);function v(R){return ue(`num < 2^${t.nBitLength}`,R,Ir,S),Yr(R,t.nByteLength)}function _(R,N,I=z){if(["recovered","canonical"].some(Nt=>Nt in I))throw new Error("sign() legacy options not supported");let{hash:A,randomBytes:C}=t,{lowS:V,prehash:K,extraEntropy:G}=I;V==null&&(V=!0),R=xt("msgHash",R),Bm(I),K&&(R=xt("prehashed msgHash",A(R)));let J=T(R),et=l(N),Q=[v(et),v(J)];if(G!=null&&G!==!1){let Nt=G===!0?C(e.BYTES):G;Q.push(xt("extraEntropy",Nt))}let st=yr(...Q),lt=J;function Rt(Nt){let Dt=k(Nt);if(!f(Dt))return;let jt=a(Dt),kt=c.BASE.multiply(Dt).toAffine(),ee=s(kt.x);if(ee===Ir)return;let lr=s(jt*s(lt+ee*et));if(lr===Ir)return;let Ko=(kt.x===ee?0:2)|Number(kt.y&Lt),Go=lr;return V&&h(lr)&&(Go=m(lr),Ko^=1),new y(ee,Go,Ko)}return{seed:st,k2sig:Rt}}let z={lowS:t.lowS,prehash:!1},F={lowS:t.lowS,prehash:!1};function U(R,N,I=z){let{seed:A,k2sig:C}=_(R,N,I),V=t;return qu(V.hash.outputLen,V.nByteLength,V.hmac)(A,C)}c.BASE._setWindowSize(8);function P(R,N,I,A=F){let C=R;if(N=xt("msgHash",N),I=xt("publicKey",I),"strict"in A)throw new Error("options.strict was renamed to lowS");Bm(A);let{lowS:V,prehash:K}=A,G,J;try{if(typeof C=="string"||Wr(C))try{G=y.fromDER(C)}catch(kt){if(!(kt instanceof Ar.Err))throw kt;G=y.fromCompact(C)}else if(typeof C=="object"&&typeof C.r=="bigint"&&typeof C.s=="bigint"){let{r:kt,s:ee}=C;G=new y(kt,ee)}else throw new Error("PARSE");J=c.fromHex(I)}catch(kt){if(kt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(V&&G.hasHighS())return!1;K&&(N=t.hash(N));let{r:et,s:Q}=G,st=T(N),lt=a(Q),Rt=s(st*lt),Nt=s(et*lt),Dt=c.BASE.multiplyAndAddUnsafe(J,Rt,Nt)?.toAffine();return Dt?s(Dt.x)===et:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:E,sign:U,verify:P,ProjectivePoint:c,Signature:y,utils:g}}function GE(r){return{hash:r,hmac:(t,...e)=>df(r,t,Ou(...e)),randomBytes:no}}function Rm(r,t){let e=n=>Cm({...r,...GE(n)});return Object.freeze({...e(t),create:e})}var Pm=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Nm=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),WE=BigInt(1),pf=BigInt(2),Lm=(r,t)=>(r+t/pf)/t;function jE(r){let t=Pm,e=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=dt(u,e,t)*u%t,d=dt(f,e,t)*u%t,h=dt(d,pf,t)*l%t,m=dt(h,o,t)*h%t,p=dt(m,i,t)*m%t,y=dt(p,a,t)*p%t,g=dt(y,c,t)*y%t,x=dt(g,a,t)*p%t,b=dt(x,e,t)*u%t,E=dt(b,s,t)*m%t,k=dt(E,n,t)*l%t,T=dt(k,pf,t);if(!mf.eql(mf.sqr(T),r))throw new Error("Cannot find square root");return T}var mf=Xr(Pm,void 0,void 0,{sqrt:jE}),Bn=Rm({a:BigInt(0),b:BigInt(7),Fp:mf,n:Nm,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Nm,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-WE*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=e,s=BigInt("0x100000000000000000000000000000000"),a=Lm(i*r,t),c=Lm(-n*r,t),l=at(r-a*e-c*o,t),u=at(-a*n-c*i,t),f=l>s,d=u>s;if(f&&(l=t-l),d&&(u=t-u),l>s||u>s)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},ao),RT=BigInt(0);var NT=Bn.ProjectivePoint;function Dm(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Om(r,t,e){let n=Xe.digest(e instanceof Uint8Array?e:e.subarray());if(Dm(n))return n.then(({digest:o})=>Bn.verify(t,o,r)).catch(o=>{throw new pi(String(o))});try{return Bn.verify(t,n.digest,r)}catch(o){throw new pi(String(o))}}var Aa=class{type="secp256k1";raw;_key;constructor(t){this._key=Fm(t),this.raw=Um(this._key)}toMultihash(){return bt.digest(so(this))}toCID(){return L.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Z(this.raw,t.raw)}verify(t,e){return Om(this._key,e,t)}};function gf(r){return new Aa(r)}function Um(r){return Bn.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Fm(r){try{return Bn.ProjectivePoint.fromHex(r),r}catch(t){throw new zn(String(t))}}function Ia(r){let{Type:t,Data:e}=Je.decode(r),n=e??new Uint8Array;switch(t){case Tt.RSA:return hf(n);case Tt.Ed25519:return Qu(n);case Tt.secp256k1:return gf(n);default:throw new pn}}function rn(r){let{Type:t,Data:e}=Je.decode(r.digest),n=e??new Uint8Array;switch(t){case Tt.Ed25519:return Qu(n);case Tt.secp256k1:return gf(n);default:throw new pn}}function so(r){return Je.encode({Type:Tt[r.type],Data:r.raw})}var Mm=Symbol.for("nodejs.util.inspect.custom"),YE=114,yi=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[$n]=!0;toString(){return this.string==null&&(this.string=Y.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return L.createV1(YE,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Z(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Z(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Mm](){return`PeerId(${this.toString()})`}},ka=class extends yi{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},_a=class extends yi{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Ba=class extends yi{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},XE=2336,wi=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=bt.digest(D(this.url))}[Mm](){return`PeerId(${this.url})`}[$n]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return L.createV1(XE,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=q(t)),t.toString()===this.toString())}};var ZE=114,Vm=2336;function mo(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=wt(Y.decode(`z${r}`));else{if(t==null)throw new gt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=wt(t.decode(r))}return Hm(e)}function Hm(r){if(QE(r))return new ka({multihash:r});if(JE(r))try{let t=rn(r);if(t.type==="Ed25519")return new _a({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Ba({multihash:r,publicKey:t})}catch{let e=q(r.digest);return new wi(new URL(e))}throw new Ae("Supplied PeerID Multihash is invalid")}function $m(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==ZE&&r.code!==Vm)throw new Yo("Supplied PeerID CID is invalid");if(r.code===Vm){let t=q(r.multihash.digest);return new wi(new URL(t))}return Hm(r.multihash)}function JE(r){return r.code===bt.code}function QE(r){return r.code===Xe.code}function tv(r,t){try{if(typeof r=="string"&&r.length>0)return ev(r);if(typeof r=="number"&&isFinite(r))return t?.long?nv(r):rv(r);throw new Error("Value is not a string or number.")}catch(e){let n=ov(e)?`${e.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function ev(r){if(r=String(r),r.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let t=/^(-?(?:\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(!t)return NaN;let e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*315576e5;case"weeks":case"week":case"w":return e*6048e5;case"days":case"day":case"d":return e*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return e*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return e*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return e*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var Ra=tv;function rv(r){let t=Math.abs(r);return t>=864e5?`${Math.round(r/864e5)}d`:t>=36e5?`${Math.round(r/36e5)}h`:t>=6e4?`${Math.round(r/6e4)}m`:t>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function nv(r){let t=Math.abs(r);return t>=864e5?Ca(r,t,864e5,"day"):t>=36e5?Ca(r,t,36e5,"hour"):t>=6e4?Ca(r,t,6e4,"minute"):t>=1e3?Ca(r,t,1e3,"second"):`${r} ms`}function Ca(r,t,e,n){let o=t>=e*1.5;return`${Math.round(r/e)} ${n}${o?"s":""}`}function ov(r){return typeof r=="object"&&r!==null&&"message"in r}function wf(r){e.debug=e,e.default=e,e.coerce=c,e.disable=i,e.enable=o,e.enabled=s,e.humanize=Ra,e.destroy=l,Object.keys(r).forEach(u=>{e[u]=r[u]}),e.names=[],e.skips=[],e.formatters={};function t(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return e.colors[Math.abs(f)%e.colors.length]}e.selectColor=t;function e(u){let f,d=null,h,m;function p(...y){if(!p.enabled)return;let g=p,x=Number(new Date),b=x-(f||x);g.diff=b,g.prev=f,g.curr=x,f=x,y[0]=e.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let E=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(T,S)=>{if(T==="%%")return"%";E++;let v=e.formatters[S];if(typeof v=="function"){let _=y[E];T=v.call(g,_),y.splice(E,1),E--}return T}),e.formatArgs.call(g,y),(g.log||e.log).apply(g,y)}return p.namespace=u,p.useColors=e.useColors(),p.color=e.selectColor(u),p.extend=n,p.destroy=e.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==e.namespaces&&(h=e.namespaces,m=e.enabled(u)),m),set:y=>{d=y}}),typeof e.init=="function"&&e.init(p),p}function n(u,f){let d=e(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function o(u){e.save(u),e.namespaces=u,e.names=[],e.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?e.skips.push(new RegExp("^"+u.substr(1)+"$")):e.names.push(new RegExp("^"+u+"$")))}function i(){let u=[...e.names.map(a),...e.skips.map(a).map(f=>"-"+f)].join(",");return e.enable(""),u}function s(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=e.skips.length;f<d;f++)if(e.skips[f].test(u))return!1;for(f=0,d=e.names.length;f<d;f++)if(e.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.setupFormatters(e.formatters),e.enable(e.load()),e}var Na=fv(),iv=["#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 sv(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function av(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ra(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}var cv=console.debug??console.log??(()=>{});function lv(r){try{r?Na?.setItem("debug",r):Na?.removeItem("debug")}catch{}}function uv(){let r;try{r=Na?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function fv(){try{return localStorage}catch{}}function hv(r){r.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}var Km=wf({formatArgs:av,save:lv,load:uv,useColors:sv,setupFormatters:hv,colors:iv,storage:Na,log:cv});var W=Km;W.formatters.b=r=>r==null?"undefined":Y.baseEncode(r);W.formatters.t=r=>r==null?"undefined":St.baseEncode(r);W.formatters.m=r=>r==null?"undefined":se.baseEncode(r);W.formatters.p=r=>r==null?"undefined":r.toString();W.formatters.c=r=>r==null?"undefined":r.toString();W.formatters.k=r=>r==null?"undefined":r.toString();W.formatters.a=r=>r==null?"undefined":r.toString();W.formatters.e=r=>r==null?"undefined":r.stack??r.message;function dv(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function Gm(){return{forComponent(r){return pv(r)}}}function pv(r){let t=dv(`${r}:trace`);return W.enabled(`${r}:trace`)&&W.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=W(`${r}:trace`)),Object.assign(W(r),{error:W(`${r}:error`),trace:t})}var xf=Ot(jm(),1);var Ei=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Ef=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Ym=r=>globalThis.DOMException===void 0?new Ef(r):new DOMException(r),Xm=r=>{let t=r.reason===void 0?Ym("This operation was aborted."):r.reason;return t instanceof Error?t:Ym(t)};function vi(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=t,s,c=new Promise((l,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:d}=t;d.aborted&&u(Xm(d)),d.addEventListener("abort",()=>{u(Xm(d))})}if(e===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new Ei;s=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){u(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?u(o):(f.message=o??`Promise timed out after ${e} milliseconds`,u(f))},e),(async()=>{try{l(await r)}catch(d){u(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{i.clearTimeout.call(void 0,s),s=void 0},c}function vf(r,t,e){let n=0,o=r.length;for(;o>0;){let i=Math.trunc(o/2),s=n+i;e(r[s],t)<=0?(n=++s,o-=i+1):o=i}return n}var Si=class{#t=[];enqueue(t,e){e={priority:0,...e};let n={priority:e.priority,run:t};if(this.size&&this.#t[this.size-1].priority>=e.priority){this.#t.push(n);return}let o=vf(this.#t,n,(i,s)=>s.priority-i.priority);this.#t.splice(o,0,n)}dequeue(){return this.#t.shift()?.run}filter(t){return this.#t.filter(e=>e.priority===t.priority).map(e=>e.run)}get size(){return this.#t.length}};var de=class extends xf.default{#t;#r;#a=0;#c;#g;#S=0;#o;#y;#n;#i;#e=0;#h;#l;#d;timeout;constructor(t){if(super(),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Si,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);this.#t=t.carryoverConcurrencyCount,this.#r=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#c=t.intervalCap,this.#g=t.interval,this.#n=new t.queueClass,this.#i=t.queueClass,this.concurrency=t.concurrency,this.timeout=t.timeout,this.#d=t.throwOnTimeout===!0,this.#l=t.autoStart===!1}get#u(){return this.#r||this.#a<this.#c}get#b(){return this.#e<this.#h}#f(){this.#e--,this.#m(),this.emit("next")}#x(){this.#A(),this.#w(),this.#y=void 0}get#E(){let t=Date.now();if(this.#o===void 0){let e=this.#S-t;if(e<0)this.#a=this.#t?this.#e:0;else return this.#y===void 0&&(this.#y=setTimeout(()=>{this.#x()},e)),!0}return!1}#m(){if(this.#n.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#e===0&&this.emit("idle"),!1;if(!this.#l){let t=!this.#E;if(this.#u&&this.#b){let e=this.#n.dequeue();return e?(this.emit("active"),e(),t&&this.#w(),!0):!1}}return!1}#w(){this.#r||this.#o!==void 0||(this.#o=setInterval(()=>{this.#A()},this.#g),this.#S=Date.now()+this.#g)}#A(){this.#a===0&&this.#e===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#a=this.#t?this.#e:0,this.#p()}#p(){for(;this.#m(););}get concurrency(){return this.#h}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#h=t,this.#p()}async#C(t){return new Promise((e,n)=>{t.addEventListener("abort",()=>{n(t.reason)},{once:!0})})}async add(t,e={}){return e={timeout:this.timeout,throwOnTimeout:this.#d,...e},new Promise((n,o)=>{this.#n.enqueue(async()=>{this.#e++,this.#a++;try{e.signal?.throwIfAborted();let i=t({signal:e.signal});e.timeout&&(i=vi(Promise.resolve(i),{milliseconds:e.timeout})),e.signal&&(i=Promise.race([i,this.#C(e.signal)]));let s=await i;n(s),this.emit("completed",s)}catch(i){if(i instanceof Ei&&!e.throwOnTimeout){n();return}o(i),this.emit("error",i)}finally{this.#f()}},e),this.emit("add"),this.#m()})}async addAll(t,e){return Promise.all(t.map(async n=>this.add(n,e)))}start(){return this.#l?(this.#l=!1,this.#p(),this):this}pause(){this.#l=!0}clear(){this.#n=new this.#i}async onEmpty(){this.#n.size!==0&&await this.#I("empty")}async onSizeLessThan(t){this.#n.size<t||await this.#I("next",()=>this.#n.size<t)}async onIdle(){this.#e===0&&this.#n.size===0||await this.#I("idle")}async#I(t,e){return new Promise(n=>{let o=()=>{e&&!e()||(this.off(t,o),n())};this.on(t,o)})}get size(){return this.#n.size}sizeBy(t){return this.#n.filter(t).length}get pending(){return this.#e}get isPaused(){return this.#l}};function Pa(r){let t=[pe.A];return r==null?t:Array.isArray(r)?r.length===0?t:r:[r]}var Sf=60;function Da(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(t=>({name:t.name,type:pe[t.type]})),Answer:(r.Answer??r.answers??[]).map(t=>({name:t.name,type:pe[t.type],TTL:t.TTL??t.ttl??Sf,data:t.data instanceof Uint8Array?q(t.data):t.data}))}}var yv=4;function Af(r,t={}){let e=new de({concurrency:t.queryConcurrency??yv});return async(n,o={})=>{let i=new URLSearchParams;i.set("name",n),Pa(o.types).forEach(a=>{i.append("type",pe[a])}),o.onProgress?.(new H("dns:query",{detail:n}));let s=await e.add(async()=>{let a=await fetch(`${r}?${i}`,{headers:{accept:"application/dns-json"},signal:o?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=Da(await a.json());return o.onProgress?.(new H("dns:response",{detail:c})),c},{signal:o.signal});if(s==null)throw new Error("No DNS response received");return s}}function Zm(){return[Af("https://cloudflare-dns.com/dns-query"),Af("https://dns.google/resolve")]}var Qm=Ot(If(),1);var kf=class{lru;constructor(t){this.lru=(0,Qm.default)(t)}get(t,e){let n=!0,o=[];for(let i of e){let s=this.getAnswers(t,i);if(s.length===0){n=!1;break}o.push(...s)}if(n)return Da({answers:o})}getAnswers(t,e){let n=`${t.toLowerCase()}-${e}`,o=this.lru.get(n);if(o!=null){let i=o.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:pe[a.type]}));return i.length===0&&this.lru.remove(n),i}return[]}add(t,e){let n=`${t.toLowerCase()}-${e.type}`,o=this.lru.get(n)??[];o.push({expires:Date.now()+(e.TTL??Sf)*1e3,value:e}),this.lru.set(n,o)}remove(t,e){let n=`${t.toLowerCase()}-${e}`;this.lru.remove(n)}clear(){this.lru.clear()}};function tg(r){return new kf(r)}var wv=1e3,Oa=class{resolvers;cache;constructor(t){this.resolvers={},this.cache=tg(t.cacheSize??wv),Object.entries(t.resolvers??{}).forEach(([e,n])=>{Array.isArray(n)||(n=[n]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=n}),this.resolvers["."]==null&&(this.resolvers["."]=Zm())}async query(t,e={}){let n=Pa(e.types),o=e.cached!==!1?this.cache.get(t,n):void 0;if(o!=null)return e.onProgress?.(new H("dns:cache",{detail:o})),o;let i=`${t.split(".").pop()}.`,s=(this.resolvers[i]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(e.signal?.aborted===!0)break;try{let l=await c(t,{...e,types:n});for(let u of l.Answer)this.cache.add(t,u);return l}catch(l){a.push(l),e.onProgress?.(new H("dns:error",{detail:l}))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${t} ${n} failed`)}};var pe;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(pe||(pe={}));function Ai(r={}){return new Oa(r)}var Ua=class extends Error{static name="QueueFullError";constructor(t="The queue was full"){super(t),this.name="QueueFullError"}};var Fa=class{deferred;signal;constructor(t){this.signal=t,this.deferred=ft(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ne)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function bv(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Ma=class{id;fn;options;recipients;status;timeline;controller;constructor(t,e){this.id=bv(),this.status="queued",this.fn=t,this.options=e,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,mt(1/0,this.controller.signal),this.onAbort=this.onAbort.bind(this)}abort(t){this.controller.abort(t)}onAbort(){this.recipients.reduce((e,n)=>e&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Ne),this.cleanup())}async join(t={}){let e=new Fa(t.signal);return this.recipients.push(e),t.signal?.addEventListener("abort",this.onAbort),e.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let t=await Rd(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(e=>{e.deferred.resolve(t)}),this.status="complete"}catch(t){this.recipients.forEach(e=>{e.deferred.reject(t)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(t=>{t.cleanup(),t.signal?.removeEventListener("abort",this.onAbort)})}};var kr=class extends qn{concurrency;maxSize;queue;pending;sort;constructor(t={}){super(),this.concurrency=t.concurrency??Number.POSITIVE_INFINITY,this.maxSize=t.maxSize??Number.POSITIVE_INFINITY,this.pending=0,t.metricName!=null&&t.metrics?.registerMetricGroup(t.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=t.sort,this.queue=[]}tryToStartAnother(){if(this.size===0)return queueMicrotask(()=>{this.safeDispatchEvent("empty")}),this.running===0&&queueMicrotask(()=>{this.safeDispatchEvent("idle")}),!1;if(this.pending<this.concurrency){let t;for(let e of this.queue)if(e.status==="queued"){t=e;break}return t==null?!1:(this.safeDispatchEvent("active"),this.pending++,t.run().finally(()=>{for(let e=0;e<this.queue.length;e++)if(this.queue[e]===t){this.queue.splice(e,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(t){this.queue.push(t),this.sort!=null&&this.queue.sort(this.sort)}async add(t,e){if(e?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Ua;let n=new Ma(t,e);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(e).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{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:o}),this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(t=>{t.abort(new Ne)}),this.clear()}async onEmpty(t){this.size!==0&&await fs(this,"empty",t?.signal)}async onSizeLessThan(t,e){this.size<t||await fs(this,"next",e?.signal,{filter:()=>this.size<t})}async onIdle(t){this.pending===0&&this.size===0||await fs(this,"idle",t?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(t){t?.signal?.throwIfAborted();let e=We({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),e.end(c)},o=c=>{c.detail!=null&&e.push(c.detail)},i=c=>{n(c.detail)},s=()=>{n()},a=()=>{n(new Ne("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("error",i),this.addEventListener("idle",s),t?.signal?.addEventListener("abort",a);try{yield*e}finally{this.removeEventListener("completed",o),this.removeEventListener("error",i),this.removeEventListener("idle",s),t?.signal?.removeEventListener("abort",a),n()}}};var xv=["string","number","bigint","symbol"],Ev=["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 eg(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let t=typeof r;if(xv.includes(t))return t;if(t==="function")return"Function";if(Array.isArray(r))return"Array";if(vv(r))return"Buffer";let e=Sv(r);return e||"Object"}function vv(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function Sv(r){let t=Object.prototype.toString.call(r).slice(8,-1);if(Ev.includes(t))return t}var w=class{constructor(t,e,n){this.major=t,this.majorEncoded=t<<5,this.name=e,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(t){return this.major<t.major?-1:this.major>t.major?1:0}};w.uint=new w(0,"uint",!0);w.negint=new w(1,"negint",!0);w.bytes=new w(2,"bytes",!0);w.string=new w(3,"string",!0);w.array=new w(4,"array",!1);w.map=new w(5,"map",!1);w.tag=new w(6,"tag",!1);w.float=new w(7,"float",!0);w.false=new w(7,"false",!0);w.true=new w(7,"true",!0);w.null=new w(7,"null",!0);w.undefined=new w(7,"undefined",!0);w.break=new w(7,"break",!0);var B=class{constructor(t,e,n){this.type=t,this.value=e,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var go=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Av=new TextDecoder,Iv=new TextEncoder;function Va(r){return go&&globalThis.Buffer.isBuffer(r)}function Ii(r){return r instanceof Uint8Array?Va(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var ig=go?(r,t,e)=>e-t>64?globalThis.Buffer.from(r.subarray(t,e)).toString("utf8"):ng(r,t,e):(r,t,e)=>e-t>64?Av.decode(r.subarray(t,e)):ng(r,t,e),Ha=go?r=>r.length>64?globalThis.Buffer.from(r):rg(r):r=>r.length>64?Iv.encode(r):rg(r),rr=r=>Uint8Array.from(r),yo=go?(r,t,e)=>Va(r)?new Uint8Array(r.subarray(t,e)):r.slice(t,e):(r,t,e)=>r.slice(t,e),sg=go?(r,t)=>(r=r.map(e=>e instanceof Uint8Array?e:globalThis.Buffer.from(e)),Ii(globalThis.Buffer.concat(r,t))):(r,t)=>{let e=new Uint8Array(t),n=0;for(let o of r)n+o.length>e.length&&(o=o.subarray(0,e.length-n)),e.set(o,n),n+=o.length;return e},ag=go?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function cg(r,t){if(Va(r)&&Va(t))return r.compare(t);for(let e=0;e<r.length;e++)if(r[e]!==t[e])return r[e]<t[e]?-1:1;return 0}function rg(r){let t=[],e=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=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),t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128)}return t}function ng(r,t,e){let n=[];for(;t<e;){let o=r[t],i=null,s=o>239?4:o>223?3:o>191?2:1;if(t+s<=e){let a,c,l,u;switch(s){case 1:o<128&&(i=o);break;case 2:a=r[t+1],(a&192)===128&&(u=(o&31)<<6|a&63,u>127&&(i=u));break;case 3:a=r[t+1],c=r[t+2],(a&192)===128&&(c&192)===128&&(u=(o&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(i=u));break;case 4:a=r[t+1],c=r[t+2],l=r[t+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(o&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(i=u))}}i===null?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|i&1023),n.push(i),t+=s}return _f(n)}var og=4096;function _f(r){let t=r.length;if(t<=og)return String.fromCharCode.apply(String,r);let e="",n=0;for(;n<t;)e+=String.fromCharCode.apply(String,r.slice(n,n+=og));return e}var kv=256,ki=class{constructor(t=kv){this.chunkSize=t,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(t){let e=this.chunks[this.chunks.length-1];if(this.cursor+t.length<=this.maxCursor+1){let o=e.length-(this.maxCursor-this.cursor)-1;e.set(t,o)}else{if(e){let o=e.length-(this.maxCursor-this.cursor)-1;o<e.length&&(this.chunks[this.chunks.length-1]=e.subarray(0,o),this.maxCursor=this.cursor-1)}t.length<64&&t.length<this.chunkSize?(e=ag(this.chunkSize),this.chunks.push(e),this.maxCursor+=e.length,this._initReuseChunk===null&&(this._initReuseChunk=e),e.set(t,0)):(this.chunks.push(t),this.maxCursor+=t.length)}this.cursor+=t.length}toBytes(t=!1){let e;if(this.chunks.length===1){let n=this.chunks[0];t&&this.cursor>n.length/2?(e=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):e=yo(n,0,this.cursor)}else e=sg(this.chunks,this.cursor);return t&&this.reset(),e}};var $="CBOR decode error:",_r="CBOR encode error:",_i=[];_i[23]=1;_i[24]=2;_i[25]=3;_i[26]=5;_i[27]=9;function Br(r,t,e){if(r.length-t<e)throw new Error(`${$} not enough data for type`)}var Pt=[24,256,65536,4294967296,BigInt("18446744073709551616")];function we(r,t,e){Br(r,t,1);let n=r[t];if(e.strict===!0&&n<Pt[0])throw new Error(`${$} integer encoded in more bytes than necessary (strict decode)`);return n}function be(r,t,e){Br(r,t,2);let n=r[t]<<8|r[t+1];if(e.strict===!0&&n<Pt[1])throw new Error(`${$} integer encoded in more bytes than necessary (strict decode)`);return n}function xe(r,t,e){Br(r,t,4);let n=r[t]*16777216+(r[t+1]<<16)+(r[t+2]<<8)+r[t+3];if(e.strict===!0&&n<Pt[2])throw new Error(`${$} integer encoded in more bytes than necessary (strict decode)`);return n}function Ee(r,t,e){Br(r,t,8);let n=r[t]*16777216+(r[t+1]<<16)+(r[t+2]<<8)+r[t+3],o=r[t+4]*16777216+(r[t+5]<<16)+(r[t+6]<<8)+r[t+7],i=(BigInt(n)<<BigInt(32))+BigInt(o);if(e.strict===!0&&i<Pt[3])throw new Error(`${$} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(e.allowBigInt===!0)return i;throw new Error(`${$} integers outside of the safe integer range are not supported`)}function lg(r,t,e,n){return new B(w.uint,we(r,t+1,n),2)}function ug(r,t,e,n){return new B(w.uint,be(r,t+1,n),3)}function fg(r,t,e,n){return new B(w.uint,xe(r,t+1,n),5)}function hg(r,t,e,n){return new B(w.uint,Ee(r,t+1,n),9)}function _e(r,t){return Mt(r,0,t.value)}function Mt(r,t,e){if(e<Pt[0]){let n=Number(e);r.push([t|n])}else if(e<Pt[1]){let n=Number(e);r.push([t|24,n])}else if(e<Pt[2]){let n=Number(e);r.push([t|25,n>>>8,n&255])}else if(e<Pt[3]){let n=Number(e);r.push([t|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(e);if(n<Pt[4]){let o=[t|27,0,0,0,0,0,0,0],i=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,r.push(o)}else throw new Error(`${$} encountered BigInt larger than allowable range`)}}_e.encodedSize=function(t){return Mt.encodedSize(t.value)};Mt.encodedSize=function(t){return t<Pt[0]?1:t<Pt[1]?2:t<Pt[2]?3:t<Pt[3]?5:9};_e.compareTokens=function(t,e){return t.value<e.value?-1:t.value>e.value?1:0};function dg(r,t,e,n){return new B(w.negint,-1-we(r,t+1,n),2)}function pg(r,t,e,n){return new B(w.negint,-1-be(r,t+1,n),3)}function mg(r,t,e,n){return new B(w.negint,-1-xe(r,t+1,n),5)}var Bf=BigInt(-1),gg=BigInt(1);function yg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new B(w.negint,i,9)}if(n.allowBigInt!==!0)throw new Error(`${$} integers outside of the safe integer range are not supported`);return new B(w.negint,Bf-BigInt(o),9)}function $a(r,t){let e=t.value,n=typeof e=="bigint"?e*Bf-gg:e*-1-1;Mt(r,t.type.majorEncoded,n)}$a.encodedSize=function(t){let e=t.value,n=typeof e=="bigint"?e*Bf-gg:e*-1-1;return n<Pt[0]?1:n<Pt[1]?2:n<Pt[2]?3:n<Pt[3]?5:9};$a.compareTokens=function(t,e){return t.value<e.value?1:t.value>e.value?-1:0};function Bi(r,t,e,n){Br(r,t,e+n);let o=yo(r,t+e,t+e+n);return new B(w.bytes,o,e+n)}function wg(r,t,e,n){return Bi(r,t,1,e)}function bg(r,t,e,n){return Bi(r,t,2,we(r,t+1,n))}function xg(r,t,e,n){return Bi(r,t,3,be(r,t+1,n))}function Eg(r,t,e,n){return Bi(r,t,5,xe(r,t+1,n))}function vg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o=="bigint")throw new Error(`${$} 64-bit integer bytes lengths not supported`);return Bi(r,t,9,o)}function za(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===w.string?Ha(r.value):r.value),r.encodedBytes}function wo(r,t){let e=za(t);Mt(r,t.type.majorEncoded,e.length),r.push(e)}wo.encodedSize=function(t){let e=za(t);return Mt.encodedSize(e.length)+e.length};wo.compareTokens=function(t,e){return Bv(za(t),za(e))};function Bv(r,t){return r.length<t.length?-1:r.length>t.length?1:cg(r,t)}function Ti(r,t,e,n,o){let i=e+n;Br(r,t,i);let s=new B(w.string,ig(r,t+e,t+i),i);return o.retainStringBytes===!0&&(s.byteValue=yo(r,t+e,t+i)),s}function Sg(r,t,e,n){return Ti(r,t,1,e,n)}function Ag(r,t,e,n){return Ti(r,t,2,we(r,t+1,n),n)}function Ig(r,t,e,n){return Ti(r,t,3,be(r,t+1,n),n)}function kg(r,t,e,n){return Ti(r,t,5,xe(r,t+1,n),n)}function _g(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o=="bigint")throw new Error(`${$} 64-bit integer string lengths not supported`);return Ti(r,t,9,o,n)}var Bg=wo;function bo(r,t,e,n){return new B(w.array,n,e)}function Tg(r,t,e,n){return bo(r,t,1,e)}function Cg(r,t,e,n){return bo(r,t,2,we(r,t+1,n))}function Rg(r,t,e,n){return bo(r,t,3,be(r,t+1,n))}function Ng(r,t,e,n){return bo(r,t,5,xe(r,t+1,n))}function Lg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o=="bigint")throw new Error(`${$} 64-bit integer array lengths not supported`);return bo(r,t,9,o)}function Pg(r,t,e,n){if(n.allowIndefinite===!1)throw new Error(`${$} indefinite length items not allowed`);return bo(r,t,1,1/0)}function qa(r,t){Mt(r,w.array.majorEncoded,t.value)}qa.compareTokens=_e.compareTokens;qa.encodedSize=function(t){return Mt.encodedSize(t.value)};function xo(r,t,e,n){return new B(w.map,n,e)}function Dg(r,t,e,n){return xo(r,t,1,e)}function Og(r,t,e,n){return xo(r,t,2,we(r,t+1,n))}function Ug(r,t,e,n){return xo(r,t,3,be(r,t+1,n))}function Fg(r,t,e,n){return xo(r,t,5,xe(r,t+1,n))}function Mg(r,t,e,n){let o=Ee(r,t+1,n);if(typeof o=="bigint")throw new Error(`${$} 64-bit integer map lengths not supported`);return xo(r,t,9,o)}function Vg(r,t,e,n){if(n.allowIndefinite===!1)throw new Error(`${$} indefinite length items not allowed`);return xo(r,t,1,1/0)}function Ka(r,t){Mt(r,w.map.majorEncoded,t.value)}Ka.compareTokens=_e.compareTokens;Ka.encodedSize=function(t){return Mt.encodedSize(t.value)};function Hg(r,t,e,n){return new B(w.tag,e,1)}function $g(r,t,e,n){return new B(w.tag,we(r,t+1,n),2)}function zg(r,t,e,n){return new B(w.tag,be(r,t+1,n),3)}function qg(r,t,e,n){return new B(w.tag,xe(r,t+1,n),5)}function Kg(r,t,e,n){return new B(w.tag,Ee(r,t+1,n),9)}function Ga(r,t){Mt(r,w.tag.majorEncoded,t.value)}Ga.compareTokens=_e.compareTokens;Ga.encodedSize=function(t){return Mt.encodedSize(t.value)};var Pv=20,Dv=21,Ov=22,Uv=23;function Gg(r,t,e,n){if(n.allowUndefined===!1)throw new Error(`${$} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new B(w.null,null,1):new B(w.undefined,void 0,1)}function Wg(r,t,e,n){if(n.allowIndefinite===!1)throw new Error(`${$} indefinite length items not allowed`);return new B(w.break,void 0,1)}function Tf(r,t,e){if(e){if(e.allowNaN===!1&&Number.isNaN(r))throw new Error(`${$} NaN values are not supported`);if(e.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${$} Infinity values are not supported`)}return new B(w.float,r,t)}function jg(r,t,e,n){return Tf(Cf(r,t+1),3,n)}function Yg(r,t,e,n){return Tf(Rf(r,t+1),5,n)}function Xg(r,t,e,n){return Tf(t0(r,t+1),9,n)}function Wa(r,t,e){let n=t.value;if(n===!1)r.push([w.float.majorEncoded|Pv]);else if(n===!0)r.push([w.float.majorEncoded|Dv]);else if(n===null)r.push([w.float.majorEncoded|Ov]);else if(n===void 0)r.push([w.float.majorEncoded|Uv]);else{let o,i=!1;(!e||e.float64!==!0)&&(Jg(n),o=Cf(Me,1),n===o||Number.isNaN(n)?(Me[0]=249,r.push(Me.slice(0,3)),i=!0):(Qg(n),o=Rf(Me,1),n===o&&(Me[0]=250,r.push(Me.slice(0,5)),i=!0))),i||(Fv(n),o=t0(Me,1),Me[0]=251,r.push(Me.slice(0,9)))}}Wa.encodedSize=function(t,e){let n=t.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!e||e.float64!==!0){Jg(n);let o=Cf(Me,1);if(n===o||Number.isNaN(n))return 3;if(Qg(n),o=Rf(Me,1),n===o)return 5}return 9};var Zg=new ArrayBuffer(9),Be=new DataView(Zg,1),Me=new Uint8Array(Zg,0);function Jg(r){if(r===1/0)Be.setUint16(0,31744,!1);else if(r===-1/0)Be.setUint16(0,64512,!1);else if(Number.isNaN(r))Be.setUint16(0,32256,!1);else{Be.setFloat32(0,r);let t=Be.getUint32(0),e=(t&2139095040)>>23,n=t&8388607;if(e===255)Be.setUint16(0,31744,!1);else if(e===0)Be.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let o=e-127;o<-24?Be.setUint16(0,0):o<-14?Be.setUint16(0,(t&2147483648)>>16|1<<24+o,!1):Be.setUint16(0,(t&2147483648)>>16|o+15<<10|n>>13,!1)}}}function Cf(r,t){if(r.length-t<2)throw new Error(`${$} not enough data for float16`);let e=(r[t]<<8)+r[t+1];if(e===31744)return 1/0;if(e===64512)return-1/0;if(e===32256)return NaN;let n=e>>10&31,o=e&1023,i;return n===0?i=o*2**-24:n!==31?i=(o+1024)*2**(n-25):i=o===0?1/0:NaN,e&32768?-i:i}function Qg(r){Be.setFloat32(0,r,!1)}function Rf(r,t){if(r.length-t<4)throw new Error(`${$} not enough data for float32`);let e=(r.byteOffset||0)+t;return new DataView(r.buffer,e,4).getFloat32(0,!1)}function Fv(r){Be.setFloat64(0,r,!1)}function t0(r,t){if(r.length-t<8)throw new Error(`${$} not enough data for float64`);let e=(r.byteOffset||0)+t;return new DataView(r.buffer,e,8).getFloat64(0,!1)}Wa.compareTokens=_e.compareTokens;function rt(r,t,e){throw new Error(`${$} encountered invalid minor (${e}) for major ${r[t]>>>5}`)}function ja(r){return()=>{throw new Error(`${$} ${r}`)}}var O=[];for(let r=0;r<=23;r++)O[r]=rt;O[24]=lg;O[25]=ug;O[26]=fg;O[27]=hg;O[28]=rt;O[29]=rt;O[30]=rt;O[31]=rt;for(let r=32;r<=55;r++)O[r]=rt;O[56]=dg;O[57]=pg;O[58]=mg;O[59]=yg;O[60]=rt;O[61]=rt;O[62]=rt;O[63]=rt;for(let r=64;r<=87;r++)O[r]=wg;O[88]=bg;O[89]=xg;O[90]=Eg;O[91]=vg;O[92]=rt;O[93]=rt;O[94]=rt;O[95]=ja("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)O[r]=Sg;O[120]=Ag;O[121]=Ig;O[122]=kg;O[123]=_g;O[124]=rt;O[125]=rt;O[126]=rt;O[127]=ja("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)O[r]=Tg;O[152]=Cg;O[153]=Rg;O[154]=Ng;O[155]=Lg;O[156]=rt;O[157]=rt;O[158]=rt;O[159]=Pg;for(let r=160;r<=183;r++)O[r]=Dg;O[184]=Og;O[185]=Ug;O[186]=Fg;O[187]=Mg;O[188]=rt;O[189]=rt;O[190]=rt;O[191]=Vg;for(let r=192;r<=215;r++)O[r]=Hg;O[216]=$g;O[217]=zg;O[218]=qg;O[219]=Kg;O[220]=rt;O[221]=rt;O[222]=rt;O[223]=rt;for(let r=224;r<=243;r++)O[r]=ja("simple values are not supported");O[244]=rt;O[245]=rt;O[246]=rt;O[247]=Gg;O[248]=ja("simple values are not supported");O[249]=jg;O[250]=Yg;O[251]=Xg;O[252]=rt;O[253]=rt;O[254]=rt;O[255]=Wg;var Ve=[];for(let r=0;r<24;r++)Ve[r]=new B(w.uint,r,1);for(let r=-1;r>=-24;r--)Ve[31-r]=new B(w.negint,r,1);Ve[64]=new B(w.bytes,new Uint8Array(0),1);Ve[96]=new B(w.string,"",1);Ve[128]=new B(w.array,0,1);Ve[160]=new B(w.map,0,1);Ve[244]=new B(w.false,!1,1);Ve[245]=new B(w.true,!0,1);Ve[246]=new B(w.null,null,1);function Nf(r){switch(r.type){case w.false:return rr([244]);case w.true:return rr([245]);case w.null:return rr([246]);case w.bytes:return r.value.length?void 0:rr([64]);case w.string:return r.value===""?rr([96]):void 0;case w.array:return r.value===0?rr([128]):void 0;case w.map:return r.value===0?rr([160]):void 0;case w.uint:return r.value<24?rr([Number(r.value)]):void 0;case w.negint:if(r.value>=-24)return rr([31-Number(r.value)])}}var Vv={float64:!1,mapSorter:$v,quickEncodeToken:Nf};function Pf(){let r=[];return r[w.uint.major]=_e,r[w.negint.major]=$a,r[w.bytes.major]=wo,r[w.string.major]=Bg,r[w.array.major]=qa,r[w.map.major]=Ka,r[w.tag.major]=Ga,r[w.float.major]=Wa,r}var e0=Pf(),Lf=new ki,Ya=class r{constructor(t,e){this.obj=t,this.parent=e}includes(t){let e=this;do if(e.obj===t)return!0;while(e=e.parent);return!1}static createCheck(t,e){if(t&&t.includes(e))throw new Error(`${_r} object contains circular references`);return new r(e,t)}},nn={null:new B(w.null,null),undefined:new B(w.undefined,void 0),true:new B(w.true,!0),false:new B(w.false,!1),emptyArray:new B(w.array,0),emptyMap:new B(w.map,0)},on={number(r,t,e,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new B(w.float,r):r>=0?new B(w.uint,r):new B(w.negint,r)},bigint(r,t,e,n){return r>=BigInt(0)?new B(w.uint,r):new B(w.negint,r)},Uint8Array(r,t,e,n){return new B(w.bytes,r)},string(r,t,e,n){return new B(w.string,r)},boolean(r,t,e,n){return r?nn.true:nn.false},null(r,t,e,n){return nn.null},undefined(r,t,e,n){return nn.undefined},ArrayBuffer(r,t,e,n){return new B(w.bytes,new Uint8Array(r))},DataView(r,t,e,n){return new B(w.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,t,e,n){if(!r.length)return e.addBreakTokens===!0?[nn.emptyArray,new B(w.break)]:nn.emptyArray;n=Ya.createCheck(n,r);let o=[],i=0;for(let s of r)o[i++]=Ci(s,e,n);return e.addBreakTokens?[new B(w.array,r.length),o,new B(w.break)]:[new B(w.array,r.length),o]},Object(r,t,e,n){let o=t!=="Object",i=o?r.keys():Object.keys(r),s=o?r.size:i.length;if(!s)return e.addBreakTokens===!0?[nn.emptyMap,new B(w.break)]:nn.emptyMap;n=Ya.createCheck(n,r);let a=[],c=0;for(let l of i)a[c++]=[Ci(l,e,n),Ci(o?r.get(l):r[l],e,n)];return Hv(a,e),e.addBreakTokens?[new B(w.map,s),a,new B(w.break)]:[new B(w.map,s),a]}};on.Map=on.Object;on.Buffer=on.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))on[`${r}Array`]=on.DataView;function Ci(r,t={},e){let n=eg(r),o=t&&t.typeEncoders&&t.typeEncoders[n]||on[n];if(typeof o=="function"){let s=o(r,n,t,e);if(s!=null)return s}let i=on[n];if(!i)throw new Error(`${_r} unsupported type: ${n}`);return i(r,n,t,e)}function Hv(r,t){t.mapSorter&&r.sort(t.mapSorter)}function $v(r,t){let e=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(t[0])?t[0][0]:t[0];if(e.type!==n.type)return e.type.compare(n.type);let o=e.type.major,i=e0[o].compareTokens(e,n);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function r0(r,t,e,n){if(Array.isArray(t))for(let o of t)r0(r,o,e,n);else e[t.type.major](r,t,n)}function Df(r,t,e){let n=Ci(r,e);if(!Array.isArray(n)&&e.quickEncodeToken){let o=e.quickEncodeToken(n);if(o)return o;let i=t[n.type.major];if(i.encodedSize){let s=i.encodedSize(n,e),a=new ki(s);if(i(a,n,e),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return Ii(a.chunks[0])}}return Lf.reset(),r0(Lf,n,t,e),Lf.toBytes(!0)}function nr(r,t){return t=Object.assign({},Vv,t),Df(r,e0,t)}var zv={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Xa=class{constructor(t,e={}){this._pos=0,this.data=t,this.options=e}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let t=this.data[this._pos],e=Ve[t];if(e===void 0){let n=O[t];if(!n)throw new Error(`${$} no decoder for major type ${t>>>5} (byte 0x${t.toString(16).padStart(2,"0")})`);let o=t&31;e=n(this.data,this._pos,o,this.options)}return this._pos+=e.encodedLength,e}},Ri=Symbol.for("DONE"),Za=Symbol.for("BREAK");function qv(r,t,e){let n=[];for(let o=0;o<r.value;o++){let i=Eo(t,e);if(i===Za){if(r.value===1/0)break;throw new Error(`${$} got unexpected break to lengthed array`)}if(i===Ri)throw new Error(`${$} found array but not enough entries (got ${o}, expected ${r.value})`);n[o]=i}return n}function Kv(r,t,e){let n=e.useMaps===!0,o=n?void 0:{},i=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=Eo(t,e);if(a===Za){if(r.value===1/0)break;throw new Error(`${$} got unexpected break to lengthed map`)}if(a===Ri)throw new Error(`${$} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${$} non-string keys not supported (got ${typeof a})`);if(e.rejectDuplicateMapKeys===!0&&(n&&i.has(a)||!n&&a in o))throw new Error(`${$} found repeat map key "${a}"`);let c=Eo(t,e);if(c===Ri)throw new Error(`${$} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?i.set(a,c):o[a]=c}return n?i:o}function Eo(r,t){if(r.done())return Ri;let e=r.next();if(e.type===w.break)return Za;if(e.type.terminal)return e.value;if(e.type===w.array)return qv(e,r,t);if(e.type===w.map)return Kv(e,r,t);if(e.type===w.tag){if(t.tags&&typeof t.tags[e.value]=="function"){let n=Eo(r,t);return t.tags[e.value](n)}throw new Error(`${$} tag not supported (${e.value})`)}throw new Error("unsupported")}function Of(r,t){if(!(r instanceof Uint8Array))throw new Error(`${$} data to decode must be a Uint8Array`);t=Object.assign({},zv,t);let e=t.tokenizer||new Xa(r,t),n=Eo(e,t);if(n===Ri)throw new Error(`${$} did not find any content to decode`);if(n===Za)throw new Error(`${$} got unexpected break`);return[n,r.subarray(e.pos())]}function Vt(r,t){let[e,n]=Of(r,t);if(n.length>0)throw new Error(`${$} too many terminals, data makes no sense`);return e}var Tr="/",n0=new TextEncoder().encode(Tr),Qa=n0[0],At=class r{_buf;constructor(t,e){if(typeof t=="string")this._buf=D(t);else if(t instanceof Uint8Array)this._buf=t;else throw new Error("Invalid key, should be String of Uint8Array");if(e==null&&(e=!0),e&&this.clean(),this._buf.byteLength===0||this._buf[0]!==Qa)throw new Error("Invalid key")}toString(t="utf8"){return q(this._buf,t)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(t){return new r(t.join(Tr))}static random(){return new r(Math.random().toString().substring(2))}static asKey(t){return t instanceof Uint8Array||typeof t=="string"?new r(t):typeof t.uint8Array=="function"?new r(t.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=n0),this._buf[0]!==Qa){let t=new Uint8Array(this._buf.byteLength+1);t.fill(Qa,0,1),t.set(this._buf,1),this._buf=t}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Qa;)this._buf=this._buf.subarray(0,-1)}less(t){let e=this.list(),n=t.list();for(let o=0;o<e.length;o++){if(n.length<o+1)return!1;let i=e[o],s=n[o];if(i<s)return!0;if(i>s)return!1}return e.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let t=this.namespaces();return t[t.length-1]}list(){return this.toString().split(Tr).slice(1)}type(){return Gv(this.baseNamespace())}name(){return Wv(this.baseNamespace())}instance(t){return new r(this.toString()+":"+t)}path(){let t=this.parent().toString();return t.endsWith(Tr)||(t+=Tr),t+=this.type(),new r(t)}parent(){let t=this.list();return t.length===1?new r(Tr):new r(t.slice(0,-1).join(Tr))}child(t){return this.toString()===Tr?t:t.toString()===Tr?this:new r(this.toString()+t.toString(),!1)}isAncestorOf(t){return t.toString()===this.toString()?!1:t.toString().startsWith(this.toString())}isDecendantOf(t){return t.toString()===this.toString()?!1:this.toString().startsWith(t.toString())}isTopLevel(){return this.list().length===1}concat(...t){return r.withNamespaces([...this.namespaces(),...jv(t.map(e=>e.namespaces()))])}};function Gv(r){let t=r.split(":");return t.length<2?"":t.slice(0,-1).join(":")}function Wv(r){let t=r.split(":");return t[t.length-1]}function jv(r){return[].concat(...r)}function tc({enumerable:r=!0,configurable:t=!1}={}){return{enumerable:r,configurable:t,writable:!1}}function*Yv(r,t){if(t!=null&&typeof t=="object")if(Array.isArray(t))for(let[e,n]of t.entries()){let o=[...r,e],i=L.asCID(n);i!=null?yield[o.join("/"),i]:typeof n=="object"&&(yield*Uf(n,o))}else{let e=L.asCID(t);e!=null?yield[r.join("/"),e]:yield*Uf(t,r)}}function*Uf(r,t){if(r==null||r instanceof Uint8Array)return;let e=L.asCID(r);e!=null&&(yield[t.join("/"),e]);for(let[n,o]of Object.entries(r)){let i=[...t,n];yield*Yv(i,o)}}function*Xv(r,t){if(Array.isArray(t))for(let[e,n]of t.entries()){let o=[...r,e];yield o.join("/"),typeof n=="object"&&L.asCID(n)==null&&(yield*Ff(n,o))}else yield*Ff(t,r)}function*Ff(r,t){if(!(r==null||typeof r!="object"))for(let[e,n]of Object.entries(r)){let o=[...t,e];yield o.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&L.asCID(n)==null&&(yield*Xv(o,n))}}function Zv(r,t){let e=r;for(let[n,o]of t.entries()){if(e=e[o],e==null)throw new Error(`Object has no property at ${t.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let i=L.asCID(e);if(i!=null)return{value:i,remaining:t.slice(n+1).join("/")}}return{value:e}}var Mf=class{cid;bytes;value;asBlock;constructor({cid:t,bytes:e,value:n}){if(t==null||e==null||typeof n>"u")throw new Error("Missing required argument");this.cid=t,this.bytes=e,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:tc(),bytes:tc(),value:tc(),asBlock:tc()})}links(){return Uf(this.value,[])}tree(){return Ff(this.value,[])}get(t="/"){return Zv(this.value,t.split("/").filter(Boolean))}};function ec({bytes:r,cid:t,value:e,codec:n}){let o=e!==void 0?e:n?.decode(r);if(o===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Mf({cid:t,bytes:r,value:o})}var s0="/pin/",o0="/pinned-block/",Vf=Kt,i0=1;function rc(r){return r.version===0&&(r=r.toV1()),new At(`${s0}${r.toString(Vf)}`)}var nc=class{datastore;blockstore;getCodec;constructor(t,e,n){this.datastore=t,this.blockstore=e,this.getCodec=n}async*add(t,e={}){let n=rc(t);if(await this.datastore.has(n))throw new Error("Already pinned");let o=Math.round(e.depth??1/0);if(o<0)throw new Error("Depth must be greater than or equal to 0");let i=new kr({concurrency:i0});for await(let a of this.#t(t,i,{...e,depth:o}))await this.#r(a,c=>c.pinnedBy.find(l=>Z(l,t.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(t.bytes),!0),e),yield a;let s={depth:o,metadata:e.metadata??{}};await this.datastore.put(n,nr(s),e)}async*#t(t,e,n){if(n.depth===-1)return;let o=await this.getCodec(t.code),i=await this.blockstore.get(t,n),s=ec({bytes:i,cid:t,codec:o});yield t;for await(let[,a]of s.links())yield*await e.add(async()=>this.#t(a,e,{...n,depth:n.depth-1}))}async#r(t,e,n){let o=new At(`${o0}${Vf.encode(t.multihash.bytes)}`),i={pinCount:0,pinnedBy:[]};try{i=Vt(await this.datastore.get(o,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(e(i)){if(i.pinCount===0&&await this.datastore.has(o)){await this.datastore.delete(o);return}await this.datastore.put(o,nr(i),n),n.onProgress?.(new H("helia:pin:add",t))}}async*rm(t,e={}){let n=rc(t),o=await this.datastore.get(n,e),i=Vt(o);await this.datastore.delete(n,e);let s=new kr({concurrency:i0});for await(let a of this.#t(t,s,{...e,depth:i.depth}))await this.#r(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>Z(l,t.bytes)),!0),{...e,depth:i.depth}),yield a}async*ls(t={}){for await(let{key:e,value:n}of this.datastore.query({prefix:s0+(t.cid!=null?`${t.cid.toString(Kt)}`:"")},t)){let o=L.parse(e.toString().substring(5),Kt),i=Vt(n);yield{cid:o,...i}}}async isPinned(t,e={}){let n=new At(`${o0}${Vf.encode(t.multihash.bytes)}`);return this.datastore.has(n,e)}async get(t,e){let n=rc(t),o=await this.datastore.get(n,e);return Vt(o)}async setMetadata(t,e,n){let o=rc(t),i=await this.datastore.get(o,n),s=Vt(i);s.metadata=e??{},await this.datastore.put(o,nr(s),n)}};var oc=class extends Error{static name="InsufficientProvidersError";constructor(t="Insufficient providers found"){super(t),this.name="InsufficientProvidersError"}},Cn=class extends Error{static name="NoRoutersAvailableError";constructor(t="No routers available"){super(t),this.name="NoRoutersAvailableError"}},ic=class extends Error{static name="UnknownHashAlgorithmError";constructor(t="Unknown hash algorithm"){super(t),this.name="UnknownHashAlgorithmError"}},sc=class extends Error{static name="UnknownCodecError";constructor(t="Unknown codec"){super(t),this.name="UnknownCodecError"}};var ac=class extends kr{has(t){return this.find(t)!=null}find(t){return this.queue.find(e=>t.equals(e.options.peerId))}};var Jv=5,cc=class{log;routers;providerLookupConcurrency;constructor(t,e){this.log=t.logger.forComponent("helia:routing"),this.routers=e.routers??[],this.providerLookupConcurrency=e.providerLookupConcurrency??Jv}async start(){await Vr(...this.routers)}async stop(){await Hr(...this.routers)}async*findProviders(t,e={}){if(this.routers.length===0)throw new Cn("No content routers available");let n=new ac({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let o of $r(n.toGenerator(),...vo(this.routers,"findProviders").map(i=>i.findProviders(t,e))))if(o!=null){if(o.multiaddrs.length===0){if(n.find(o.id)!=null)continue;n.add(async()=>{try{let i=await this.findPeer(o.id,e);return i.multiaddrs.length===0?null:i}catch(i){return this.log.error("could not load multiaddrs for peer %p",o.id,i),null}},{peerId:o.id,signal:e.signal}).catch(i=>{this.log.error("could not load multiaddrs for peer %p",o.id,i)})}yield o}}async provide(t,e={}){if(this.routers.length===0)throw new Cn("No content routers available");await Promise.all(vo(this.routers,"provide").map(async n=>{await n.provide(t,e)}))}async put(t,e,n){await Promise.all(vo(this.routers,"put").map(async o=>{await o.put(t,e,n)}))}async get(t,e){return Promise.any(vo(this.routers,"get").map(async n=>n.get(t,e)))}async findPeer(t,e){if(this.routers.length===0)throw new Cn("No peer routers available");let n=this,o=$r(...vo(this.routers,"findPeer").map(i=>async function*(){try{yield await i.findPeer(t,e)}catch(s){n.log.error(s)}}()));for await(let i of o)if(i!=null)return i;throw new _t("Could not find peer in routing")}async*getClosestPeers(t,e={}){if(this.routers.length===0)throw new Cn("No peer routers available");for await(let n of $r(...vo(this.routers,"getClosestPeers").map(o=>o.getClosestPeers(t,e))))n!=null&&(yield n)}};function vo(r,t){return r.filter(e=>e[t]!=null)}var sn={},So=r=>{r.addEventListener("message",t=>{So.dispatchEvent("message",r,t)}),r.port!=null&&r.port.addEventListener("message",t=>{So.dispatchEvent("message",r,t)})};So.addEventListener=(r,t)=>{sn[r]==null&&(sn[r]=[]),sn[r].push(t)};So.removeEventListener=(r,t)=>{sn[r]!=null&&(sn[r]=sn[r].filter(e=>e===t))};So.dispatchEvent=function(r,t,e){sn[r]!=null&&sn[r].forEach(n=>n(t,e))};var Hf=So;var $f="lock:worker:request-read",zf="lock:worker:release-read",qf="lock:master:grant-read",Kf="lock:worker:request-write",Gf="lock:worker:release-write",Wf="lock:master:grant-write";var a0=(r=21)=>Math.random().toString().substring(2);var c0=(r,t,e,n,o)=>(i,s)=>{if(s.data.type!==e)return;let a={type:s.data.type,name:s.data.name,identifier:s.data.identifier};r.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{i.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise(c=>{let l=u=>{if(u==null||u.data==null)return;let f={type:u.data.type,name:u.data.name,identifier:u.data.identifier};f.type===n&&f.identifier===a.identifier&&(i.removeEventListener("message",l),c())};i.addEventListener("message",l)})}}}))},l0=(r,t,e,n)=>async()=>{let o=a0();return globalThis.postMessage({type:t,identifier:o,name:r}),new Promise(i=>{let s=a=>{if(a==null||a.data==null)return;let c={type:a.data.type,identifier:a.data.identifier};c.type===e&&c.identifier===o&&(globalThis.removeEventListener("message",s),i(()=>{globalThis.postMessage({type:n,identifier:o,name:r})}))};globalThis.addEventListener("message",s)})},Qv={singleProcess:!1},u0=r=>{if(r=Object.assign({},Qv,r),!!globalThis.document||r.singleProcess){let e=new EventTarget;return Hf.addEventListener("message",c0(e,"requestReadLock",$f,zf,qf)),Hf.addEventListener("message",c0(e,"requestWriteLock",Kf,Gf,Wf)),e}return{isWorker:!0,readLock:e=>l0(e,$f,qf,zf),writeLock:e=>l0(e,Kf,Wf,Gf)}};var Rn={},an;async function jf(r,t){let e,n=new Promise(o=>{e=o});return r.add(async()=>vi((async()=>{await new Promise(o=>{e(()=>{o()})})})(),{milliseconds:t.timeout})),n}var t2=(r,t)=>{if(an.isWorker===!0)return{readLock:an.readLock(r,t),writeLock:an.writeLock(r,t)};let e=new de({concurrency:1}),n;return{async readLock(){if(n!=null)return jf(n,t);n=new de({concurrency:t.concurrency,autoStart:!1});let o=n,i=jf(n,t);return e.add(async()=>{o.start(),await o.onIdle().then(()=>{n===o&&(n=null)})}),i},async writeLock(){return n=null,jf(e,t)}}},e2={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};function Yf(r){let t=Object.assign({},e2,r);return an==null&&(an=u0(t),an.isWorker!==!0&&(an.addEventListener("requestReadLock",e=>{Rn[e.data.name]!=null&&Rn[e.data.name].readLock().then(async n=>e.data.handler().finally(()=>{n()}))}),an.addEventListener("requestWriteLock",async e=>{Rn[e.data.name]!=null&&Rn[e.data.name].writeLock().then(async n=>e.data.handler().finally(()=>{n()}))}))),Rn[t.name]==null&&(Rn[t.name]=t2(t.name,t)),Rn[t.name]}var lc=class{lock;child;pins;started;constructor(t,e,n={}){this.child=t,this.pins=e,this.lock=Yf({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await Vr(this.child),this.started=!0}async stop(){await Hr(this.child),this.started=!1}unwrap(){return this.child}async put(t,e,n={}){n?.signal?.throwIfAborted();let o=await this.lock.readLock();try{return await this.child.put(t,e,n)}finally{o()}}async*putMany(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(t,e)}finally{n()}}async get(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(t,e)}finally{n()}}async*getMany(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(t,e)}finally{n()}}async delete(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(t))throw new Error("CID was pinned");await this.child.delete(t,e)}finally{n()}}async*deleteMany(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let o=this;yield*this.child.deleteMany(async function*(){for await(let i of t){if(await o.pins.isPinned(i))throw new Error("CID was pinned");yield i}}(),e)}finally{n()}}async has(t,e={}){e?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(t,e)}finally{n()}}async*getAll(t={}){t?.signal?.throwIfAborted();let e=await this.lock.readLock();try{yield*this.child.getAll(t)}finally{e()}}createSession(t,e){return e?.signal?.throwIfAborted(),this.child.createSession(t,e)}};var Xf=new At("/version"),f0=1;async function h0(r){if(!await r.has(Xf)){await r.put(Xf,D(`${f0}`));return}let t=await r.get(Xf),e=q(t);if(parseInt(e,10)!==f0)throw new Error("Unknown datastore version, a datastore migration may be required")}var Nn={};vt(Nn,{code:()=>Cr,decode:()=>cn,decodeOptions:()=>a2,encode:()=>Ao,encodeOptions:()=>i2,name:()=>c2,toByteView:()=>p0});var d0=42;function p0(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function r2(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let t=L.asCID(r);if(!t)return null;let e=new Uint8Array(t.bytes.byteLength+1);return e.set(t.bytes,1),[new B(w.tag,d0),new B(w.bytes,e)]}function n2(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function o2(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 Zf={float64:!0,typeEncoders:{Object:r2,undefined:n2,number:o2}},i2={...Zf,typeEncoders:{...Zf.typeEncoders}};function s2(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return L.decode(r.subarray(1))}var uc={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};uc.tags[d0]=s2;var a2={...uc,tags:uc.tags.slice()},c2="dag-cbor",Cr=113,Ao=r=>nr(r,Zf),cn=r=>Vt(p0(r),uc);var _o={};vt(_o,{code:()=>Rr,decode:()=>ko,encode:()=>hc,format:()=>b2,name:()=>w2,parse:()=>E2,stringify:()=>b2});var Jf=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(t){let e=this.inRecursive[this.inRecursive.length-1];e&&(e.type===w.array&&(e.elements++,e.elements!==1&&t.push([44])),e.type===w.map&&(e.elements++,e.elements!==1&&(e.elements%2===1?t.push([44]):t.push([58]))))}[w.uint.major](t,e){this.prefix(t);let n=String(e.value),o=[];for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);t.push(o)}[w.negint.major](t,e){this[w.uint.major](t,e)}[w.bytes.major](t,e){throw new Error(`${_r} unsupported type: Uint8Array`)}[w.string.major](t,e){this.prefix(t);let n=Ha(JSON.stringify(e.value));t.push(n.length>32?Ii(n):n)}[w.array.major](t,e){this.prefix(t),this.inRecursive.push({type:w.array,elements:0}),t.push([91])}[w.map.major](t,e){this.prefix(t),this.inRecursive.push({type:w.map,elements:0}),t.push([123])}[w.tag.major](t,e){}[w.float.major](t,e){if(e.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===w.array)t.push([93]);else if(s.type===w.map)t.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(e.value===void 0)throw new Error(`${_r} unsupported type: undefined`);if(this.prefix(t),e.type.name==="true"){t.push([116,114,117,101]);return}else if(e.type.name==="false"){t.push([102,97,108,115,101]);return}else if(e.type.name==="null"){t.push([110,117,108,108]);return}let n=String(e.value),o=[],i=!1;for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s),!i&&(o[s]===46||o[s]===101||o[s]===69)&&(i=!0);i||(o.push(46),o.push(48)),t.push(o)}};function l2(r,t){if(Array.isArray(r[0])||Array.isArray(t[0]))throw new Error(`${_r} complex map keys are not supported`);let e=r[0],n=t[0];if(e.type!==w.string||n.type!==w.string)throw new Error(`${_r} non-string map keys are not supported`);if(e<n)return-1;if(e>n)return 1;throw new Error(`${_r} unexpected duplicate map keys, this is not supported`)}var u2={addBreakTokens:!0,mapSorter:l2};function Ni(r,t){return t=Object.assign({},u2,t),Df(r,new Jf,t)}var Io=class{constructor(t,e={}){this._pos=0,this.data=t,this.options=e,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 t=this.ch();for(;t===32||t===9||t===13||t===10;)t=this.data[++this._pos]}expect(t){if(this.data.length-this._pos<t.length)throw new Error(`${$} unexpected end of input at position ${this._pos}`);for(let e=0;e<t.length;e++)if(this.data[this._pos++]!==t[e])throw new Error(`${$} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...t)}'`)}parseNumber(){let t=this._pos,e=!1,n=!1,o=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(e=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new B(w.uint,0,this._pos-t);if(o([48,49,50,51,52,53,54,55,56,57]),e&&this._pos===t+1)throw new Error(`${$} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${$} unexpected token at position ${this._pos}`);n=!0,this._pos++,o([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,o([48,49,50,51,52,53,54,55,56,57]));let i=String.fromCharCode.apply(null,this.data.subarray(t,this._pos)),s=parseFloat(i);return n?new B(w.float,s,this._pos-t):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new B(s>=0?w.uint:w.negint,s,this._pos-t):new B(s>=0?w.uint:w.negint,BigInt(i),this._pos-t)}parseString(){if(this.ch()!==34)throw new Error(`${$} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let i=this._pos,s=0;i<this.data.length&&s<65536;i++,s++){let a=this.data[i];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,i));return this._pos=i+1,new B(w.string,c,s)}}let t=this._pos,e=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${$} unexpected end of unicode escape sequence at position ${this._pos}`);let i=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${$} unexpected unicode escape character at position ${this._pos}`);i=i*16+a,this._pos++}return i},o=()=>{let i=this.ch(),s=null,a=i>239?4:i>223?3:i>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${$} unexpected unicode sequence at position ${this._pos}`);let c,l,u,f;switch(a){case 1:i<128&&(s=i);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(i&31)<<6|c&63,f>127&&(s=f));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(f=(i&15)<<12|(c&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(f=(i&15)<<18|(c&63)<<12|(l&63)<<6|u&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,e.push(s>>>10&1023|55296),s=56320|s&1023),e.push(s),this._pos+=a};for(;!this.done();){let i=this.ch(),s;switch(i){case 92:if(this._pos++,this.done())throw new Error(`${$} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:e.push(s);break;case 98:e.push(8);break;case 116:e.push(9);break;case 110:e.push(10);break;case 102:e.push(12);break;case 114:e.push(13);break;case 117:e.push(n());break;default:throw new Error(`${$} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new B(w.string,_f(e),this._pos-t);default:if(i<32)throw new Error(`${$} invalid control character at position ${this._pos}`);i<128?(e.push(i),this._pos++):o()}}throw new Error(`${$} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new B(w.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new B(w.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new B(w.null,null,4);case 102:return this.expect([102,97,108,115,101]),new B(w.false,!1,5);case 116:return this.expect([116,114,117,101]),new B(w.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(`${$} 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 B(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${$} 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 B(w.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 B(w.break,void 0,1);if(this.ch()!==44)throw new Error(`${$} 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 B(w.break,void 0,1);let t=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${$} 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"),t}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${$} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function Qf(r,t){return t=Object.assign({tokenizer:new Io(r,t)},t),Vt(r,t)}function h2(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function d2(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let t=L.asCID(r);if(!t)return null;let e=t.toString();return[new B(w.map,1/0,1),new B(w.string,"/",1),new B(w.string,e,e.length),new B(w.break,void 0,1)]}function fc(r){let t=se.encode(r).slice(1);return[new B(w.map,1/0,1),new B(w.string,"/",1),new B(w.map,1/0,1),new B(w.string,"bytes",5),new B(w.string,t,t.length),new B(w.break,void 0,1),new B(w.break,void 0,1)]}function He(r){return fc(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function p2(r){return fc(new Uint8Array(r))}function m2(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function g2(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 y2={typeEncoders:{Object:d2,Buffer:fc,Uint8Array:fc,Int8Array:He,Uint16Array:He,Int16Array:He,Uint32Array:He,Int32Array:He,Float32Array:He,Float64Array:He,Uint8ClampedArray:He,BigInt64Array:He,BigUint64Array:He,DataView:He,ArrayBuffer:p2,undefined:m2,number:g2}},th=class extends Io{constructor(t,e){super(t,e),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let t=this._next();if(t.type===w.map){let e=this._next();if(e.type===w.string&&e.value==="/"){let n=this._next();if(n.type===w.string){if(this._next().type!==w.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new B(w.tag,42,0)}if(n.type===w.map){let o=this._next();if(o.type===w.string&&o.value==="bytes"){let i=this._next();if(i.type===w.string){for(let a=0;a<2;a++)if(this._next().type!==w.break)throw new Error("Invalid encoded Bytes form");let s=se.decode(`m${i.value}`);return new B(w.bytes,s,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(o)}this.tokenBuffer.push(n)}this.tokenBuffer.push(e)}return t}},eh={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};eh.tags[42]=L.parse;var w2="dag-json",Rr=297,hc=r=>Ni(r,y2),ko=r=>{let t=h2(r),e=Object.assign(eh,{tokenizer:new th(t,eh)});return Qf(t,e)},b2=r=>x2.decode(hc(r));var x2=new TextDecoder,E2=r=>ko(v2.encode(r)),v2=new TextEncoder;var Pi={};vt(Pi,{code:()=>Te,createLink:()=>A0,createNode:()=>S0,decode:()=>Nr,encode:()=>P2,name:()=>L2,prepare:()=>oh,validate:()=>ih});var S2=new TextDecoder;function rh(r,t){let e=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(t>=r.length)throw new Error("protobuf: unexpected end of data");let o=r[t++];if(e+=n<28?(o&127)<<n:(o&127)*2**n,o<128)break}return[e,t]}function dc(r,t){let e;[e,t]=rh(r,t);let n=t+e;if(e<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(t,n),n]}function m0(r,t){let e;return[e,t]=rh(r,t),[e&7,e>>3,t]}function A2(r){let t={},e=r.length,n=0;for(;n<e;){let o,i;if([o,i,n]=m0(r,n),i===1){if(t.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(o!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Hash`);if(t.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(t.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[t.Hash,n]=dc(r,n)}else if(i===2){if(t.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(t.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=dc(r,n),t.Name=S2.decode(s)}else if(i===3){if(t.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(o!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${o}) for Tsize`);[t.Tsize,n]=rh(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>e)throw new Error("protobuf: (PBLink) unexpected end of data");return t}function g0(r){let t=r.length,e=0,n,o=!1,i;for(;e<t;){let a,c;if([a,c,e]=m0(r,e),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,e]=dc(r,e),n&&(o=!0)}else if(c===2){if(o)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,e]=dc(r,e),n.push(A2(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(e>t)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return i&&(s.Data=i),s.Links=n||[],s}var w0=new TextEncoder,y0=2**32,I2=2**31;function k2(r,t){let e=t.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");e=Li(t,e,r.Tsize)-1,t[e]=24}if(typeof r.Name=="string"){let n=w0.encode(r.Name);e-=n.length,t.set(n,e),e=Li(t,e,n.length)-1,t[e]=18}return r.Hash&&(e-=r.Hash.length,t.set(r.Hash,e),e=Li(t,e,r.Hash.length)-1,t[e]=10),t.length-e}function b0(r){let t=B2(r),e=new Uint8Array(t),n=t;if(r.Data&&(n-=r.Data.length,e.set(r.Data,n),n=Li(e,n,r.Data.length)-1,e[n]=10),r.Links)for(let o=r.Links.length-1;o>=0;o--){let i=k2(r.Links[o],e.subarray(0,n));n-=i,n=Li(e,n,i)-1,e[n]=18}return e}function _2(r){let t=0;if(r.Hash){let e=r.Hash.length;t+=1+e+Bo(e)}if(typeof r.Name=="string"){let e=w0.encode(r.Name).length;t+=1+e+Bo(e)}return typeof r.Tsize=="number"&&(t+=1+Bo(r.Tsize)),t}function B2(r){let t=0;if(r.Data){let e=r.Data.length;t+=1+e+Bo(e)}if(r.Links)for(let e of r.Links){let n=_2(e);t+=1+n+Bo(n)}return t}function Li(r,t,e){t-=Bo(e);let n=t;for(;e>=I2;)r[t++]=e&127|128,e/=128;for(;e>=128;)r[t++]=e&127|128,e>>>=7;return r[t]=e,n}function Bo(r){return r%2===0&&r++,Math.floor((T2(r)+6)/7)}function T2(r){let t=0;return r>=y0&&(r=Math.floor(r/y0),t=32),r>=65536&&(r>>>=16,t+=16),r>=256&&(r>>>=8,t+=8),t+C2[r]}var C2=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var R2=["Data","Links"],N2=["Hash","Name","Tsize"],nh=new TextEncoder;function E0(r,t){if(r===t)return 0;let e=r.Name?nh.encode(r.Name):[],n=t.Name?nh.encode(t.Name):[],o=e.length,i=n.length;for(let s=0,a=Math.min(o,i);s<a;++s)if(e[s]!==n[s]){o=e[s],i=n[s];break}return o<i?-1:i<o?1:0}function x0(r,t){return!Object.keys(r).some(e=>!t.includes(e))}function v0(r){if(typeof r.asCID=="object"){let e=L.asCID(r);if(!e)throw new TypeError("Invalid DAG-PB form");return{Hash:e}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let t={};if(r.Hash){let e=L.asCID(r.Hash);try{e||(typeof r.Hash=="string"?e=L.parse(r.Hash):r.Hash instanceof Uint8Array&&(e=L.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}e&&(t.Hash=e)}if(!t.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(t.Name=r.Name),typeof r.Tsize=="number"&&(t.Tsize=r.Tsize),t}function oh(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let t={};if(r.Data!==void 0)if(typeof r.Data=="string")t.Data=nh.encode(r.Data);else if(r.Data instanceof Uint8Array)t.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))t.Links=r.Links.map(v0),t.Links.sort(E0);else throw new TypeError("Invalid DAG-PB form");else t.Links=[];return t}function ih(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!x0(r,R2))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let t=0;t<r.Links.length;t++){let e=r.Links[t];if(!e||typeof e!="object"||Array.isArray(e)||e instanceof Uint8Array||e["/"]&&e["/"]===e.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!x0(e,N2))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(e.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(e.Hash==null||!e.Hash["/"]||e.Hash["/"]!==e.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(e.Name!==void 0&&typeof e.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(e.Tsize!==void 0){if(typeof e.Tsize!="number"||e.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(e.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(t>0&&E0(e,r.Links[t-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function S0(r,t=[]){return oh({Data:r,Links:t})}function A0(r,t,e){return v0({Hash:e,Name:r,Tsize:t})}function I0(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var L2="dag-pb",Te=112;function P2(r){ih(r);let t={};return r.Links&&(t.Links=r.Links.map(e=>{let n={};return e.Hash&&(n.Hash=e.Hash.bytes),e.Name!==void 0&&(n.Name=e.Name),e.Tsize!==void 0&&(n.Tsize=e.Tsize),n})),r.Data&&(t.Data=r.Data),b0(t)}function Nr(r){let t=I0(r),e=g0(t),n={};return e.Data&&(n.Data=e.Data),e.Links&&(n.Links=e.Links.map(o=>{let i={};try{i.Hash=L.decode(o.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return o.Name!==void 0&&(i.Name=o.Name),o.Tsize!==void 0&&(i.Tsize=o.Tsize),i})),n}function To(r){return r?.then!=null}function k0(r=[],t){let e={[Te]:Pi,[ae]:wn,[Cr]:Nn,[Rr]:_o,[hr]:Yn};return r.forEach(n=>{e[n.code]=n}),async n=>{let o=e[n];if(o==null&&t!=null){let i=t(n);To(i)?o=await i:o=i,e[o.code]=o}if(o!=null)return o;throw new sc(`Could not load codec for ${n}`)}}function _0(r=[],t){let e={[Xe.code]:Xe,[gs.code]:gs,[bt.code]:bt};return r.forEach(n=>{e[n.code]=n}),async n=>{let o=e[n];if(o==null&&t!=null){let i=t(n);To(i)?o=await i:o=i,e[o.code]=o}if(o!=null)return o;throw new ic(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var pc=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};var mc=class{has(t,e){return Promise.reject(new Error(".has is not implemented"))}put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(t,e){for await(let{cid:n,block:o}of t)await this.put(n,o,e),yield n}get(t,e){return Promise.reject(new Error(".get is not implemented"))}async*getMany(t,e){for await(let n of t)yield{cid:n,block:await this.get(n,e)}}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(t,e){for await(let n of t)await this.delete(n,e),yield n}async*getAll(t){throw new Error(".getAll is not implemented")}};var gc=0,yc=class extends mc{child;constructor(t){super(),this.child=t}put(t,e){return t.multihash.code===gc||this.child==null?t:this.child.put(t,e)}get(t){if(t.multihash.code===gc)return t.multihash.digest;if(this.child==null)throw new pc;return this.child.get(t)}has(t){return t.multihash.code===gc?!0:this.child==null?!1:this.child.has(t)}delete(t){if(t.code!==gc&&this.child!=null)return this.child.delete(t)}getAll(t){return this.child!=null?this.child.getAll(t):[]}};function D2(r){return r[Symbol.asyncIterator]!=null}function O2(r,t){let e=0;if(D2(r))return async function*(){for await(let c of r)await t(c,e++)&&(yield c)}();let n=Wn(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();let s=t(o,e++);if(typeof s.then=="function")return async function*(){await s&&(yield o);for await(let c of n)await t(c,e++)&&(yield c)}();let a=t;return function*(){s===!0&&(yield o);for(let c of n)a(c,e++)&&(yield c)}()}var ve=O2;function U2(r){return r[Symbol.asyncIterator]!=null}function B0(r){return r?.then!=null}function F2(r,t){let e=0;if(U2(r))return async function*(){for await(let c of r){let l=t(c,e++);B0(l)&&await l,yield c}}();let n=Wn(r),{value:o,done:i}=n.next();if(i===!0)return function*(){}();if(typeof t(o,e++)?.then=="function")return async function*(){yield o;for await(let c of n){let l=t(c,e++);B0(l)&&await l,yield c}}();let a=t;return function*(){yield o;for(let c of n)a(c,e++),yield c}()}var sh=F2;var wc=class{child;getHasher;log;logger;components;constructor(t){this.log=t.logger.forComponent("helia:networked-storage"),this.logger=t.logger,this.components=t,this.child=new yc(t.blockstore),this.getHasher=t.getHasher}async put(t,e,n={}){return await this.child.has(t,n)?(n.onProgress?.(new H("blocks:put:duplicate",t)),t):(n.onProgress?.(new H("blocks:put:providers:notify",t)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(t,e,n))),n.onProgress?.(new H("blocks:put:blockstore:put",t)),this.child.put(t,e,n))}async*putMany(t,e={}){let n=ve(t,async({cid:i})=>{let s=await this.child.has(i,e);return s&&e.onProgress?.(new H("blocks:put-many:duplicate",i)),!s}),o=sh(n,async({cid:i,block:s})=>{e.onProgress?.(new H("blocks:put-many:providers:notify",i)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(i,s,e)))});e.onProgress?.(new H("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(o,e)}async get(t,e={}){if(e.offline!==!0&&!await this.child.has(t,e)){let n=await this.getHasher(t.multihash.code);e.onProgress?.(new H("blocks:get:providers:get",t));let o=await T0(t,this.components.blockBrokers,n,{...e,log:this.log});return e.onProgress?.(new H("blocks:get:blockstore:put",t)),await this.child.put(t,o,e),e.onProgress?.(new H("blocks:get:providers:notify",t)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(t,o,e))),o}return e.onProgress?.(new H("blocks:get:blockstore:get",t)),this.child.get(t,e)}async*getMany(t,e={}){e.onProgress?.(new H("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(sh(t,async n=>{if(e.offline!==!0&&!await this.child.has(n,e)){let o=await this.getHasher(n.multihash.code);e.onProgress?.(new H("blocks:get-many:providers:get",n));let i=await T0(n,this.components.blockBrokers,o,{...e,log:this.log});e.onProgress?.(new H("blocks:get-many:blockstore:put",n)),await this.child.put(n,i,e),e.onProgress?.(new H("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,i,e)))}}))}async delete(t,e={}){e.onProgress?.(new H("blocks:delete:blockstore:delete",t)),await this.child.delete(t,e)}async*deleteMany(t,e={}){e.onProgress?.(new H("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany(async function*(){for await(let n of t)yield n}(),e)}async has(t,e={}){return this.child.has(t,e)}async*getAll(t={}){t.onProgress?.(new H("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(t)}},bc=class extends wc{started;constructor(t){super(t),this.started=!1}isStarted(){return this.started}async start(){await Vr(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await Hr(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(t,e){let n=this.components.blockBrokers.map(o=>o.createSession==null?o:o.createSession(e));return new ah({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:t})}},ah=class extends wc{closeController;constructor(t,e){super(t),this.closeController=new AbortController,mt(1/0,this.closeController.signal),this.log=t.logger.forComponent(`helia:session-storage:${e.root}`)}close(){this.closeController.abort()}async put(t,e,n={}){let o=Yt([this.closeController.signal,n.signal]);mt(1/0,o);try{return await super.put(t,e,{...n,signal:o})}finally{o.clear()}}async*putMany(t,e={}){let n=Yt([this.closeController.signal,e.signal]);mt(1/0,n);try{yield*super.putMany(t,{...e,signal:n})}finally{n.clear()}}async get(t,e={}){let n=Yt([this.closeController.signal,e.signal]);mt(1/0,n);try{return await super.get(t,{...e,signal:n})}finally{n.clear()}}async*getMany(t,e={}){let n=Yt([this.closeController.signal,e.signal]);mt(1/0,n);try{yield*super.getMany(t,{...e,signal:n})}finally{n.clear()}}async delete(t,e={}){let n=Yt([this.closeController.signal,e.signal]);mt(1/0,n);try{await super.delete(t,{...e,signal:n})}finally{n.clear()}}async*deleteMany(t,e={}){let n=Yt([this.closeController.signal,e.signal]);mt(1/0,n);try{yield*super.deleteMany(t,{...e,signal:n})}finally{n.clear()}}async has(t,e={}){let n=Yt([this.closeController.signal,e.signal]);mt(1/0,n);try{return await super.has(t,{...e,signal:n})}finally{n.clear()}}async*getAll(t={}){let e=Yt([this.closeController.signal,t.signal]);mt(1/0,e);try{yield*super.getAll({...t,signal:e})}finally{e.clear()}}};function M2(r){return typeof r.retrieve=="function"}var V2=(r,t)=>{if(t==null)throw new gt(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async e=>{let n,o=t.digest(e);if(To(o)?n=await o:n=o,!Z(n.digest,r.multihash.digest))throw new Ae("Hash of downloaded block did not match multihash from passed CID")}};async function T0(r,t,e,n){let o=V2(r,e),i=new AbortController,s=Yt([i.signal,n.signal]);mt(1/0,i.signal,s);let a=[];for(let c of t)M2(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:s,validateFn:async f=>{await o(f),l=!0}});return l||await o(u),u}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{i.abort(),s.clear()}}var ch=Ot(yf(),1);var H2=Math.LN2*Math.LN2,xc=class r{static create(t,e=.005){let n=$2(t,e);return new r(n)}seeds;bits;buffer;constructor(t={}){t.seeds!=null?this.seeds=t.seeds:this.seeds=z2(t.hashes??8),this.bits=t.bits??1024,this.buffer=re(Math.ceil(this.bits/8))}add(t){typeof t=="string"&&(t=D(t));for(let e=0;e<this.seeds.length;e++){let o=ch.default.x86.hash32(t,this.seeds[e])%this.bits;this.setbit(o)}}has(t){typeof t=="string"&&(t=D(t));for(let e=0;e<this.seeds.length;e++){let o=ch.default.x86.hash32(t,this.seeds[e])%this.bits;if(!this.getbit(o))return!1}return!0}clear(){this.buffer.fill(0)}setbit(t){let e=0,n=t;for(;n>7;)e++,n-=8;let o=this.buffer[e];o|=1<<n,this.buffer[e]=o}getbit(t){let e=0,n=t;for(;n>7;)e++,n-=8;return(this.buffer[e]&1<<n)!==0}};function $2(r,t=.005){let e=Math.round(-1*r*Math.log(t)/H2),n=Math.round(e/r*Math.LN2);return{bits:e,hashes:n}}function z2(r){let t,e,n=[];for(let o=0;o<r;o++)for(t=new fr(xa(4)),n[o]=t.getUint32(0,!0),e=0;e<o;e++)if(n[o]===n[e]){o--;break}return n}var Di=class extends qn{intialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;constructor(t,e){super(),mt(1/0,this),this.name=e.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=e.minProviders??1,this.maxProviders=e.maxProviders??5,this.providers=[],this.evictionFilter=xc.create(this.maxProviders)}async retrieve(t,e={}){let n=se.encode(t.multihash.bytes),o=this.requests.get(n);if(o!=null)return this.log("join existing request for %c",t),o;let i=ft();if(this.requests.set(n,i.promise),this.providers.length===0){let l=!1;this.intialPeerSearchComplete==null&&(l=!0,this.log=this.logger.forComponent(`${this.name}:${t}`),this.intialPeerSearchComplete=this.findProviders(t,this.minProviders,e)),await this.intialPeerSearchComplete,l&&this.log("found initial session peers for %c",t)}let s=!1,a=new kr({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",l=>{this.log.error("error querying provider %o, evicting from session",l.detail.job.options.provider,l.detail.error),this.evict(l.detail.job.options.provider)}),a.addEventListener("success",l=>{s=!0,i.resolve(l.detail.result)}),a.addEventListener("idle",()=>{s||e.signal?.aborted===!0||Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",t);for(let l=0;l<this.minProviders&&this.providers.length!==0;l++){let u=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(u)}await this.findProviders(t,this.minProviders,e),this.log("found new providers re-retrieving %c",t),this.requests.delete(n),i.resolve(await this.retrieve(t,e))}).catch(l=>{this.log.error("could not find new providers for %c",t,l),i.reject(l)})});let c=l=>{a.add(async()=>this.queryProvider(t,l.detail,e),{provider:l.detail}).catch(u=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,u)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async l=>a.add(async()=>this.queryProvider(t,l,e),{provider:l}))).catch(l=>{e.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",t,l)});try{return await i.promise}finally{this.removeEventListener("provider",c),a.clear(),this.requests.delete(n)}}evict(t){this.evictionFilter.add(this.toEvictionKey(t));let e=this.providers.findIndex(n=>this.equals(n,t));e!==-1&&this.providers.splice(e,1)}isEvicted(t){return this.evictionFilter.has(this.toEvictionKey(t))}hasProvider(t){return!!(this.providers.find(e=>this.equals(e,t))!=null||this.isEvicted(t))}async findProviders(t,e,n){let o=ft(),i=0;return Promise.resolve().then(async()=>{this.log("finding %d-%d new provider(s) for %c",e,this.maxProviders,t);for await(let s of this.findNewProviders(t,n)){if(i===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",i,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),i++,i===e&&(this.log("session is ready"),o.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",i);break}}if(this.log("found %d/%d new session peers",i,this.maxProviders),i<e)throw new oc(`Found ${i} of ${e} ${this.name} providers for ${t}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",t,s.errors??s),o.reject(s)}),o.promise}};var Ec=class{blockstore;datastore;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(t){this.logger=t.logger??Gm(),this.log=this.logger.forComponent("helia"),this.getHasher=_0(t.hashers,t.loadHasher),this.getCodec=k0(t.codecs,t.loadCodec),this.dns=t.dns??Ai(),this.metrics=t.metrics;let e={blockstore:t.blockstore,datastore:t.datastore,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...t.components??{}};this.routing=e.routing=new cc(e,{routers:(t.routers??[]).flatMap(o=>{let i=[o];return o[Wo]!=null&&i.push(o[Wo]),o[jo]!=null&&i.push(o[jo]),i}),providerLookupConcurrency:t.providerLookupConcurrency});let n=new bc(e);this.pins=new nc(t.datastore,n,this.getCodec),this.blockstore=new lc(n,this.pins,{holdGcLock:t.holdGcLock??!0}),this.datastore=t.datastore,e.blockBrokers=t.blockBrokers.map(o=>o(e))}async start(){await h0(this.datastore),await Vr(this.blockstore,this.datastore,this.routing)}async stop(){await Hr(this.blockstore,this.datastore,this.routing)}async gc(t={}){let e=await this.blockstore.lock.writeLock();try{let n=this,o=this.blockstore.unwrap();this.log("gc start"),await ur(o.deleteMany(async function*(){for await(let{cid:i}of o.getAll())try{if(await n.pins.isPinned(i,t))continue;yield i,t.onProgress?.(new H("helia:gc:deleted",i))}catch(s){n.log.error("Error during gc",s),t.onProgress?.(new H("helia:gc:error",s))}}()))}finally{e()}this.log("gc finished")}};var vc=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let i=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(i*=t,i+=u,i>l||(s+=1,e!==void 0&&s>e))return}if(s!==0)return!n&&c&&s>1?void 0:i})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return e[o]=s[0],e[o+1]=s[1],e[o+2]=s[2],e[o+3]=s[3],[o+4,!0]}let i=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(i===void 0)return[o,!1];e[o]=i>>8,e[o+1]=i&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let i=new Uint8Array(14),s=16-(n+2),[a]=t(i.subarray(0,s));return e.set(i.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var C0=45,G2=15,Co=new vc;function lh(r){if(!(r.length>G2))return Co.new(r).parseWith(()=>Co.readIPv4Addr())}function uh(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>C0))return Co.new(r).parseWith(()=>Co.readIPv6Addr())}function Sc(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>C0))return Co.new(r).parseWith(()=>Co.readIPAddr())}function Ro(r){return!!lh(r)}function No(r){return!!uh(r)}function Ac(r){return!!Sc(r)}var N0=Ot(R0(),1),W2=["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"],j2=W2.map(r=>new N0.Netmask(r));function fh(r){for(let t of j2)if(t.contains(r))return!0;return!1}function Y2(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function X2(r){let t=r.split(":");if(t.length<2)return!1;let e=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(e.substring(0,2),16)}.${parseInt(e.substring(2),16)}`;return fh(o)}function Z2(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function J2(r){let t=r.split(":"),e=t[t.length-1];return fh(e)}function Q2(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function L0(r){return Ro(r)?fh(r):Y2(r)?X2(r):Z2(r)?J2(r):No(r)?Q2(r):void 0}var tS=r=>r.toString().split("/").slice(1),Lo=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),nt=r=>({match:t=>Lo(e=>e===r).match(t),pattern:r}),Ui=()=>({match:r=>Lo(t=>typeof t=="string").match(r),pattern:"{string}"}),Fi=()=>({match:r=>Lo(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),pt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{Y.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Mi=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{bu.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),ut=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Qt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),ot=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function Et(...r){function t(o){let i=tS(o);for(let s of r){let a=s.match(i);if(a===!1)return!1;i=a}return i}function e(o){return t(o)!==!1}function n(o){let i=t(o);return i===!1?!1:i.length===0}return{matchers:r,matches:e,exactMatch:n}}var kc=ot(nt("dns4"),Ui()),_c=ot(nt("dns6"),Ui()),Bc=ot(nt("dnsaddr"),Ui()),dh=ot(nt("dns"),Ui()),dN=Et(kc,ut(pt())),pN=Et(_c,ut(pt())),mN=Et(Bc,ut(pt())),P0=Et(Qt(dh,Bc,kc,_c),ut(pt())),D0=ot(nt("ip4"),Lo(Ro)),O0=ot(nt("ip6"),Lo(No)),ph=Qt(D0,O0),Lr=Qt(ph,dh,kc,_c,Bc),gN=Et(Qt(ph,ot(Qt(dh,Bc,kc,_c),ut(pt())))),yN=Et(D0),wN=Et(O0),bN=Et(ph),mh=ot(Lr,nt("tcp"),Fi()),Vi=ot(Lr,nt("udp"),Fi()),xN=Et(ot(mh,ut(pt()))),EN=Et(Vi),gh=ot(Vi,nt("quic")),Tc=ot(Vi,nt("quic-v1")),eS=Qt(gh,Tc),vN=Et(gh),SN=Et(Tc),hh=Qt(Lr,mh,Vi,gh,Tc),U0=Qt(ot(hh,nt("ws"),ut(pt()))),AN=Et(U0),F0=Qt(ot(hh,nt("wss"),ut(pt())),ot(hh,nt("tls"),nt("ws"),ut(pt()))),IN=Et(F0),M0=ot(Vi,nt("webrtc-direct"),ut(Mi()),ut(Mi()),ut(pt())),kN=Et(M0),V0=ot(Tc,nt("webtransport"),ut(Mi()),ut(Mi()),ut(pt())),_N=Et(V0),Ic=Qt(U0,F0,ot(mh,ut(pt())),ot(eS,ut(pt())),ot(Lr,ut(pt())),M0,V0,pt()),BN=Et(Ic),rS=ot(Ic,nt("p2p-circuit"),pt()),TN=Et(rS),nS=Qt(ot(Ic,nt("p2p-circuit"),nt("webrtc"),ut(pt())),ot(Ic,nt("webrtc"),ut(pt())),nt("webrtc")),CN=Et(nS),oS=Qt(ot(Lr,nt("tcp"),Fi(),nt("http"),ut(pt())),ot(Lr,nt("http"),ut(pt()))),H0=Et(oS),iS=Qt(ot(Lr,nt("tcp"),Qt(ot(nt("443"),nt("http")),ot(Fi(),nt("https"))),ut(pt())),ot(Lr,nt("tls"),nt("http"),ut(pt())),ot(Lr,nt("https"),ut(pt()))),$0=Et(iS);var FN=parseInt("0xFFFF",16),MN=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var K0=Ro,uS=No,yh=function(r){let t=0;if(r=r.toString().trim(),K0(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(uS(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let i=K0(e[n]),s;i&&(s=yh(e[n]),e[n]=q(s.slice(0,2),"base16")),s!=null&&++n<8&&e.splice(n,0,q(s.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let i=[n,1];for(n=9-e.length;n>0;n--)i.push("0");e.splice.apply(e,i)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let i=parseInt(e[n],16);o[t++]=i>>8&255,o[t++]=i&255}return o}throw new Error("invalid ip address")},G0=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let i=0;i<e;i++)o.push(r[t+i]);return o.join(".")}if(e===16){let o=[];for(let i=0;i<e;i+=2)o.push(n.getUint16(t+i).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Po={},wh={},hS=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];hS.forEach(r=>{let t=dS(...r);wh[t.code]=t,Po[t.name]=t});function dS(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function X(r){if(typeof r=="number"){if(wh[r]!=null)return wh[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Po[r]!=null)return Po[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var xL=X("ip4"),EL=X("ip6"),vL=X("ipcidr");function vh(r,t){switch(X(r).code){case 4:case 41:return mS(t);case 42:return Eh(t);case 6:case 273:case 33:case 132:return Y0(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Eh(t);case 421:return bS(t);case 444:return j0(t);case 445:return j0(t);case 466:return wS(t);case 481:return globalThis.encodeURIComponent(Eh(t));default:return q(t,"base16")}}function Sh(r,t){switch(X(r).code){case 4:return W0(t);case 41:return W0(t);case 42:return xh(t);case 6:case 273:case 33:case 132:return Ah(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return xh(t);case 421:return gS(t);case 444:return xS(t);case 445:return ES(t);case 466:return yS(t);case 481:return xh(globalThis.decodeURIComponent(t));default:return D(t,"base16")}}var bh=Object.values(Qo).map(r=>r.decoder),pS=function(){let r=bh[0].or(bh[1]);return bh.slice(2).forEach(t=>r=r.or(t)),r}();function W0(r){if(!Ac(r))throw new Error("invalid ip address");return yh(r)}function mS(r){let t=G0(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Ac(t))throw new Error("invalid ip address");return t}function Ah(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Y0(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function xh(r){let t=D(r),e=Uint8Array.from(Gn(t.length));return ct([e,t],e.length+t.length)}function Eh(r){let t=mn(r);if(r=r.slice(oe(t)),r.length!==t)throw new Error("inconsistent lengths");return q(r)}function gS(r){let t;r[0]==="Q"||r[0]==="1"?t=wt(Y.decode(`z${r}`)).bytes:t=L.parse(r).multihash.bytes;let e=Uint8Array.from(Gn(t.length));return ct([e,t],e.length+t.length)}function yS(r){let t=pS.decode(r),e=Uint8Array.from(Gn(t.length));return ct([e,t],e.length+t.length)}function wS(r){let t=mn(r),e=r.slice(oe(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+q(e,"base64url")}function bS(r){let t=mn(r),e=r.slice(oe(t));if(e.length!==t)throw new Error("inconsistent lengths");return q(e,"base58btc")}function xS(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=St.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ah(n);return ct([e,o],e.length+o.length)}function ES(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=St.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ah(n);return ct([e,o],e.length+o.length)}function j0(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=q(t,"base32"),o=Y0(e);return`${n}:${o}`}function X0(r){r=Ih(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let i=0;i<o.length;i++){let s=o[i],a=X(s);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(i++,i>=o.length)throw J0("invalid address: "+r);if(a.path===!0){n=Ih(o.slice(i).join("/")),t.push([a.code,Sh(a.code,n)]),e.push([a.code,n]);break}let c=Sh(a.code,o[i]);t.push([a.code,c]),e.push([a.code,vh(a.code,c)])}return{string:Z0(e),bytes:_h(t),tuples:t,stringTuples:e,path:n}}function kh(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let i=mn(r,o),s=oe(i),a=X(i),c=vS(a,r.slice(o+s));if(c===0){t.push([i]),e.push([i]),o+=s;continue}let l=r.slice(o+s,o+s+c);if(o+=c+s,o>r.length)throw J0("Invalid address Uint8Array: "+q(r,"base16"));t.push([i,l]);let u=vh(i,l);if(e.push([i,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Z0(e),tuples:t,stringTuples:e,path:n}}function Z0(r){let t=[];return r.map(e=>{let n=X(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Ih(t.join("/"))}function _h(r){return ct(r.map(t=>{let e=X(t[0]),n=Uint8Array.from(Gn(e.code));return t.length>1&&t[1]!=null&&(n=ct([n,t[1]])),n}))}function vS(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=mn(t instanceof Uint8Array?t:Uint8Array.from(t));return e+oe(e)}}function Ih(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function J0(r){return new Error("Error parsing address: "+r)}var SS=Symbol.for("nodejs.util.inspect.custom"),Th=Symbol.for("@multiformats/js-multiaddr/multiaddr"),AS=[X("dns").code,X("dns4").code,X("dns6").code,X("dnsaddr").code],Bh=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},Cc=class r{bytes;#t;#r;#a;#c;[Th]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=kh(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=X0(t)}else if(ty(t))e=kh(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#r=e.tuples,this.#a=e.stringTuples,this.#c=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,i="",s=X("tcp"),a=X("udp"),c=X("ip4"),l=X("ip6"),u=X("dns6"),f=X("ip6zone");for(let[h,m]of this.stringTuples())h===f.code&&(i=`%${m??""}`),AS.includes(h)&&(e=s.name,o=443,n=`${m??""}${i}`,t=h===u.code?6:4),(h===s.code||h===a.code)&&(e=X(h).name,o=parseInt(m??"")),(h===c.code||h===l.code)&&(e=X(h).name,n=`${m??""}${i}`,t=h===l.code?6:4);if(t==null||e==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:t,host:n,transport:e,port:o}}protos(){return this.#r.map(([t])=>Object.assign({},X(t)))}protoCodes(){return this.#r.map(([t])=>t)}protoNames(){return this.#r.map(([t])=>X(t).name)}tuples(){return this.#r}stringTuples(){return this.#a}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(_h(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Po.p2p.code&&t.push([n,o]),n===Po["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?q(Y.decode(`z${n}`),"base58btc"):q(L.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#c}equals(t){return Z(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(i=>i.resolvable);if(e==null)return[this];let n=Q0.get(e.name);if(n==null)throw new Bh(`no available resolver for ${e.name}`);return(await n(this,t)).map(i=>Pr(i))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[SS](){return`Multiaddr(${this.#t})`}};var Q0=new Map;function ty(r){return!!r?.[Th]}function Pr(r){return new Cc(r)}var IS=[X("tcp").code,X("dns").code,X("dnsaddr").code,X("dns4").code,X("dns6").code];function ey(r){let t;try{t=X("sni").code}catch{return null}for(let[e,n]of r)if(e===t&&n!==void 0)return n;return null}function ry(r){return r.some(([t,e])=>t===X("tls").code)}function me(r,t,e){let n=ny[X(r).name];if(n===void 0)throw new Error(`Can't interpret protocol ${X(r).name}`);let o=n(t,e);return r===X("ip6").code?`[${o}]`:o}var ny={ip4:(r,t)=>r,ip6:(r,t)=>t.length===0?r:`[${r}]`,tcp:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`tcp://${me(e[0],e[1]??"",t)}:${r}`},udp:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`udp://${me(e[0],e[1]??"",t)}:${r}`},dnsaddr:(r,t)=>r,dns4:(r,t)=>r,dns6:(r,t)=>r,dns:(r,t)=>r,ipfs:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/ipfs/${r}`},p2p:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/p2p/${r}`},http:(r,t)=>{let e=ry(t),n=ey(t);if(e&&n!==null)return`https://${n}`;let o=e?"https://":"http://",i=t.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=me(i[0],i[1]??"",t);return s=s.replace("tcp://",""),`${o}${s}`},"http-path":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=me(e[0],e[1]??"",t),o=decodeURIComponent(r);return`${n}/${o}`},tls:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return me(e[0],e[1]??"",t)},sni:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return me(e[0],e[1]??"",t)},https:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=me(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(r,t)=>{let e=ry(t),n=ey(t);if(e&&n!==null)return`wss://${n}`;let o=e?"wss://":"ws://",i=t.pop();if(i===void 0)throw new Error("Unexpected end of multiaddr");let s=me(i[0],i[1]??"",t);return s=s.replace("tcp://",""),`${o}${s}`},wss:(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");let n=me(e[0],e[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(r,t)=>{let e=t.pop();if(e===void 0)throw new Error("Unexpected end of multiaddr");return`${me(e[0],e[1]??"",t)}/p2p-webrtc-direct`}};function oy(r,t){let n=Pr(r).stringTuples(),o=n.pop();if(o===void 0)throw new Error("Unexpected end of multiaddr");let i=X(o[0]),s=ny[i.name];if(s==null)throw new Error(`No interpreter found for ${i.name}`);let a=s(o[1]??"",n);return t?.assumeHttp!==!1&&IS.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 Rc=class{url;#t=0;#r=0;#a=0;#c=0;#g=new Map;log;constructor(t,e){this.url=t instanceof URL?t:new URL(t),this.log=e.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#S(t){let e=t.multihash.bytes;return se.encode(e)}async getRawBlock(t,e){let n=new URL(this.url.toString());if(n.pathname=`/ipfs/${t.toString()}`,n.search="?format=raw",e?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${t} from gateway ${this.url} was aborted prior to fetch`);let o=this.#S(t),i=new AbortController,s=()=>{i.abort()};e?.addEventListener("abort",s);try{let a=this.#g.get(o);return a==null&&(this.#t++,a=fetch(n.toString(),{signal:i.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"}).then(async c=>{if(this.log("GET %s %d",n,c.status),!c.ok)throw this.#r++,new Error(`unable to fetch raw block for CID ${t} from gateway ${this.url}`);return this.#c++,new Uint8Array(await c.arrayBuffer())}),this.#g.set(o,a)),await a}catch{throw e?.aborted===!0?new Error(`fetching raw block for CID ${t} from gateway ${this.url} was aborted`):(this.#r++,new Error(`unable to fetch raw block for CID ${t}`))}finally{e?.removeEventListener("abort",s),this.#g.delete(o)}}reliability(){return this.#t===0?1:this.#a>0?-1/0:this.#c/(this.#t+this.#r*3)}incrementInvalidBlocks(){this.#a++}getStats(){return{attempts:this.#t,errors:this.#r,invalidBlocks:this.#a,successes:this.#c,pendingResponses:this.#g.size}}};function kS(r,t,e){return r.filter(n=>{if($0.matches(n)||t&&H0.matches(n))return e||P0.matches(n)?!0:L0(n.toOptions().host)===!1;if(!t&&e){let{host:o}=n.toOptions();if(o==="127.0.0.1"||o==="localhost"||o.endsWith(".localhost"))return!0}return!1})}async function*Nc(r,t,e,n,o,i){for await(let s of t.findProviders(r,i)){let a=kS(s.multiaddrs,n,o);if(a.length===0)continue;let c=oy(a[0]);yield new Rc(c,e)}}var Ch=class extends Di{routing;allowInsecure;allowLocal;constructor(t,e){super(t,{...e,name:"helia:trustless-gateway:session"}),this.routing=t.routing,this.allowInsecure=e.allowInsecure??Lc,this.allowLocal=e.allowLocal??Pc}async queryProvider(t,e,n){this.log("fetching BLOCK for %c from %s",t,e.url);let o=await e.getRawBlock(t,n.signal);return this.log.trace("got block for %c from %s",t,e.url),await n.validateFn?.(o),o}async*findNewProviders(t,e={}){yield*Nc(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,e)}toEvictionKey(t){return t.url.toString()}equals(t,e){return t.url.toString()===e.url.toString()}};function iy(r,t){return new Ch(r,t)}var Dc=class{allowInsecure;allowLocal;routing;log;logger;constructor(t,e={}){this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=e.allowInsecure??Lc,this.allowLocal=e.allowLocal??Pc}async retrieve(t,e={}){let n=[];for await(let o of Nc(t,this.routing,this.logger,this.allowInsecure,this.allowLocal,e)){this.log("getting block for %c from %s",t,o.url);try{let i=await o.getRawBlock(t,e.signal);this.log.trace("got block for %c from %s",t,o.url);try{await e.validateFn?.(i)}catch(s){this.log.error("failed to validate block for %c from %s",t,o.url,s);continue}return i}catch(i){if(this.log.error("failed to get block for %c from %s",t,o.url,i),i instanceof Error?n.push(i):n.push(new Error(`Unable to fetch raw block for CID ${t} from gateway ${o.url}`)),e.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,o.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${t} from any gateway`):new Error(`Unable to fetch raw block for CID ${t} from any gateway`)}createSession(t={}){return iy({logger:this.logger,routing:this.routing},{...t,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure})}};var Lc=!1,Pc=!1;function Hi(r={}){return t=>new Dc(t,r)}W.formatters.b=r=>r==null?"undefined":Y.baseEncode(r);W.formatters.t=r=>r==null?"undefined":St.baseEncode(r);W.formatters.m=r=>r==null?"undefined":se.baseEncode(r);W.formatters.p=r=>r==null?"undefined":r.toString();W.formatters.c=r=>r==null?"undefined":r.toString();W.formatters.k=r=>r==null?"undefined":r.toString();W.formatters.a=r=>r==null?"undefined":r.toString();W.formatters.e=r=>r==null?"undefined":r.stack??r.message;function _S(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function Ce(r){let t=_S(`${r}:trace`);return W.enabled(`${r}:trace`)&&W.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=W(`${r}:trace`)),Object.assign(W(r),{error:W(`${r}:error`),trace:t})}async function*Oc(r,t={}){let e=r.getReader();try{for(;;){let n=await e.read();if(n.done)return;yield n.value}}finally{t.preventCancel!==!0&&await e.cancel(),e.releaseLock()}}var LS=Ot(Do(),1);var $e=class extends Error{static name="SignatureVerificationError";constructor(t="Record signature verification failed"){super(t),this.name="SignatureVerificationError"}},Uc=class extends Error{static name="RecordExpiredError";constructor(t="Record has expired"){super(t),this.name="RecordExpiredError"}},Oo=class extends Error{static name="UnsupportedValidityError";constructor(t="The validity type is unsupported"){super(t),this.name="UnsupportedValidityError"}},Fc=class extends Error{static name="RecordTooLargeError";constructor(t="The record is too large"){super(t),this.name="RecordTooLargeError"}},Mc=class extends Error{static name="InvalidValueError";constructor(t="Value must be a valid content path starting with /"){super(t),this.name="InvalidValueError"}},Vc=class extends Error{static name="InvalidRecordDataError";constructor(t="Invalid record data"){super(t),this.name="InvalidRecordDataError"}},$i=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(t="Invalid embedded public key"){super(t),this.name="InvalidEmbeddedPublicKeyError"}};var ze;(function(r){let t;(function(o){o.EOL="EOL"})(t=r.ValidityType||(r.ValidityType={}));let e;(function(o){o[o.EOL=0]="EOL"})(e||(e={})),function(o){o.codec=()=>dr(e)}(t=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=le((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.value!=null&&(i.uint32(10),i.bytes(o.value)),o.signatureV1!=null&&(i.uint32(18),i.bytes(o.signatureV1)),o.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(o.validityType,i)),o.validity!=null&&(i.uint32(34),i.bytes(o.validity)),o.sequence!=null&&(i.uint32(40),i.uint64(o.sequence)),o.ttl!=null&&(i.uint32(48),i.uint64(o.ttl)),o.pubKey!=null&&(i.uint32(58),i.bytes(o.pubKey)),o.signatureV2!=null&&(i.uint32(66),i.bytes(o.signatureV2)),o.data!=null&&(i.uint32(74),i.bytes(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ce(o,r.codec()),r.decode=(o,i)=>ie(o,r.codec(),i)})(ze||(ze={}));var BS=Ce("ipns:utils"),sy=D("/ipns/");var TS=0,CS=18;function ay(r){let t;if(r.pubKey!=null)try{t=Ia(r.pubKey)}catch(e){throw BS.error(e),e}if(t!=null)return t}function cy(r){let t=D("ipns-signature:");return ct([t,r])}function Ln(r){return"signatureV1"in r?ze.encode({value:D(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:D(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):ze.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function or(r){let t=ze.decode(r);if(t.sequence!=null&&(t.sequence=BigInt(t.sequence)),t.ttl!=null&&(t.ttl=BigInt(t.ttl)),t.signatureV2==null||t.data==null)throw new $e("Missing data or signatureV2");let e=ly(t.data),n=RS(e.Value),o=q(e.Validity);if(t.value!=null&&t.signatureV1!=null)return NS(t),{value:n,validityType:ze.ValidityType.EOL,validity:o,sequence:e.Sequence,ttl:e.TTL,pubKey:t.pubKey,signatureV1:t.signatureV1,signatureV2:t.signatureV2,data:t.data};if(t.signatureV2!=null)return{value:n,validityType:ze.ValidityType.EOL,validity:o,sequence:e.Sequence,ttl:e.TTL,pubKey:t.pubKey,signatureV2:t.signatureV2,data:t.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function zi(r){return ct([sy,r.bytes])}function Dr(r){let t=wt(r.slice(sy.length));if(!Hc(t,TS)&&!Hc(t,CS))throw new Ae("Multihash in IPNS key was not identity or sha2-256");return t}function ly(r){let t=Vt(r);if(t.ValidityType===0)t.ValidityType=ze.ValidityType.EOL;else throw new Oo("The validity type is unsupported");return Number.isInteger(t.Sequence)&&(t.Sequence=BigInt(t.Sequence)),Number.isInteger(t.TTL)&&(t.TTL=BigInt(t.TTL)),t}function RS(r){let t=q(r).trim();if(t.startsWith("/"))return t;try{return`/ipfs/${L.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${L.parse(t).toV1().toString()}`}catch{}throw new Mc("Value must be a valid content path starting with /")}function NS(r){if(r.data==null)throw new Vc("Record data is missing");let t=ly(r.data);if(!Z(t.Value,r.value??new Uint8Array(0)))throw new $e('Field "value" did not match between protobuf and CBOR');if(!Z(t.Validity,r.validity??new Uint8Array(0)))throw new $e('Field "validity" did not match between protobuf and CBOR');if(t.ValidityType!==r.validityType)throw new $e('Field "validityType" did not match between protobuf and CBOR');if(t.Sequence!==r.sequence)throw new $e('Field "sequence" did not match between protobuf and CBOR');if(t.TTL!==r.ttl)throw new $e('Field "ttl" did not match between protobuf and CBOR')}function Hc(r,t){return r.code===t}var HP=Ce("ipns"),$P=60*60*1e9,PS="/ipns/",zP=PS.length;var uy=Ot(Do(),1);var $c=Ce("ipns:validator"),DS=1024*10,OS=async(r,t)=>{let e=or(t),n;try{let o=cy(e.data);n=await r.verify(o,e.signatureV2)}catch{n=!1}if(!n)throw $c.error("record signature verification failed"),new $e("Record signature verification failed");if(e.validityType===ze.ValidityType.EOL){if(uy.default.fromString(e.validity).toDate().getTime()<Date.now())throw $c.error("record has expired"),new Uc("record has expired")}else if(e.validityType!=null)throw $c.error("the validity type is unsupported"),new Oo("The validity type is unsupported");$c("ipns record for %s is valid",e.value)};async function fy(r,t){if(t.byteLength>DS)throw new Fc("The record is too large");let e=Dr(r),n;Hc(e,0)&&(n=rn(e));let o=or(t),i=ay(o)??n;if(i==null)throw new $i("Could not extract public key from IPNS record or routing key");let s=zi(i.toMultihash());if(!Z(r,s))throw new $i("Embedded public key did not match routing key");await OS(i,t)}async function*qi(r){let t=/\r?\n/,e=new TextDecoder("utf8"),n="";for await(let o of r){typeof o=="string"&&(o=new TextEncoder().encode(o)),n+=e.decode(o,{stream:!0});let i=n.split(t);n=i.pop()??"";for(let s=0;s<i.length;s++)yield JSON.parse(i[s])}n+=e.decode(),n!==""&&(yield JSON.parse(n))}var Uo=class extends Error{static name="InvalidRequestError";constructor(t="Invalid request"){super(t),this.name="InvalidRequestError"}},Pn=class extends Error{static name="BadResponseError";constructor(t="Bad response"){super(t),this.name="BadResponseError"}};function US(r){return r[Symbol.asyncIterator]!=null}function FS(r){if(US(r))return(async()=>{for await(let t of r)return t})();for(let t of r)return t}var zc=FS;var hy=D("/ipns/");function dy(r){return Z(r.subarray(0,hy.byteLength),hy)}var qc=class{client;constructor(t){this.client=t}async*findProviders(t,e={}){yield*zt(this.client.getProviders(t,e),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async put(t,e,n){if(!dy(t))return;let o=Dr(t),i=L.createV1(114,o),s=or(e);await this.client.putIPNS(i,s,n)}async get(t,e){if(!dy(t))throw new _t("Not found");let n=Dr(t),o=L.createV1(114,n);try{let i=await this.client.getIPNS(o,e);return Ln(i)}catch(i){throw i.name==="BadResponseError"?new _t("Not found"):i}}},Kc=class{client;constructor(t){this.client=t}async findPeer(t,e={}){let n=await zc(this.client.getPeers(t,e));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new _t("Not found")}async*getClosestPeers(t,e={}){}};var te=Ce("delegated-routing-v1-http-api-client"),py={concurrentRequests:4,timeout:3e4},Gc=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;constructor(t,e={}){this.started=!1,this.shutDownController=new AbortController,mt(1/0,this.shutDownController.signal),this.httpQueue=new de({concurrency:e.concurrentRequests??py.concurrentRequests}),this.clientUrl=t instanceof URL?t:new URL(t),this.timeout=e.timeout??py.timeout,this.filterAddrs=e.filterAddrs,this.filterProtocols=e.filterProtocols,this.contentRouting=new qc(this),this.peerRouting=new Kc(this)}get[Wo](){return this.contentRouting}get[jo](){return this.peerRouting}isStarted(){return this.started}start(){this.started=!0}stop(){this.httpQueue.clear(),this.shutDownController.abort(),this.started=!1}async*getProviders(t,e={}){te("getProviders starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Yt([this.shutDownController.signal,n,e.signal]);mt(1/0,n,o);let i=ft(),s=ft();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/providers/${t.toString()}`);this.#r(a,e.filterAddrs,e.filterProtocols);let l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new _t("No matching records found");if(l.status===422)throw new Uo("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Pn("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let f=await l.json();for(let d of f.Providers){let h=this.#t(d);h!=null&&(yield h)}}else for await(let f of qi(Oc(l.body))){let d=this.#t(f);d!=null&&(yield d)}}catch(a){te.error("getProviders errored:",a)}finally{o.clear(),s.resolve(),te("getProviders finished: %c",t)}}async*getPeers(t,e={}){te("getPeers starts: %c",t);let n=AbortSignal.timeout(this.timeout),o=Yt([this.shutDownController.signal,n,e.signal]);mt(1/0,n,o);let i=ft(),s=ft();this.httpQueue.add(async()=>(i.resolve(),s.promise));try{await i.promise;let a=new URL(`${this.clientUrl}routing/v1/peers/${t.toCID().toString()}`);this.#r(a,e.filterAddrs,e.filterProtocols);let l=await fetch(a,{headers:{Accept:"application/x-ndjson"},signal:o});if(l.status===404)throw new _t("No matching records found");if(l.status===422)throw new Uo("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Pn("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let f=await l.json();for(let d of f.Peers){let h=this.#t(d);h!=null&&(yield h)}}else for await(let f of qi(Oc(l.body))){let d=this.#t(f);d!=null&&(yield d)}}catch(a){te.error("getPeers errored:",a)}finally{o.clear(),s.resolve(),te("getPeers finished: %c",t)}}async getIPNS(t,e={}){te("getIPNS starts: %s",t);let n=AbortSignal.timeout(this.timeout),o=Yt([this.shutDownController.signal,n,e.signal]);mt(1/0,n,o);let i=ft(),s=ft();this.httpQueue.add(async()=>(i.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${t}`;try{await i.promise;let l=await fetch(a,{headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:o});if(te("getIPNS GET %s %d",a,l.status),l.status===404)throw new _t("No matching records found");if(l.status===422)throw new Uo("Request does not conform to schema or semantic constraints");if(l.body==null)throw new Pn("GET ipns response had no body");let u=await l.arrayBuffer(),f=new Uint8Array(u,0,u.byteLength);return e.validate!==!1&&await fy(zi(t.multihash),f),or(f)}catch(c){throw te.error("getIPNS GET %s error:",a,c),c}finally{o.clear(),s.resolve(),te("getIPNS finished: %s",t)}}async putIPNS(t,e,n={}){te("putIPNS starts: %c",t);let o=AbortSignal.timeout(this.timeout),i=Yt([this.shutDownController.signal,o,n.signal]);mt(1/0,o,i);let s=ft(),a=ft();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${t}`;try{await s.promise;let l=Ln(e),f=await fetch(c,{method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:i});if(te("putIPNS PUT %s %d",c,f.status),f.status!==200)throw new Pn("PUT ipns response had status other than 200")}catch(l){throw te.error("putIPNS PUT %s error:",c,l.stack),l}finally{i.clear(),a.resolve(),te("putIPNS finished: %c",t)}}#t(t){try{let e=[],n=t.Addrs?.map(Pr)??[];return t.Protocols!=null&&e.push(...t.Protocols),t.Protocol!=null&&(e.push(t.Protocol),delete t.Protocol),{...t,Schema:"peer",ID:mo(t.ID),Addrs:n,Protocols:e}}catch(e){te.error("could not conform record to peer schema",e)}}#r(t,e,n){if(e!=null||this.filterAddrs!=null){let o=e?.join(",")??this.filterAddrs?.join(",")??"";o!==""&&t.searchParams.set("filter-addrs",o)}if(n!=null||this.filterProtocols!=null){let o=n?.join(",")??this.filterProtocols?.join(",")??"";o!==""&&t.searchParams.set("filter-protocols",o)}}};function my(r,t={}){return new Gc(new URL(r),t)}var gy=D("/ipns/");function yy(r){return Z(r.subarray(0,gy.byteLength),gy)}var Nh=class{client;constructor(t){this.client=my(t)}async provide(t,e){}async*findProviders(t,e){yield*zt(this.client.getProviders(t,e),n=>({id:n.ID,multiaddrs:n.Addrs,protocols:n.Protocols}))}async put(t,e,n){if(!yy(t))return;let o=Dr(t),i=L.createV1(114,o),s=or(e);await this.client.putIPNS(i,s,n)}async get(t,e){if(!yy(t))throw new _t("Not found");let n=Dr(t),o=L.createV1(114,n);try{let i=await this.client.getIPNS(o,e);return Ln(i)}catch(i){throw i.name==="BadResponseError"?new _t("Not found"):i}}async findPeer(t,e){let n=await zc(this.client.getPeers(t,e));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new _t("Not found")}async*getClosestPeers(t,e){}};function Ki(r){return new Nh(new URL(r))}var wy="[a-fA-F\\d:]",ln=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${wy})|(?<=${wy})(?=\\s|$))`:"",qe="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",It="[a-fA-F\\d]{1,4}",Wc=`
9
8
  (?:
10
- (?:${_e}:){7}(?:${_e}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
11
- (?:${_e}:){6}(?:${zt}|:${_e}|:)| // 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
12
- (?:${_e}:){5}(?::${zt}|(?::${_e}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
13
- (?:${_e}:){4}(?:(?::${_e}){0,1}:${zt}|(?::${_e}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
14
- (?:${_e}:){3}(?:(?::${_e}){0,2}:${zt}|(?::${_e}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
15
- (?:${_e}:){2}(?:(?::${_e}){0,3}:${zt}|(?::${_e}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
16
- (?:${_e}:){1}(?:(?::${_e}){0,4}:${zt}|(?::${_e}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
17
- (?::(?:(?::${_e}){0,5}:${zt}|(?::${_e}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
9
+ (?:${It}:){7}(?:${It}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
10
+ (?:${It}:){6}(?:${qe}|:${It}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
11
+ (?:${It}:){5}(?::${qe}|(?::${It}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
12
+ (?:${It}:){4}(?:(?::${It}){0,1}:${qe}|(?::${It}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
13
+ (?:${It}:){3}(?:(?::${It}){0,2}:${qe}|(?::${It}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
14
+ (?:${It}:){2}(?:(?::${It}){0,3}:${qe}|(?::${It}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
15
+ (?:${It}:){1}(?:(?::${It}){0,4}:${qe}|(?::${It}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
16
+ (?::(?:(?::${It}){0,5}:${qe}|(?::${It}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
18
17
  )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
19
- `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),nS=new RegExp(`(?:^${zt}$)|(?:^${kc}$)`),oS=new RegExp(`^${zt}$`),iS=new RegExp(`^${kc}$`),zf=r=>r&&r.exact?nS:new RegExp(`(?:${dn(r)}${zt}${dn(r)})|(?:${dn(r)}${kc}${dn(r)})`,"g");zf.v4=r=>r&&r.exact?oS:new RegExp(`${dn(r)}${zt}${dn(r)}`,"g");zf.v6=r=>r&&r.exact?iS:new RegExp(`${dn(r)}${kc}${dn(r)}`,"g");var Kf=zf;function qf(r){let e=(...t)=>r(...t);return Object.defineProperty(e,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),e}function Q0(){return!1}var{toString:sS}=Object.prototype;function Gf(r){return sS.call(r)==="[object RegExp]"}var ey={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function Wf(r,e={}){if(!Gf(r))throw new TypeError("Expected a RegExp instance");let t=Object.keys(ey).map(o=>(typeof e[o]=="boolean"?e[o]:r[o])?ey[o]:"").join(""),n=new RegExp(e.source||r.source,t);return n.lastIndex=typeof e.lastIndex=="number"?e.lastIndex:r.lastIndex,n}function jf(r,e,{timeout:t}={}){try{return qf(()=>Wf(r).test(e),{timeout:t})()}catch(n){if(Q0(n))return!1;throw n}}var aS=15,cS=45,ty={timeout:400};function Yf(r){return r.length>cS?!1:jf(Kf.v6({exact:!0}),r,ty)}function ry(r){return r.length>aS?!1:jf(Kf.v4({exact:!0}),r,ty)}var ny={http:"80",https:"443",ws:"80",wss:"443"},lS=["http","https","ws","wss"];function oy(r,e){e=e??{};let t=e.defaultDnsType??"dns4",{scheme:n,hostname:o,port:i}=uS(r),a="/"+[fS(o,t),hS(i,n),dS(n)].filter(c=>!!c).reduce((c,l)=>c.concat(l),[]).join("/");return Tr(a)}function uS(r){let[e]=r.split(":");lS.includes(e)||(r="http"+r.substring(e.length));let{protocol:t,hostname:n,port:o}=new URL(r);if(o==null||o===""){let i=pS(e);i!=null&&(o=i),i==null&&t==="http:"&&(o="80")}return{scheme:e,hostname:n,port:o}}function fS(r,e){if(!(r==null||r==="")){if(ry(r))return["ip4",r];if(Yf(r))return["ip6",r];if(r[0]==="["){let t=r.substring(1,r.length-1);if(Yf(t))return["ip6",t]}return[e,r]}}function hS(r,e){if(!(r==null||r===""))return e==="udp"?["udp",r]:["tcp",r]}function dS(r){if(r.match(/^tcp$|^udp$/)==null)return[r]}function pS(r){if(!(r==null||r===""||ny[r]==null))return ny[r]}var mS=["https://trustless-gateway.link","https://4everland.io"],gS=2336,yS=Symbol.for("nodejs.util.inspect.custom"),Xf=class{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Be.digest(P(this.url))}[yS](){return`PeerId(${this.url})`}[zo]=!0;toString(){return this.toCID().toString()}toCID(){return z.createV1(gS,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=G(e)),e.toString()===this.toString())}};function wS(r){return r=r.toString(),{id:new Xf(new URL(r)),multiaddrs:[oy(r)]}}var Zf=class{gateways;constructor(e={}){this.gateways=(e.gateways??mS).map(t=>wS(t))}async*findProviders(e,t){yield*this.gateways.toSorted(()=>Math.random()>.5?1:-1).map(n=>({...n,protocols:["transport-ipfs-gateway-http"]}))}};function qi(r={}){return new Zf(r)}var iy=re(De(),1);function Bc(r){return r=r??new Error("Not Found"),(0,iy.default)(r,"ERR_NOT_FOUND")}var sy="SHARDING";function xS(r){return r[Symbol.asyncIterator]!=null}function ES(r){if(xS(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var Jf=ES;function vS(r){return r[Symbol.asyncIterator]!=null}function SS(r,e){return vS(r)?async function*(){yield*(await Jf(r)).sort(e)}():function*(){yield*Jf(r).sort(e)}()}var Tc=SS;var Lr=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:o}of e)await this.put(n,o,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,o){e.push({key:n,value:o})},delete(n){t.push(n)},commit:async n=>{await ur(this.putMany(e,n)),e=[],await ur(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let o=e.prefix;n=xt(n,i=>i.key.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>xt(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>Tc(o,i),n)),e.offset!=null){let o=0,i=e.offset;n=xt(n,()=>o++>=i)}return e.limit!=null&&(n=ds(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let o=e.prefix;n=xt(n,i=>i.toString().startsWith(o))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((o,i)=>xt(o,i),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((o,i)=>Tc(o,i),n)),e.offset!=null){let o=e.offset,i=0;n=xt(n,()=>i++>=o)}return e.limit!=null&&(n=ds(n,e.limit)),n}};var Wi=class extends Lr{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){let t=this.data.get(e.toString());if(t==null)throw Bc();return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(let[e,t]of this.data.entries())yield{key:new xe(e),value:t}}*_allKeys(){for(let e of this.data.keys())yield new xe(e)}};var xD=new xe(sy);var CD=Qe("datastore:core:tiered");async function cy(r={}){let e=r.datastore??new Wi,t=r.blockstore??new Oi,n=new oc({...r,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[Mi()],routers:r.routers??[Ki("https://delegated-ipfs.dev"),qi()]});return r.start!==!1&&await n.start(),n}var th=re(Nc(),1);var rh=40;function nh(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=th.default.decode(r);return e.seek(th.default.decode.bytes),t}function oh(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}var pn={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},ji={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":pn.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(pn.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=ji["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=ji["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:pn.Int,CarV1HeaderOrV2Pragma:r=>{if(pn.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=ji["CarV1HeaderOrV2Pragma > roots (anon)"](r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=ji.Int(r[i]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},Yi={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":pn.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(pn.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=Yi["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let o=e;o<r.length;o++){let i=r[o];if(i=Yi["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:pn.Int,CarV1HeaderOrV2Pragma:r=>{if(pn.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let o=0;o<e.length;o++){let[i,s]=e[o];switch(i){case"roots":{let a=Yi["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=Yi.Int(s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<o;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},ih={toTyped:ji.CarV1HeaderOrV2Pragma,toRepresentation:Yi.CarV1HeaderOrV2Pragma};var yP=Wu();var $S=re(Nc(),1);var vP=[new R(w.map,2),new R(w.string,"version"),new R(w.uint,1),new R(w.string,"roots")],SP=new R(w.tag,42);async function sh(r,e){let t=nh(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),o=Ln(n);if(ih.toTyped(o)===void 0)throw new Error("Invalid CAR header format");if(o.version!==1&&o.version!==2||e!==void 0&&o.version!==e)throw new Error(`Invalid CAR version: ${o.version}${e!==void 0?` (expected ${e})`:""}`);if(o.version===1){if(!Array.isArray(o.roots))throw new Error("Invalid CAR header format");return o}if(o.roots!==void 0)throw new Error("Invalid CAR header format");let i=oh(await r.exactly(rh,!0));r.seek(i.dataOffset-r.pos);let s=await sh(r,1);return Object.assign(s,i)}function Xi(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let o=r.subarray(e,e+t);return n&&(e+=t),o},seek(t){e+=t},get pos(){return e}}}var ah=re(Nc(),1),xy=1;function ch(r){let e=Bi({version:xy,roots:r}),t=ah.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function Ey(r){return{async setRoots(e){let t=ch(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(ah.default.encode(t.bytes.length+n.length))),await r.write(t.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return xy}}}function Cc(){}function vy(){let r=[],e=null,t=Cc,n=!1,o=null,i=Cc,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=Cc,l()}})),e),a={write(l){r.push(l);let f=s();return i(),f},async end(){n=!0;let l=s();i(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&t(),{done:!1,value:l}):n?(t(),{done:!0,value:void 0}):(o||(o=new Promise(f=>{i=()=>(o=null,i=Cc,f(c.next()))})),o)}};return{writer:a,iterator:c}}var Zi=class r{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let t=z.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:t,bytes:e.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(e){e=GS(e);let{encoder:t,iterator:n}=Sy(),o=new r(e,t),i=new Lc(n);return{writer:o,out:i}}static createAppender(){let{encoder:e,iterator:t}=Sy();e.setRoots=()=>Promise.resolve();let n=new r([],e),o=new Lc(t);return{writer:n,out:o}}static async updateRootsInBytes(e,t){let n=Xi(e);await sh(n);let o=ch(t);if(Number(n.pos)!==o.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${o.length} bytes)`);return e.set(o,0),e}},Lc=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function Sy(){let r=vy(),{writer:e,iterator:t}=r;return{encoder:Ey(e),iterator:t}}function GS(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=z.asCID(r);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}let e=[];for(let t of r){let n=z.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var WS=1,lh=class{components;constructor(e,t){this.components=e}async import(e,t){await ur(this.components.blockstore.putMany(Ke(e.blocks(),({cid:n,bytes:o})=>({cid:n,block:o})),t))}async export(e,t,n){let o=fe(),i=Array.isArray(e)?e:[e],s=new at({concurrency:WS});s.on("idle",()=>{o.resolve()}),s.on("error",a=>{s.clear(),o.reject(a)});for(let a of i)s.add(async()=>{await this.#e(a,s,async(c,l)=>{await t.put({cid:c,bytes:l})},n)}).catch(()=>{});try{await o.promise}finally{await t.close()}}async*stream(e,t){let{writer:n,out:o}=Zi.create(e);this.export(e,n,t).catch(()=>{});for await(let i of o)yield i}async#e(e,t,n,o){let i=this.components.dagWalkers[e.code];if(i==null)throw new Error(`No dag walker found for cid codec ${e.code}`);let s=await this.components.blockstore.get(e,o);await n(e,s);for await(let a of i.walk(s))t.add(async()=>{await this.#e(a,t,n,o)})}};function Ay(r,e={}){return new lh(r,e)}var uh=re(Ec(),1);function _y(r,e){let t=e.map((n,o)=>({record:je(n),index:o}));return t.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===He.ValidityType.EOL&&o.record.validityType===He.ValidityType.EOL){let a=uh.default.fromString(n.record.validity).toDate(),c=uh.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 jS=32;async function Iy(r,e,t,n,o={}){if(e===0)throw new Error("recursion limit exceeded");n("query %s for TXT and CNAME records",r);let s=(await t.query(r,{...o,types:[ct.TXT]})).Answer.sort((l,f)=>l.data.localeCompare(f.data));n("found %d TXT records for %s",s.length,r);for(let l of s)try{let f=l.data;if(f.startsWith('"')&&f.endsWith('"')&&(f=f.substring(1,f.length-1)),!f.startsWith("dnslink="))continue;n("%s TXT %s",l.name,f),f=f.replace("dnslink=","");let[,u,p,...h]=f.split("/");if(u==="ipfs")try{return{value:`/ipfs/${z.parse(p)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}else if(u==="ipns"){try{return{value:`/ipns/${Lt(p)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}return await Oc(p,e-1,t,n,o)}else{if(u==="dnslink")return await Oc(p,e-1,t,n,o);n('unknown protocol "%s" in DNSLink record for domain: %s',u,r);continue}}catch(f){n.error("could not parse DNS link record for domain %s, %s",r,l.data,f)}n("no DNSLink records found for %s, falling back to CNAME",r);let c=(await t.query(r,{...o,types:[ct.CNAME]})).Answer.sort((l,f)=>l.data.localeCompare(f.data));n("found %d CNAME records for %s",c.length,r);for(let l of c)try{return await Oc(l.data,e-1,t,n,o)}catch(f){n.error("domain %s cname %s had no DNSLink records",r,l.data,f)}throw new N(`No DNSLink records found for domain: ${r}`,"ERR_DNSLINK_NOT_FOUND")}async function Oc(r,e,t,n,o={}){if(e===0)throw new Error("recursion limit exceeded");r.startsWith("_dnslink.")||(r=`_dnslink.${r}`);try{return await Iy(r,e,t,n,o)}catch(i){if(i.code!=="ENOTFOUND"&&i.code!=="ERR_DNSLINK_NOT_FOUND"&&i.code!=="ENODATA")throw i;return r.startsWith("_dnslink.")?r=r.replace("_dnslink.",""):r=`_dnslink.${r}`,await Iy(r,e,t,n,o)}}async function Ry(r,e,t,n={}){return Oc(r,n.maxRecursiveDepth??jS,e,t,n)}var fh=class{routing;constructor(e){this.routing=e}async put(e,t,n={}){try{await this.routing.put(e,t,n)}catch(o){n.onProgress?.(new V("ipns:routing:helia:error",o))}}async get(e,t={}){try{return await this.routing.get(e,t)}catch(n){t.onProgress?.(new V("ipns:routing:helia:error",n))}throw new Error("Not found")}};function ky(r){return new fh(r)}var Ji;(function(r){let e;r.codec=()=>(e==null&&(e=It((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.key!=null&&t.key.byteLength>0&&(n.uint32(10),n.bytes(t.key)),t.value!=null&&t.value.byteLength>0&&(n.uint32(18),n.bytes(t.value)),t.timeReceived!=null&&t.timeReceived!==""&&(n.uint32(42),n.string(t.timeReceived)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let i={key:rt(0),value:rt(0),timeReceived:""},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{i.key=t.bytes();break}case 2:{i.value=t.bytes();break}case 5:{i.timeReceived=t.string();break}default:{t.skipType(a&7);break}}}return i})),e),r.encode=t=>_t(t,r.codec()),r.decode=(t,n)=>St(t,r.codec(),n)})(Ji||(Ji={}));function By(r){let e=r.getUTCFullYear(),t=String(r.getUTCMonth()+1).padStart(2,"0"),n=String(r.getUTCDate()).padStart(2,"0"),o=String(r.getUTCHours()).padStart(2,"0"),i=String(r.getUTCMinutes()).padStart(2,"0"),s=String(r.getUTCSeconds()).padStart(2,"0"),a=r.getUTCMilliseconds(),c=String(a*1e3*1e3).padStart(9,"0");return`${e}-${t}-${n}T${o}:${i}:${s}.${c}Z`}function Ty(r){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),t=String(r).trim().match(e);if(t==null)throw new Error("Invalid format");let n=parseInt(t[1],10),o=parseInt(t[2],10)-1,i=parseInt(t[3],10),s=parseInt(t[4],10),a=parseInt(t[5],10),c=parseInt(t[6],10),l=parseInt(t[7].slice(0,-6),10);return new Date(Date.UTC(n,o,i,s,a,c,l))}var Or=class r{key;value;timeReceived;constructor(e,t,n){if(!(e instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(t instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=e,this.value=t,this.timeReceived=n}serialize(){return Ji.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:By(this.timeReceived)}}static deserialize(e){let t=Ji.decode(e);return new r(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){let t=Ty(e.timeReceived);if(e.key==null)throw new Error("key missing from deserialized object");if(e.value==null)throw new Error("value missing from deserialized object");return new r(e.key,e.value,t)}};var Dc=globalThis.CustomEvent??Event;async function*On(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered==null?!1:e.ordered,o=new EventTarget,i=[],s=fe(),a=fe(),c=!1,l,f=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(i.length===t&&(s=fe(),await s.promise),f)break;let d={done:!1};i.push(d),m().then(y=>{d.done=!0,d.ok=!0,d.value=y,o.dispatchEvent(new Dc("task-complete"))},y=>{d.done=!0,d.err=y,o.dispatchEvent(new Dc("task-complete"))})}c=!0,o.dispatchEvent(new Dc("task-complete"))}catch(m){l=m,o.dispatchEvent(new Dc("task-complete"))}});function u(){return n?i[0]?.done:!!i.find(m=>m.done)}function*p(){for(;i.length>0&&i[0].done;){let m=i[0];if(i.shift(),m.ok)yield m.value;else throw f=!0,s.resolve(),m.err;s.resolve()}}function*h(){for(;u();)for(let m=0;m<i.length;m++)if(i[m].done){let d=i[m];if(i.splice(m,1),m--,d.ok)yield d.value;else throw f=!0,s.resolve(),d.err;s.resolve()}}for(;;){if(u()||(a=fe(),await a.promise),l!=null)throw l;if(n?yield*p():yield*h(),c&&i.length===0)break}}var Ny;(function(r){r[r.SEND_QUERY=0]="SEND_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADD_PEER=6]="ADD_PEER",r[r.DIAL_PEER=7]="DIAL_PEER"})(Ny||(Ny={}));function Pc(r){return new xe("/dht/record/"+G(r,"base32"),!1)}function Cy(r){return{async put(e,t,n={}){try{let o=Pc(e);try{let s=await r.get(o),a=Or.deserialize(s);if(ne(a.value,t))return}catch(s){if(s.code!=="ERR_NOT_FOUND")throw s}let i=new Or(e,t,new Date);n.onProgress?.(new V("ipns:routing:datastore:put")),await r.put(o,i.serialize(),n)}catch(o){throw n.onProgress?.(new V("ipns:routing:datastore:error",o)),o}},async get(e,t={}){try{let n=Pc(e);t.onProgress?.(new V("ipns:routing:datastore:get"));let o=await r.get(n,t),i=Or.deserialize(o);return{record:i.value,created:i.timeReceived}}catch(n){throw t.onProgress?.(new V("ipns:routing:datastore:error",n)),n}},async has(e,t={}){let n=Pc(e);return r.has(n,t)},async delete(e,t){let n=Pc(e);return r.delete(n,t)}}}var Dr=Qe("helia:ipns"),XS=60*1e3,ph=60*XS,ZS=24*ph,hh=23*ph,JS=BigInt(ph)*1000000n,dh=class{routers;localStore;timeout;dns;log;constructor(e,t=[]){this.routers=[ky(e.routing),...t],this.localStore=Cy(e.datastore),this.dns=e.dns,this.log=e.logger.forComponent("helia:ipns")}async publish(e,t,n={}){try{let o=1n,i=Lo(e);if(await this.localStore.has(i,n)){let{record:c}=await this.localStore.get(i,n);o=je(c).sequence+1n}let s=await K0(e,t,o,n.lifetime??ZS,n),a=Cr(s);return await this.localStore.put(i,a,n),n.offline!==!0&&await Promise.all(this.routers.map(async c=>{await c.put(i,a,n)})),s}catch(o){throw n.onProgress?.(new V("ipns:publish:error",o)),o}}async resolve(e,t={}){let n=Lo(e),o=await this.#n(n,t);return{...await this.#e(o.value,t),record:o}}async resolveDNSLink(e,t={}){let n=await Ry(e,this.dns,this.log,t);return{...await this.#e(n.value,t),answer:n.answer}}republish(e={}){if(this.timeout!=null)throw new Error("Republish is already running");e.signal?.addEventListener("abort",()=>{clearTimeout(this.timeout)});async function t(){let n=Date.now();e.onProgress?.(new V("ipns:republish:start"));let i=Date.now()-n,s=hh-i;s<0&&(s=e.interval??hh),setTimeout(()=>{t().catch(a=>{Dr.error("error republishing",a)})},s)}this.timeout=setTimeout(()=>{t().catch(n=>{Dr.error("error republishing",n)})},e.interval??hh)}async#e(e,t={}){let n=e.split("/");try{let o=n[1];if(o==="ipns"){let{cid:i}=await this.resolve(Lt(n[2]),t),s=n.slice(3).join("/");return{cid:i,path:s}}else if(o==="ipfs"){let i=z.parse(n[2]),s=n.slice(3).join("/");return{cid:i,path:s}}}catch(o){Dr.error("error parsing ipfs path",o)}throw Dr.error("invalid ipfs path %s",e),new Error("Invalid value")}async#n(e,t={}){let n=[];if(await this.localStore.has(e,t))if(Dr("record is present in the cache"),t.nocache!==!0)try{let{record:a,created:c}=await this.localStore.get(e,t);this.log("record retrieved from cache"),await $i(e,a),this.log("record was valid");let l=je(a),f=Number((l.ttl??JS)/1000000n);if(c.getTime()+f>Date.now())return this.log("record TTL was valid"),l;if(t.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),l;this.log("record TTL has been reached, searching routing for updates"),n.push(a)}catch(a){this.log("cached record was invalid",a),await this.localStore.delete(e,t)}else Dr("ignoring local cache due to nocache=true option");if(t.offline===!0)throw new N("Record was not present in the cache or has expired","ERR_NOT_FOUND");Dr("did not have record locally");let i=0;if(await Promise.all(this.routers.map(async a=>{let c;try{c=await a.get(e,{...t,validate:!1})}catch(l){Dr.error("error finding IPNS record",l);return}try{await $i(e,c),n.push(c)}catch(l){i++,Dr.error("error finding IPNS record",l)}})),n.length===0)throw i>0?new N(`${i>1?`${i} records`:"Record"} found for routing key ${i>1?"were":"was"} invalid`,"ERR_RECORDS_FAILED_VALIDATION"):new N("Could not find record for routing key","ERR_NOT_FOUND");let s=n[_y(e,n)];return await this.localStore.put(e,s,t),je(s)}};function Ly(r,{routers:e=[]}={}){return new dh(r,e)}var $c=re(De(),1);function QS(r){return r[Symbol.asyncIterator]!=null}function eA(r){if(QS(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var Oy=eA;var lw=re(De(),1);var Dy=re(De(),1);function Do(r,e,t,n,o,i,s){let a=r,c=o;for(;i.length>0;){let l=i[0];if(l in a){i.shift(),c=`${c}/${l}`;let f=z.asCID(a[l]);if(f!=null)return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}},next:{cid:f,name:l,path:c,toResolve:i}};a=a[l]}else throw(0,Dy.default)(new Error(`No property named ${l} found in node ${t}`),"ERR_NO_PROP")}return{entry:{type:"object",name:n,path:o,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}}}}var tA=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=Ln(c);return Do(l,c,r,e,t,n,i)},Py=tA;var rA=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=Xa(c);return Do(l,c,r,e,t,n,i)},Uy=rA;var Fy=re(De(),1);function nA(r,e,t,n){let o=BigInt(r.length),i=BigInt(e+o);return t>=i||n<e?new Uint8Array(0):(n>=e&&n<i&&(r=r.subarray(0,Number(n-e))),t>=e&&t<i&&(r=r.subarray(Number(t-e))),r)}var Dn=nA;var Qi=re(De(),1),oA=(r,e=0,t=r)=>{let n=BigInt(r),o=BigInt(e??0),i=BigInt(t);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw(0,Qi.default)(new Error("Offset must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(o>n)throw(0,Qi.default)(new Error("Offset must be less than the file size"),"ERR_INVALID_PARAMS");if(i<0n)throw(0,Qi.default)(new Error("Length must be greater than or equal to 0"),"ERR_INVALID_PARAMS");if(i>n)throw(0,Qi.default)(new Error("Length must be less than the file size"),"ERR_INVALID_PARAMS");return{start:o,end:i}},Po=oA;var iA=r=>{async function*e(t={}){let{start:n,end:o}=Po(r.length,t.offset,t.length),i=Dn(r,0n,n,o);t.onProgress?.(new V("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},sA=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw(0,Fy.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=Xe(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:iA(c.digest),depth:i,size:BigInt(c.digest.length),node:c.digest}}},My=sA;var aA=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=cd(c);return Do(l,c,r,e,t,n,i)},Vy=aA;var Hy=re(De(),1);var cA=r=>{async function*e(t={}){let{start:n,end:o}=Po(r.length,t.offset,t.length),i=Dn(r,0n,n,o);t.onProgress?.(new V("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return e},lA=async(r,e,t,n,o,i,s,a)=>{if(n.length>0)throw(0,Hy.default)(new Error(`No link named ${t} found in raw node ${r}`),"ERR_NOT_FOUND");let c=await s.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:cA(c),depth:i,size:BigInt(c.length),node:c}}},$y=lA;var ts=re(De(),1);var mh=re(De(),1);var Kt;(function(r){let e;(function(o){o.Raw="Raw",o.Directory="Directory",o.File="File",o.Metadata="Metadata",o.Symlink="Symlink",o.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(o){o[o.Raw=0]="Raw",o[o.Directory=1]="Directory",o[o.File=2]="File",o[o.Metadata=3]="Metadata",o[o.Symlink=4]="Symlink",o[o.HAMTShard=5]="HAMTShard"})(t||(t={})),function(o){o.codec=()=>vn(t)}(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=It((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),r.DataType.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),o.filesize!=null&&(i.uint32(24),i.uint64(o.filesize)),o.blocksizes!=null)for(let a of o.blocksizes)i.uint32(32),i.uint64(a);o.hashType!=null&&(i.uint32(40),i.uint64(o.hashType)),o.fanout!=null&&(i.uint32(48),i.uint64(o.fanout)),o.mode!=null&&(i.uint32(56),i.uint32(o.mode)),o.mtime!=null&&(i.uint32(66),Uc.codec().encode(o.mtime,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i)=>{let s={blocksizes:[]},a=i==null?o.len:o.pos+i;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:s.Type=r.DataType.codec().decode(o);break;case 2:s.Data=o.bytes();break;case 3:s.filesize=o.uint64();break;case 4:s.blocksizes.push(o.uint64());break;case 5:s.hashType=o.uint64();break;case 6:s.fanout=o.uint64();break;case 7:s.mode=o.uint32();break;case 8:s.mtime=Uc.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>_t(o,r.codec()),r.decode=o=>St(o,r.codec())})(Kt||(Kt={}));var Uc;(function(r){let e;r.codec=()=>(e==null&&(e=It((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Seconds!=null&&(n.uint32(8),n.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(t.FractionalNanoseconds)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.Seconds=t.int64();break;case 2:o.FractionalNanoseconds=t.fixed32();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>_t(t,r.codec()),r.decode=t=>St(t,r.codec())})(Uc||(Uc={}));var zy;(function(r){let e;r.codec=()=>(e==null&&(e=It((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.MimeType!=null&&(n.uint32(10),n.string(t.MimeType)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:o.MimeType=t.string();break;default:t.skipType(s&7);break}}return o})),e),r.encode=t=>_t(t,r.codec()),r.decode=t=>St(t,r.codec())})(zy||(zy={}));var Ky={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},uA=["directory","hamt-sharded-directory"],qy=parseInt("0644",8),Gy=parseInt("0755",8),ar=class r{static unmarshal(e){let t=Kt.decode(e),n=new r({type:Ky[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:t,data:n,blockSizes:o,hashType:i,fanout:s,mtime:a,mode:c}=e;if(t!=null&&!Object.values(Ky).includes(t))throw(0,mh.default)(new Error("Type: "+t+" is not valid"),"ERR_INVALID_TYPE");this.type=t??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?Gy:qy:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return uA.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=Kt.DataType.Raw;break;case"directory":e=Kt.DataType.Directory;break;case"file":e=Kt.DataType.File;break;case"metadata":e=Kt.DataType.Metadata;break;case"symlink":e=Kt.DataType.Symlink;break;case"hamt-sharded-directory":e=Kt.DataType.HAMTShard;break;default:throw(0,mh.default)(new Error(`Type: ${e} is not valid`),"ERR_INVALID_TYPE")}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===qy&&!this.isDirectory()&&(n=void 0),n===Gy&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Kt.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var Fc=re(Nu(),1);function fA(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var bU=xn({name:"murmur3-32",code:35,encode:r=>fA(Fc.default.x86.hash32(r))}),Wy=xn({name:"murmur3-128",code:34,encode:r=>zn.fromHex(Fc.default.x64.hash128(r))}),xU=xn({name:"murmur3-x64-64",code:34,encode:r=>zn.fromHex(Fc.default.x64.hash128(r)).subarray(0,8)});var es=re(De(),1);var Zy=re(Xy(),1);var Pn=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new Zy.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof r?o.push(i.serialize(e,t)):o.push(e(i,s))),o),n))}async asyncTransform(e,t){return Jy(this,e,t)}toJSON(){return this.serialize(gA,yA)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?P(e):e),n=await t.take(this._options.bits),o=this._children.get(n);return o instanceof r?o._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:o}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let o=await n._findPlace(t.existingChild.hash);return o.bucket._putAt(o,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(mA);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function mA(r){return!!r}function gA(r,e){return r.key}function yA(r){return r}async function Jy(r,e,t){let n=[];for(let o of r._children.compactArray())if(o instanceof Pn)await Jy(o,e,t);else{let i=await e(o);n.push({bitField:r._children.bitField(),children:i})}return t(n)}var wA=[255,254,252,248,240,224,192,128],bA=[1,3,7,15,31,63,127,255],Mc=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,t),a=xA(o,i-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function xA(r,e,t){let n=EA(e,t);return(r&n)>>>e}function EA(r,e){return wA[r]&bA[Math.min(e+r-1,7)]}function Qy(r){function e(t){return t instanceof Vc?t:new Vc(t,r)}return e}var Vc=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),t),s=o.take(i);n=(n<<i)+s,t-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),t);n.untake(o),t-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?ue([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new Mc(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function ew(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:Qy(r.hashFn)};return new Pn(e)}var vA=async function(r){return(await Wy.encode(r)).slice(0,8).reverse()},SA=async(r,e,t)=>{let n=(e.tableSize()-1).toString(16).length;await Promise.all(r.map(async o=>{if(o.Name==null)throw new Error("Unexpected Link without a Name");if(o.Name.length===n){let i=parseInt(o.Name,16);e._putObjectAt(i,new Pn({hash:t._options.hash,bits:t._options.bits},e,i));return}await t.put(o.Name.substring(2),!0)}))},tw=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),AA=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},rw=async(r,e,t,n,o)=>{if(n==null){if(r.Data==null)throw(0,es.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let u;try{u=ar.unmarshal(r.Data)}catch(h){throw(0,es.default)(h,"ERR_NOT_UNIXFS")}if(u.type!=="hamt-sharded-directory")throw(0,es.default)(new Error("not a HAMT"),"ERR_NOT_UNIXFS");if(u.fanout==null)throw(0,es.default)(new Error("missing fanout"),"ERR_NOT_UNIXFS");let p=ew({hashFn:vA,bits:Math.log2(Number(u.fanout))});n={rootBucket:p,hamtDepth:1,lastBucket:p}}let i=(n.lastBucket.tableSize()-1).toString(16).length;await SA(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),a=tw(s.pos,i),c=AA(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=tw(n.lastBucket._posAtParent,i));let l=r.Links.find(u=>{if(u.Name==null)return!1;let p=u.Name.substring(0,i),h=u.Name.substring(i);return!(p!==a||h!==""&&h!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(i)===e)return l.Hash;n.hamtDepth++;let f=await t.get(l.Hash,o);return r=ir(f),rw(r,e,t,n,o)},nw=rw;var _A=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=c.offset??0,f=c.length??e.Links.length,u=e.Links.slice(l,f);c.onProgress?.(new V("unixfs:exporter:walk:directory",{cid:r})),yield*jt(u,p=>Ke(p,h=>async()=>{let m=h.Name??"",d=`${n}/${m}`;return(await o(h.Hash,m,d,[],i+1,s,c)).entry}),p=>On(p,{ordered:!0,concurrency:c.blockReadConcurrency}),p=>xt(p,h=>h!=null))}return a},ow=_A;var Un=re(De(),1);async function iw(r,e,t,n,o,i,s){if(e instanceof Uint8Array){let l=Dn(e,n,o,i);t.push(l);return}if(e.Data==null)throw(0,Un.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let a;try{a=ar.unmarshal(e.Data)}catch(l){throw(0,Un.default)(l,"ERR_NOT_UNIXFS")}if(a.data!=null){let l=a.data,f=Dn(l,n,o,i);t.push(f),n+=BigInt(f.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw(0,Un.default)(new Error("Inconsistent block sizes and dag links"),"ERR_NOT_UNIXFS");for(let l=0;l<e.Links.length;l++){let f=e.Links[l],u=n,p=u+a.blockSizes[l];if((o>=u&&o<p||i>=u&&i<=p||o<u&&i>p)&&c.push({link:f,blockStart:n}),n=p,n>i)break}await jt(c,l=>Ke(l,f=>async()=>{let u=await r.get(f.link.Hash,s);return{...f,block:u}}),l=>On(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:f,block:u,blockStart:p}of l){let h;switch(f.Hash.code){case $t:h=ir(u);break;case ht:h=u;break;default:t.end((0,Un.default)(new Error(`Unsupported codec: ${f.Hash.code}`),"ERR_NOT_UNIXFS"));return}let m=new at({concurrency:1});m.on("error",d=>{t.end(d)}),m.add(async()=>{s.onProgress?.(new V("unixfs:exporter:walk:file",{cid:f.Hash})),await iw(r,h,t,p,o,i,s)}),await m.onIdle()}}),n>=i&&t.end()}var IA=(r,e,t,n,o,i,s)=>{async function*a(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:f,end:u}=Po(l,c.offset,c.length);if(u===0n)return;let p=0n,h=u-f,m=Gt();c.onProgress?.(new V("unixfs:exporter:walk:file",{cid:r})),iw(s,e,m,0n,f,u,c).catch(d=>{m.end(d)});for await(let d of m)if(d!=null){if(p+=BigInt(d.byteLength),p>h)throw m.end(),(0,Un.default)(new Error("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect"),"ERR_OVER_READ");p===h&&m.end(),c.onProgress?.(new V("unixfs:exporter:progress:unixfs:file",{bytesRead:p,totalBytes:h,fileSize:l})),yield d}if(p<h)throw(0,Un.default)(new Error("Traversed entire DAG but did not read enough bytes"),"ERR_UNDER_READ")}return a},gh=IA;var Hc=re(De(),1);var RA=(r,e,t,n,o,i,s)=>{function a(c={}){return c.onProgress?.(new V("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),sw(e,n,o,i,s,c)}return a};async function*sw(r,e,t,n,o,i){let s=r.Links;if(r.Data==null)throw(0,Hc.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");let a;try{a=ar.unmarshal(r.Data)}catch(f){throw(0,Hc.default)(f,"ERR_NOT_UNIXFS")}if(a.fanout==null)throw(0,Hc.default)(new Error("missing fanout"),"ERR_NOT_UNIXFS");let c=(a.fanout-1n).toString(16).length,l=jt(s,f=>Ke(f,u=>async()=>{let p=u.Name!=null?u.Name.substring(c):null;if(p!=null&&p!==""){let h=await t(u.Hash,p,`${e}/${p}`,[],n+1,o,i);return{entries:h.entry==null?[]:[h.entry]}}else{let h=await o.get(u.Hash,i);return r=ir(h),i.onProgress?.(new V("unixfs:exporter:walk:hamt-sharded-directory",{cid:u.Hash})),{entries:sw(r,e,t,n,o,i)}}}),f=>On(f,{ordered:!0,concurrency:i.blockReadConcurrency}));for await(let{entries:f}of l)yield*f}var aw=RA;var kA=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,BA={raw:gh,file:gh,directory:ow,"hamt-sharded-directory":aw,metadata:(r,e,t,n,o,i,s)=>()=>[],symlink:(r,e,t,n,o,i,s)=>()=>[]},TA=async(r,e,t,n,o,i,s,a)=>{let c=await s.get(r,a),l=ir(c),f,u;if(e==null&&(e=r.toString()),l.Data==null)throw(0,ts.default)(new Error("no data in PBNode"),"ERR_NOT_UNIXFS");try{f=ar.unmarshal(l.Data)}catch(h){throw(0,ts.default)(h,"ERR_NOT_UNIXFS")}if(t==null&&(t=e),n.length>0){let h;if(f?.type==="hamt-sharded-directory"?h=await nw(l,n[0],s):h=kA(l,n[0]),h==null)throw(0,ts.default)(new Error("file does not exist"),"ERR_NOT_FOUND");let m=n.shift(),d=`${t}/${m}`;u={cid:h,toResolve:n,name:m??"",path:d}}let p=BA[f.type](r,l,f,t,o,i,s);if(p==null)throw(0,ts.default)(new Error("could not find content exporter"),"ERR_NOT_FOUND");return f.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:p,unixfs:f,depth:i,node:l,size:f.fileSize()},next:u}:{entry:{type:"file",name:e,path:t,cid:r,content:p,unixfs:f,depth:i,node:l,size:f.fileSize()},next:u}},cw=TA;var NA={[$t]:cw,[ht]:$y,[un]:Py,[hn]:Uy,[Be.code]:My,[Kr]:Vy},uw=async(r,e,t,n,o,i,s)=>{let a=NA[r.code];if(a==null)throw(0,lw.default)(new Error(`No resolver for code ${r.code}`),"ERR_NO_RESOLVER");return a(r,e,t,n,uw,o,i,s)},fw=uw;var CA=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),LA=r=>{if(r instanceof Uint8Array)return{cid:z.decode(r),toResolve:[]};let e=z.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=CA(r);return{cid:z.parse(t[0]),toResolve:t.slice(1)}}throw(0,$c.default)(new Error(`Unknown path type ${r}`),"ERR_BAD_PATH")};async function*yh(r,e,t={}){let{cid:n,toResolve:o}=LA(r),i=n.toString(),s=i,a=o.length;for(;;){let c=await fw(n,i,s,o,a,e,t);if(c.entry==null&&c.next==null)throw(0,$c.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");if(c.entry!=null&&(yield c.entry),c.next==null)return;o=c.next.toResolve,n=c.next.cid,i=c.next.name,s=c.next.path}}async function Uo(r,e,t={}){let n=await Oy(yh(r,e,t));if(n==null)throw(0,$c.default)(new Error(`Could not resolve ${r}`),"ERR_NOT_FOUND");return n}async function*hw(r,e,t={}){let n=await Uo(r,e,t);if(n==null)return;if(yield n,n.type==="directory")for await(let i of o(n,t))yield i;async function*o(i,s){for await(let a of i.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*o(a,s))}}function dw(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function zc(r,e={}){let t=dw(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(o){try{let{value:i,done:s}=await t.next();if(this._cancelled)return;if(s===!0){o.close();return}o.enqueue(i)}catch(i){o.error(i)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}var Fo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,mw=new Set,wh=typeof process=="object"&&process?process:{},gw=(r,e,t,n)=>{typeof wh.emitWarning=="function"?wh.emitWarning(r,e,t,n):console.error(`[${t}] ${e}: ${r}`)},Kc=globalThis.AbortController,pw=globalThis.AbortSignal;if(typeof Kc>"u"){pw=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,o){this._onabort.push(o)}},Kc=class{constructor(){e()}signal=new pw;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let o of this.signal._onabort)o(n);this.signal.onabort?.(n)}}};let r=wh.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=!1,gw("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var OA=r=>!mw.has(r),NF=Symbol("type"),mn=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),yw=r=>mn(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?Mo:null:null,Mo=class extends Array{constructor(e){super(e),this.fill(0)}},bh=class r{heap;length;static#e=!1;static create(e){let t=yw(e);if(!t)return[];r.#e=!0;let n=new r(e,t);return r.#e=!1,n}constructor(e,t){if(!r.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},qc=class r{#e;#n;#s;#u;#g;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#f;#c;#r;#t;#i;#m;#l;#h;#b;#d;#x;#E;#y;#w;#A;#p;static unsafeExposeInternals(e){return{starts:e.#E,ttls:e.#y,sizes:e.#x,keyMap:e.#c,keyList:e.#r,valList:e.#t,next:e.#i,prev:e.#m,get head(){return e.#l},get tail(){return e.#h},free:e.#b,isBackgroundFetch:t=>e.#o(t),backgroundFetch:(t,n,o,i)=>e.#L(t,n,o,i),moveToTail:t=>e.#T(t),indexes:t=>e.#_(t),rindexes:t=>e.#I(t),isStale:t=>e.#S(t)}}get max(){return this.#e}get maxSize(){return this.#n}get calculatedSize(){return this.#f}get size(){return this.#a}get fetchMethod(){return this.#g}get dispose(){return this.#s}get disposeAfter(){return this.#u}constructor(e){let{max:t=0,ttl:n,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:c,dispose:l,disposeAfter:f,noDisposeOnSet:u,noUpdateTTL:p,maxSize:h=0,maxEntrySize:m=0,sizeCalculation:d,fetchMethod:y,noDeleteOnFetchRejection:g,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:x,allowStaleOnFetchAbort:E,ignoreFetchAbort:v}=e;if(t!==0&&!mn(t))throw new TypeError("max option must be a nonnegative integer");let _=t?yw(t):Array;if(!_)throw new Error("invalid max value: "+t);if(this.#e=t,this.#n=h,this.maxEntrySize=m||this.#n,this.sizeCalculation=d,this.sizeCalculation){if(!this.#n&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#g=y,this.#A=!!y,this.#c=new Map,this.#r=new Array(t).fill(void 0),this.#t=new Array(t).fill(void 0),this.#i=new _(t),this.#m=new _(t),this.#l=0,this.#h=0,this.#b=bh.create(t),this.#a=0,this.#f=0,typeof l=="function"&&(this.#s=l),typeof f=="function"?(this.#u=f,this.#d=[]):(this.#u=void 0,this.#d=void 0),this.#w=!!this.#s,this.#p=!!this.#u,this.noDisposeOnSet=!!u,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!g,this.allowStaleOnFetchRejection=!!x,this.allowStaleOnFetchAbort=!!E,this.ignoreFetchAbort=!!v,this.maxEntrySize!==0){if(this.#n!==0&&!mn(this.#n))throw new TypeError("maxSize must be a positive integer if specified");if(!mn(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=mn(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!mn(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#R()}if(this.#e===0&&this.ttl===0&&this.#n===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#n){let S="LRU_CACHE_UNBOUNDED";OA(S)&&(mw.add(S),gw("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",S,r))}}getRemainingTTL(e){return this.#c.has(e)?1/0:0}#R(){let e=new Mo(this.#e),t=new Mo(this.#e);this.#y=e,this.#E=t,this.#O=(i,s,a=Fo.now())=>{if(t[i]=s!==0?a:0,e[i]=s,s!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#S(i)&&this.delete(this.#r[i])},s+1);c.unref&&c.unref()}},this.#k=i=>{t[i]=e[i]!==0?Fo.now():0},this.#v=(i,s)=>{if(e[s]){let a=e[s],c=t[s];if(!a||!c)return;i.ttl=a,i.start=c,i.now=n||o();let l=i.now-c;i.remainingTTL=a-l}};let n=0,o=()=>{let i=Fo.now();if(this.ttlResolution>0){n=i;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return i};this.getRemainingTTL=i=>{let s=this.#c.get(i);if(s===void 0)return 0;let a=e[s],c=t[s];if(!a||!c)return 1/0;let l=(n||o())-c;return a-l},this.#S=i=>{let s=t[i],a=e[i];return!!a&&!!s&&(n||o())-s>a}}#k=()=>{};#v=()=>{};#O=()=>{};#S=()=>!1;#F(){let e=new Mo(this.#e);this.#f=0,this.#x=e,this.#B=t=>{this.#f-=e[t],e[t]=0},this.#D=(t,n,o,i)=>{if(this.#o(n))return 0;if(!mn(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(n,t),!mn(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#N=(t,n,o)=>{if(e[t]=n,this.#n){let i=this.#n-e[t];for(;this.#f>i;)this.#C(!0)}this.#f+=e[t],o&&(o.entrySize=n,o.totalCalculatedSize=this.#f)}}#B=e=>{};#N=(e,t,n)=>{};#D=(e,t,n,o)=>{if(n||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#_({allowStale:e=this.allowStale}={}){if(this.#a)for(let t=this.#h;!(!this.#P(t)||((e||!this.#S(t))&&(yield t),t===this.#l));)t=this.#m[t]}*#I({allowStale:e=this.allowStale}={}){if(this.#a)for(let t=this.#l;!(!this.#P(t)||((e||!this.#S(t))&&(yield t),t===this.#h));)t=this.#i[t]}#P(e){return e!==void 0&&this.#c.get(this.#r[e])===e}*entries(){for(let e of this.#_())this.#t[e]!==void 0&&this.#r[e]!==void 0&&!this.#o(this.#t[e])&&(yield[this.#r[e],this.#t[e]])}*rentries(){for(let e of this.#I())this.#t[e]!==void 0&&this.#r[e]!==void 0&&!this.#o(this.#t[e])&&(yield[this.#r[e],this.#t[e]])}*keys(){for(let e of this.#_()){let t=this.#r[e];t!==void 0&&!this.#o(this.#t[e])&&(yield t)}}*rkeys(){for(let e of this.#I()){let t=this.#r[e];t!==void 0&&!this.#o(this.#t[e])&&(yield t)}}*values(){for(let e of this.#_())this.#t[e]!==void 0&&!this.#o(this.#t[e])&&(yield this.#t[e])}*rvalues(){for(let e of this.#I())this.#t[e]!==void 0&&!this.#o(this.#t[e])&&(yield this.#t[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let n of this.#_()){let o=this.#t[n],i=this.#o(o)?o.__staleWhileFetching:o;if(i!==void 0&&e(i,this.#r[n],this))return this.get(this.#r[n],t)}}forEach(e,t=this){for(let n of this.#_()){let o=this.#t[n],i=this.#o(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#r[n],this)}}rforEach(e,t=this){for(let n of this.#I()){let o=this.#t[n],i=this.#o(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#r[n],this)}}purgeStale(){let e=!1;for(let t of this.#I({allowStale:!0}))this.#S(t)&&(this.delete(this.#r[t]),e=!0);return e}info(e){let t=this.#c.get(e);if(t===void 0)return;let n=this.#t[t],o=this.#o(n)?n.__staleWhileFetching:n;if(o===void 0)return;let i={value:o};if(this.#y&&this.#E){let s=this.#y[t],a=this.#E[t];if(s&&a){let c=s-(Fo.now()-a);i.ttl=c,i.start=Date.now()}}return this.#x&&(i.size=this.#x[t]),i}dump(){let e=[];for(let t of this.#_({allowStale:!0})){let n=this.#r[t],o=this.#t[t],i=this.#o(o)?o.__staleWhileFetching:o;if(i===void 0||n===void 0)continue;let s={value:i};if(this.#y&&this.#E){s.ttl=this.#y[t];let a=Fo.now()-this.#E[t];s.start=Math.floor(Date.now()-a)}this.#x&&(s.size=this.#x[t]),e.unshift([n,s])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let o=Date.now()-n.start;n.start=Fo.now()-o}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=n,{noUpdateTTL:l=this.noUpdateTTL}=n,f=this.#D(e,t,n.size||0,a);if(this.maxEntrySize&&f>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.delete(e),this;let u=this.#a===0?void 0:this.#c.get(e);if(u===void 0)u=this.#a===0?this.#h:this.#b.length!==0?this.#b.pop():this.#a===this.#e?this.#C(!1):this.#a,this.#r[u]=e,this.#t[u]=t,this.#c.set(e,u),this.#i[this.#h]=u,this.#m[u]=this.#h,this.#h=u,this.#a++,this.#N(u,f,c),c&&(c.set="add"),l=!1;else{this.#T(u);let p=this.#t[u];if(t!==p){if(this.#A&&this.#o(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:h}=p;h!==void 0&&!s&&(this.#w&&this.#s?.(h,e,"set"),this.#p&&this.#d?.push([h,e,"set"]))}else s||(this.#w&&this.#s?.(p,e,"set"),this.#p&&this.#d?.push([p,e,"set"]));if(this.#B(u),this.#N(u,f,c),this.#t[u]=t,c){c.set="replace";let h=p&&this.#o(p)?p.__staleWhileFetching:p;h!==void 0&&(c.oldValue=h)}}else c&&(c.set="update")}if(o!==0&&!this.#y&&this.#R(),this.#y&&(l||this.#O(u,o,i),c&&this.#v(c,u)),!s&&this.#p&&this.#d){let p=this.#d,h;for(;h=p?.shift();)this.#u?.(...h)}return this}pop(){try{for(;this.#a;){let e=this.#t[this.#l];if(this.#C(!0),this.#o(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#p&&this.#d){let e=this.#d,t;for(;t=e?.shift();)this.#u?.(...t)}}}#C(e){let t=this.#l,n=this.#r[t],o=this.#t[t];return this.#A&&this.#o(o)?o.__abortController.abort(new Error("evicted")):(this.#w||this.#p)&&(this.#w&&this.#s?.(o,n,"evict"),this.#p&&this.#d?.push([o,n,"evict"])),this.#B(t),e&&(this.#r[t]=void 0,this.#t[t]=void 0,this.#b.push(t)),this.#a===1?(this.#l=this.#h=0,this.#b.length=0):this.#l=this.#i[t],this.#c.delete(n),this.#a--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:o}=t,i=this.#c.get(e);if(i!==void 0){let s=this.#t[i];if(this.#o(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#S(i))o&&(o.has="stale",this.#v(o,i));else return n&&this.#k(i),o&&(o.has="hit",this.#v(o,i)),!0}else o&&(o.has="miss");return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,o=this.#c.get(e);if(o===void 0||!n&&this.#S(o))return;let i=this.#t[o];return this.#o(i)?i.__staleWhileFetching:i}#L(e,t,n,o){let i=t===void 0?void 0:this.#t[t];if(this.#o(i))return i;let s=new Kc,{signal:a}=n;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let c={signal:s.signal,options:n,context:o},l=(d,y=!1)=>{let{aborted:g}=s.signal,b=n.ignoreFetchAbort&&d!==void 0;if(n.status&&(g&&!y?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,b&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),g&&!b&&!y)return u(s.signal.reason);let x=h;return this.#t[t]===h&&(d===void 0?x.__staleWhileFetching?this.#t[t]=x.__staleWhileFetching:this.delete(e):(n.status&&(n.status.fetchUpdated=!0),this.set(e,d,c.options))),d},f=d=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=d),u(d)),u=d=>{let{aborted:y}=s.signal,g=y&&n.allowStaleOnFetchAbort,b=g||n.allowStaleOnFetchRejection,x=b||n.noDeleteOnFetchRejection,E=h;if(this.#t[t]===h&&(!x||E.__staleWhileFetching===void 0?this.delete(e):g||(this.#t[t]=E.__staleWhileFetching)),b)return n.status&&E.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),E.__staleWhileFetching;if(E.__returned===E)throw d},p=(d,y)=>{let g=this.#g?.(e,i,c);g&&g instanceof Promise&&g.then(b=>d(b===void 0?void 0:b),y),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(d(void 0),n.allowStaleOnFetchAbort&&(d=b=>l(b,!0)))})};n.status&&(n.status.fetchDispatched=!0);let h=new Promise(p).then(l,f),m=Object.assign(h,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,m,{...c.options,status:void 0}),t=this.#c.get(e)):this.#t[t]=m,m}#o(e){if(!this.#A)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof Kc}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:f=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:d,forceRefresh:y=!1,status:g,signal:b}=t;if(!this.#A)return g&&(g.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:g});let x={allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:a,size:c,sizeCalculation:l,noUpdateTTL:f,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:m,ignoreFetchAbort:h,status:g,signal:b},E=this.#c.get(e);if(E===void 0){g&&(g.fetch="miss");let v=this.#L(e,E,x,d);return v.__returned=v}else{let v=this.#t[E];if(this.#o(v)){let U=n&&v.__staleWhileFetching!==void 0;return g&&(g.fetch="inflight",U&&(g.returnedStale=!0)),U?v.__staleWhileFetching:v.__returned=v}let _=this.#S(E);if(!y&&!_)return g&&(g.fetch="hit"),this.#T(E),o&&this.#k(E),g&&this.#v(g,E),v;let S=this.#L(e,E,x,d),L=S.__staleWhileFetching!==void 0&&n;return g&&(g.fetch=_?"stale":"refresh",L&&_&&(g.returnedStale=!0)),L?S.__staleWhileFetching:S.__returned=S}}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=t,a=this.#c.get(e);if(a!==void 0){let c=this.#t[a],l=this.#o(c);return s&&this.#v(s,a),this.#S(a)?(s&&(s.get="stale"),l?(s&&n&&c.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?c.__staleWhileFetching:void 0):(i||this.delete(e),s&&n&&(s.returnedStale=!0),n?c:void 0)):(s&&(s.get="hit"),l?c.__staleWhileFetching:(this.#T(a),o&&this.#k(a),c))}else s&&(s.get="miss")}#U(e,t){this.#m[t]=e,this.#i[e]=t}#T(e){e!==this.#h&&(e===this.#l?this.#l=this.#i[e]:this.#U(this.#m[e],this.#i[e]),this.#U(this.#h,e),this.#h=e)}delete(e){let t=!1;if(this.#a!==0){let n=this.#c.get(e);if(n!==void 0)if(t=!0,this.#a===1)this.clear();else{this.#B(n);let o=this.#t[n];if(this.#o(o)?o.__abortController.abort(new Error("deleted")):(this.#w||this.#p)&&(this.#w&&this.#s?.(o,e,"delete"),this.#p&&this.#d?.push([o,e,"delete"])),this.#c.delete(e),this.#r[n]=void 0,this.#t[n]=void 0,n===this.#h)this.#h=this.#m[n];else if(n===this.#l)this.#l=this.#i[n];else{let i=this.#m[n];this.#i[i]=this.#i[n];let s=this.#i[n];this.#m[s]=this.#m[n]}this.#a--,this.#b.push(n)}}if(this.#p&&this.#d?.length){let n=this.#d,o;for(;o=n?.shift();)this.#u?.(...o)}return t}clear(){for(let e of this.#I({allowStale:!0})){let t=this.#t[e];if(this.#o(t))t.__abortController.abort(new Error("deleted"));else{let n=this.#r[e];this.#w&&this.#s?.(t,n,"delete"),this.#p&&this.#d?.push([t,n,"delete"])}}if(this.#c.clear(),this.#t.fill(void 0),this.#r.fill(void 0),this.#y&&this.#E&&(this.#y.fill(0),this.#E.fill(0)),this.#x&&this.#x.fill(0),this.#l=0,this.#h=0,this.#b.length=0,this.#f=0,this.#a=0,this.#p&&this.#d){let e=this.#d,t;for(;t=e?.shift();)this.#u?.(...t)}}};function ww(r,e){if(r==null)return;if(r instanceof Headers)return r.get(e)??void 0;if(Array.isArray(r))return r.find(([o])=>o.toLowerCase()===e.toLowerCase())?.[1];let t=Object.keys(r).find(n=>n.toLowerCase()===e.toLowerCase());if(t!=null)return r[t]}function bw(r,e,t){if((r??0)>(e??1/0))throw new Error("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(e??0)>=(t??1/0))throw new Error("Invalid range: Range-end index is greater than or equal to the size of the file.");if(r==null&&(e??0)>(t??1/0))throw new Error("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new Error("Invalid range: Range-start index cannot be negative.");if(r!=null&&e!=null)return{byteSize:e-r+1,start:r,end:e};if(r==null&&e!=null)return t==null?{end:e}:e===t?{byteSize:t,start:0,end:t-1}:{byteSize:e,start:t-e,end:t-1};if(r!=null&&e==null){if(t==null)return{start:r};let n=t-1;return{byteSize:t-r,start:r,end:n}}return{byteSize:t,start:0,end:t!=null?t-1:0}}function xw({ttl:r,protocol:e,response:t}){let n;e==="ipfs"?n="public, max-age=29030400, immutable":r==null?n="public, max-age=300":n=`public, max-age=${r}`,t.headers.set("cache-control",n)}function Ew({byteStart:r,byteEnd:e,byteSize:t}){let n=t??"*";if((e??0)>=(t??1/0))throw new Error("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(t??1/0))throw new Error("Invalid range: Range-start index is greater than or equal to the size of the file.");if(r!=null&&e==null)return t==null?`bytes */${n}`:`bytes ${r}-${t-1}/${t}`;if(r==null&&e!=null){if(t==null)return`bytes */${n}`;let o=t-1;return`bytes ${o-e+1}-${o}/${t}`}return r==null&&e==null?`bytes */${n}`:`bytes ${r}-${e}/${n}`}function xh(r,e){e!=null&&r.headers.set("X-Ipfs-Roots",e.map(t=>t.toV1().toString()).join(","))}function DA(r){return typeof r=="string"?r.length:r instanceof ArrayBuffer||r instanceof Uint8Array?r.byteLength:r instanceof Blob?r.size:(r instanceof ReadableStream,null)}function PA(r){let e=r.match(/^bytes=(?<start>\d+)?-(?<end>\d+)?$/);if(e?.groups==null)throw new Error("Invalid range request");let{start:t,end:n}=e.groups;return{start:t,end:n}}var rs=class{headers;isRangeRequest;_fileSize;_body=null;rangeRequestHeader;log;requestRangeStart;requestRangeEnd;byteStart;byteEnd;byteSize;constructor(e,t){if(this.headers=t,this.log=e.forComponent("helia:verified-fetch:byte-range-context"),this.rangeRequestHeader=ww(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:o}=PA(this.rangeRequestHeader);this.requestRangeStart=n!=null?parseInt(n):null,this.requestRangeEnd=o!=null?parseInt(o):null}catch(n){this.log.error("error parsing range request header: %o",n),this.requestRangeStart=null,this.requestRangeEnd=null}this.setOffsetDetails()}else this.log.trace("no range request detected"),this.isRangeRequest=!1,this.requestRangeStart=null,this.requestRangeEnd=null}setBody(e){this._body=e,this.setFileSize(this._fileSize??DA(e)),this.log.trace("set request body with fileSize %o",this._fileSize)}getBody(){let e=this._body;if(e==null)return this.log.trace("body is null"),e;if(!this.isRangeRequest||!this.isValidRangeRequest)return this.log.trace("returning body unmodified for non-range, or invalid range, request"),e;let t=this.byteStart,n=this.byteEnd,o=this.byteSize;return t!=null||n!=null?(this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",t,n,o),e instanceof ReadableStream?e:this.getSlicedBody(e)):(this.log.error("returning unmodified body for valid range request"),e)}getSlicedBody(e){let t=this.byteStart??0,n=this.byteEnd==null?void 0:this.byteEnd+1;return this.log.trace("returning body with offset %o and length %o",t,n),e.slice(t,n)}setFileSize(e){this._fileSize=e!=null?Number(e):null,this.log.trace("set _fileSize to %o",this._fileSize),this.setOffsetDetails()}getFileSize(){return this._fileSize}isValidByteStart(){return!(this.byteStart!=null&&(this.byteStart<0||this._fileSize!=null&&this.byteStart>=this._fileSize||this.byteEnd!=null&&this.byteStart>this.byteEnd))}isValidByteEnd(){return!(this.byteEnd!=null&&(this.byteEnd<0||this._fileSize!=null&&this.byteEnd>=this._fileSize||this.byteStart!=null&&this.byteEnd<this.byteStart))}get isValidRangeRequest(){if(!this.isRangeRequest)return!1;if(this.requestRangeStart==null&&this.requestRangeEnd==null)return this.log.trace("invalid range request, range request values not provided"),!1;if(!this.isValidByteStart())return this.log.trace("invalid range request, byteStart is less than 0 or greater than fileSize"),!1;if(!this.isValidByteEnd())return this.log.trace("invalid range request, byteEnd is less than 0 or greater than fileSize"),!1;if(this.requestRangeEnd!=null&&this.requestRangeStart!=null){if(this.requestRangeStart>this.requestRangeEnd)return this.log.trace("invalid range request, start is greater than end"),!1;if(this.requestRangeStart<0)return this.log.trace("invalid range request, start is less than 0"),!1;if(this.requestRangeEnd<0)return this.log.trace("invalid range request, end is less than 0"),!1}return this.byteEnd==null&&this.byteStart==null&&this.byteSize==null?(this.log.trace("invalid range request, could not calculate byteStart, byteEnd, or byteSize"),!1):!0}get offset(){return this.byteStart??0}get length(){return this.byteEnd!=null&&this.byteStart!=null&&this.byteStart===this.byteEnd?1:this.byteEnd!=null?this.byteEnd+1:this.byteSize!=null?this.byteSize-1:void 0}setOffsetDetails(){if(this.requestRangeStart==null&&this.requestRangeEnd==null){this.log.trace("requestRangeStart and requestRangeEnd are null");return}try{let{start:e,end:t,byteSize:n}=bw(this.requestRangeStart??void 0,this.requestRangeEnd??void 0,this._fileSize??void 0);this.log.trace("set byteStart to %o, byteEnd to %o, byteSize to %o",e,t,n),this.byteStart=e,this.byteEnd=t,this.byteSize=n}catch(e){this.log.error("error setting offset details: %o",e),this.byteStart=void 0,this.byteEnd=void 0,this.byteSize=void 0}}get contentRangeHeaderValue(){if(!this.isValidRangeRequest)throw this.log.error("cannot get contentRangeHeaderValue for invalid range request"),new Error("Invalid range request");return Ew({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};function vw(r){let e=tt(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(Ni(e))}function Sw(r){let e=UA(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function UA(r){return r.replace(/[^\x00-\x7F]/g,"_")}function Aw({cid:r,reqFormat:e,weak:t,rangeStart:n,rangeEnd:o}){let i=t===!0?"W/":"",s=e==null?"":`.${e}`;return(n!=null||o!=null)&&(s+=`.${n??"0"}-${o??"N"}`),`${i}"${r.toString()}${s}"`}var FA={[un]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[hn]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Kr]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[$t]:["application/octet-stream","application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car","application/x-tar"],[ht]:["application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.dag-json","application/vnd.ipld.car","application/x-tar"]};function _w(r,e){let t=FA[r.code];if(e!=null)return MA(e,t)}function MA(r,e){let t=r.split(",").map(n=>{let o=n.trim().split(";");return{mimeType:`${o[0]}`.trim(),weight:VA(o[1])}}).sort((n,o)=>n.weight===o.weight?0:n.weight>o.weight?-1:1).map(n=>n.mimeType);for(let n of t)for(let o of e)if(n.includes(o)||n==="*/*"||n.startsWith("*/")&&o.split("/")[1]===n.split("/")[1]||n.endsWith("/*")&&o.split("/")[0]===n.split("/")[0])return o}function VA(r){if(r!=null&&(r=r.trim()),r==null||!r.startsWith("q="))return 1;let e=parseFloat(r.replace("q=",""));return isNaN(e)?0:e}var Gc={raw:"application/vnd.ipld.raw",car:"application/vnd.ipld.car","dag-json":"application/vnd.ipld.dag-json","dag-cbor":"application/vnd.ipld.dag-cbor",json:"application/json",cbor:"application/cbor","ipns-record":"application/vnd.ipfs.ipns-record",tar:"application/x-tar"};function Iw(r){if(r!=null)return Gc[r]}function Eh(r){let e=r.get("accept");return!!(e!=null&&Object.values(Gc).includes(e))}function vh(r){let e=r?.format;return!!(e!=null&&Object.keys(Gc).includes(e))}function Rw({query:r,headers:e}){return Eh(e)||vh(r)}function kw({query:r,headers:e,logger:t}){let n=t.forComponent("helia:verified-fetch:get-resolved-accept-header"),o=new Headers(e),i=o.get("accept")??void 0;if(i!=null&&n('incoming accept header "%s"',i),!Rw({query:r,headers:o}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",i),i;let s=Iw(r?.format);r?.format!=null&&n('incoming query format "%s", mapped to %s',r.format,s);let a=i;return!Eh(o)&&vh(r)&&(n("accept header not recognized, but query format provided, setting accept header to %s",s),a=s),n('resolved accept header to "%s"',a),a}async function Bw(r,e,t,n){let o=t.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),i=r[Symbol.asyncIterator](),{value:s,done:a}=await i.next();if(a===!0)throw o.error("no content found for path",e),new Error("No content found");return{stream:new ReadableStream({async start(l){n?.onProgress?.(new V("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:f,done:u}=await i.next();if(n?.signal?.aborted===!0){l.error(new qt(n.signal.reason??"signal aborted by user")),l.close();return}if(u===!0){f!=null&&(n?.onProgress?.(new V("verified-fetch:request:progress:chunk")),l.enqueue(f)),l.close();return}n?.onProgress?.(new V("verified-fetch:request:progress:chunk")),l.enqueue(f)}}),firstChunk:s}}var c7=P("ustar\0","binary"),l7=P("ustar ","binary"),u7=P(" \0","binary");var Ow=re(Nw(),1);function $A(r){return r[Symbol.asyncIterator]!=null}function zA(r){if($A(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=ue([n,o],n.length+o.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return ue(e,t)}var Cw=zA;var KA="0000000000000000000",qA="7777777777777777777",GA=48,WA=P("ustar\0","binary"),jA=P("00","binary"),YA=parseInt("7777",8),XA=257,ZA=263,JA=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},QA=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},gn=function(r,e){let t=r.toString(8);return t.length>e?P(qA.slice(0,e)+" "):P(KA.slice(0,e-t.length)+t+" ")},Sh=function(r){let e=P(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function Lw(r){let e="";r.name!=null&&(e+=Sh(" path="+r.name+`
20
- `)),r.linkname!=null&&(e+=Sh(" linkpath="+r.linkname+`
21
- `));let t=r.pax;if(t!=null)for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e+=Sh(" "+n+"="+t[n]+`
22
- `));return P(e)}function Wc(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),P(t).byteLength!==t.length)return null;for(;P(t).byteLength>100;){let o=t.indexOf("/");if(o===-1)return null;n+=n!==""?"/"+t.slice(0,o):t.slice(0,o),t=t.slice(o+1)}return P(t).byteLength>100||P(n).byteLength>155||r.linkname!=null&&P(r.linkname).byteLength>100?null:(e.set(P(t),0),e.set(gn(r.mode&YA,6),100),e.set(gn(r.uid,6),108),e.set(gn(r.gid,6),116),e.set(gn(r.size,11),124),e.set(gn(r.mtime.getTime()/1e3|0,11),136),e[156]=GA+JA(r.type),r.linkname!=null&&e.set(P(r.linkname),157),e.set(WA,XA),e.set(jA,ZA),r.uname!=null&&e.set(P(r.uname),265),r.gname!=null&&e.set(P(r.gname),297),e.set(gn(r.devmajor??0,6),329),e.set(gn(r.devminor??0,6),337),n!=null&&e.set(P(n),345),e.set(gn(QA(e),6),148),e)}var{S_IFMT:t_,S_IFBLK:r_,S_IFCHR:n_,S_IFDIR:o_,S_IFIFO:i_,S_IFLNK:s_}=Ow.default,a_=parseInt("755",8),c_=parseInt("644",8),Dw=new Uint8Array(1024);function l_(r=0){switch(r&t_){case r_:return"block-device";case n_:return"character-device";case o_:return"directory";case i_:return"fifo";case s_:return"symlink";default:return"file"}}function _h(r){return r&=511,r!==0?Dw.subarray(0,512-r):new Uint8Array(0)}function Ah(r){if(r.pax==null){let e=Wc(r);if(e!=null)return e}return u_(r)}function u_(r){let e=Lw(r),t={name:"PaxHeader",mode:r.mode,uid:r.uid,gid:r.gid,size:e.length,mtime:r.mtime,type:"pax-header",linkname:r.linkname,uname:r.uname,gname:r.gname,devmajor:r.devmajor,devminor:r.devminor};return new fr(Wc(t)??new Uint8Array(0),e,_h(e.length),Wc({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function jc(){return async function*(r){for await(let{header:e,body:t}of r){let n={...e,size:e.type==="symlink"?0:e.size??0,type:e.type??l_(e.mode),mode:e.mode??(e.type==="directory"?a_:c_),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=P(t)),t instanceof Uint8Array||Wt(t)){n.size=t.length,yield Ah(n),yield Wt(t)?t.subarray():t,yield _h(n.size);continue}if(n.type==="symlink"&&n.linkname==null){if(t==null)throw new Error("type was symlink but no linkname or body specified");n.linkname=G(await Cw(t)),yield Ah(n);continue}if(yield Ah(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let o=0;for await(let i of t??[])o+=i.length,yield Wt(i)?i.subarray():i;if(o!==n.size)throw new Error(`size mismatch, wrote ${o} of ${n.size} bytes`);yield _h(n.size)}yield Dw}}var f_=["file","raw","directory"];function h_(r){let e,t;return(r.type==="file"||r.type==="directory")&&(e=r.unixfs.mode,t=r.unixfs.mtime!=null?new Date(Number(r.unixfs.mtime.secs*1000n)):void 0),{name:r.path,mode:e,mtime:t,size:Number(r.size),type:r.type==="directory"?"directory":"file"}}function Pw(r){if(!f_.includes(r.type))throw new N("Not a UnixFS node","ERR_NOT_UNIXFS");let e={header:h_(r)};return(r.type==="file"||r.type==="raw")&&(e.body=r.content()),e}async function*Uw(r,e,t){let n=await Uo(r,e,t);if(n.type==="file"||n.type==="raw"){yield*jt([Pw(n)],jc());return}if(n.type==="directory"){yield*jt(hw(r,e,t),o=>Ke(o,i=>Pw(i)),jc());return}throw new N("Not a UnixFS node","ERR_NOT_UNIXFS")}var Fw=re(Fu(),1),Yc=class{lru;constructor(e){this.lru=(0,Fw.default)(e)}get(e){let t=this.lru.get(e);if(t!=null){if(t.expire!=null&&t.expire<Date.now()){this.lru.remove(e);return}return t.value}}set(e,t,n){this.lru.set(e,{value:t,expire:Date.now()+n})}has(e){return this.get(e)!=null}remove(e){this.lru.remove(e)}clear(){this.lru.clear()}};var Mw=new Yc(1e3),d_=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,p_=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,m_=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,g_=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function y_(r){let e=r?.protocol;if(e==null)return!1;let t=r?.cidOrPeerIdOrDnsLink;if(t==null)return!1;let n=r?.path,o=r?.queryString;return["ipns","ipfs"].includes(e)&&typeof t=="string"&&(n==null||typeof n=="string")&&(o==null||typeof o=="string")}function ns(r){for(let e of[g_,d_,m_,p_]){let t=r.match(e);if(y_(t?.groups))return t.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function w_(r){if(r==null)return;let e=r.answer?.TTL,t=r.record?.ttl,n=t!=null?Number(t/BigInt(1e9)):void 0;return e??n}var b_=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function x_(r){return b_.test(r)&&r.includes("-")&&!r.includes(".")}function E_(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function Vw({urlString:r,ipns:e,logger:t},n){let o=t.forComponent("helia:verified-fetch:parse-url-string"),{protocol:i,cidOrPeerIdOrDnsLink:s,path:a,queryString:c}=ns(r),l,f,u=[],p;if(i==="ipfs")try{l=z.parse(s)}catch(d){o.error(d),u.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(p=Mw.get(s),p!=null)l=p.cid,f=p.path,o.trace("resolved %s to %c from cache",s,l);else{o.trace("Attempting to resolve PeerId for %s",s);let d=null;try{d=Lt(s),p=await e.resolve(d,n),l=p?.cid,f=p?.path,o.trace("resolved %s to %c",s,l)}catch(y){n?.signal?.throwIfAborted(),d==null?(o.error('could not parse PeerId string "%s"',s,y),u.push(new TypeError(`Could not parse PeerId in ipns url "${s}", ${y.message}`))):(o.error("could not resolve PeerId %c",d,y),u.push(new TypeError(`Could not resolve PeerId "${s}", ${y.message}`)))}if(l==null){let y=s;x_(s)&&(y=E_(s),o.trace('decoded dnslink from "%s" to "%s"',s,y)),o.trace("Attempting to resolve DNSLink for %s",y);try{p=await e.resolveDNSLink(y,n),l=p?.cid,f=p?.path,o.trace("resolved %s to %c",y,l)}catch(g){n?.signal?.throwIfAborted(),o.error('could not resolve DnsLink for "%s"',s,g),u.push(g)}}}if(l==null)throw u.length===1?u[0]:new AggregateError(u,`Invalid resource. Cannot determine CID from URL "${r}"`);let h=w_(p);p!=null&&(h=h??60*2,o.trace("caching %s resolved to %s with TTL: %s",s,l,h),Mw.set(s,p,h*1e3));let m={};if(c!=null&&c.length>0){let d=c.split("&");for(let y of d){let[g,b]=y.split("=");m[g]=decodeURIComponent(b)}m.download!=null&&(m.download=m.download==="true"),m.filename!=null&&(m.filename=m.filename.toString())}return{protocol:i,cid:l,path:v_(f,a??""),query:m,ttl:h,ipfsPath:`/${i}/${s}${a!=null&&a!==""?`/${a}`:""}`}}function v_(r,e){let t="";return r!=null&&(t+=r),e.length>0&&(t=`${t.length>0?`${t}/`:t}${e}`),t=t.replace(/\/(\/)+/g,"/"),t.startsWith("/")&&(t=t.substring(1)),t.split("/").map(decodeURIComponent).join("/")}function Ih(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function Pr(r,e){Ih(r,"type",e)}function Ur(r,e){Ih(r,"url",e)}function Hw(r){Ih(r,"redirected",!0)}function Fn(r,e,t){let n=new Response(e,{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&Hw(n),Pr(n,"basic"),Ur(n,r),n.headers.set("Accept-Ranges","bytes"),n}function Zc(r,e,t){let n=new Response(e,{...t??{},status:502,statusText:"Bad Gateway"});return Pr(n,"basic"),Ur(n,r),n}function Jc(r,e,t){let n=new Response(e,{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),Pr(n,"basic"),Ur(n,r),n}function Vo(r,e,t){let n=new Response(e,{...t??{},status:406,statusText:"Not Acceptable"});return Pr(n,"basic"),Ur(n,r),n}function Qc(r,e,t){let n=new Response(e,{...t??{},status:404,statusText:"Not Found"});return Pr(n,"basic"),Ur(n,r),n}function el(r,e,t){e instanceof Error&&(e=e.message);let n=new Response(e,{...t??{},status:400,statusText:"Bad Request"});return Pr(n,"basic"),Ur(n,r),n}function os(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return Pr(n,"basic"),Ur(n,r),n}function Rh(r,e,{byteRangeContext:t,log:n},o){if(!t.isRangeRequest)return Fn(r,e,o);if(!t.isValidRangeRequest)return Xc(r,e,o);let i;try{i=new Response(e,{...o??{},status:206,statusText:"Partial Content",headers:{...o?.headers??{},"content-range":t.contentRangeHeaderValue}})}catch(s){return n?.error("failed to create range response",s),Xc(r,e,o)}return o?.redirected===!0&&Hw(i),Pr(i,"basic"),Ur(i,r),i.headers.set("Accept-Ranges","bytes"),i}function Xc(r,e,t){let n=new Response(e,{...t??{},status:416,statusText:"Requested Range Not Satisfiable"});return Pr(n,"basic"),Ur(n,r),n}function $w(r){return r.match(/\.[a-zA-Z0-9]{1,4}$/)!=null||r.endsWith("/")?r:`${r}/`}async function zw({resource:r,options:e,logger:t,cid:n,fetch:o=globalThis.fetch}){let i=t.forComponent("helia:verified-fetch:get-redirect-response");if(typeof r!="string"||e==null||["ipfs://","ipns://"].some(f=>r.startsWith(f)))return null;let s=new Headers(e?.headers),a=s.get("x-forwarded-host"),c=s.get("host");if(s.get("x-forwarded-for")==null&&a==null&&c==null)return i.trace("no redirect info found in headers"),null;i.trace("checking for redirect info");try{let f=ns(r),u=new URL(r),p=a??u.host,h=new URL(u);if(f.protocol==="ipfs"&&n.version===0?h.host=`${n.toV1()}.ipfs.${p}`:h.host=`${f.cidOrPeerIdOrDnsLink}.${f.protocol}.${p}`,c?.includes(f.protocol)===!0&&h.host.includes(c))return i.trace("request was for a subdomain already, not setting location header"),null;if(c!=null&&!h.host.includes(c))return i.trace("host header is not the same as the subdomain url host, not setting location header"),null;if(u.host===h.host)return i.trace("req url is the same as the subdomain url, not setting location header"),null;h.pathname=$w(u.pathname.replace(`/${f.cidOrPeerIdOrDnsLink}`,"").replace(`/${f.protocol}`,"")),i.trace("subdomain url %s",h.href);let m=new URL(u,`${u.protocol}//${p}`);m.pathname=$w(u.pathname),i.trace("path url %s",m.href);try{let d=await o(h,{method:"HEAD"});if(d.ok)return i("subdomain supported, redirecting to subdomain"),os(r.toString(),h.href);throw i("subdomain not supported, subdomain failed with status %s %s",d.status,d.statusText),new Error("subdomain not supported")}catch(d){return i("subdomain not supported",d),m.href===u.href?(i("path url is the same as the request url, not setting location header"),null):os(r.toString(),m.href)}}catch(f){i.error("error setting location header for x-forwarded-host",f)}return null}async function Kw(r,{ipns:e,logger:t},n){if(typeof r=="string")return Vw({urlString:r,ipns:e,logger:t},n);let o=z.asCID(r);if(o!=null)return{cid:o,protocol:"ipfs",path:"",query:{},ipfsPath:`/ipfs/${o.toString()}`,ttl:29030400};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function qw(r){let e=z.asCID(r);if(e!=null)return`ipfs://${e}`;try{return`ipfs://${z.parse(r.toString())}`}catch{}let{protocol:t,cidOrPeerIdOrDnsLink:n}=ns(r.toString());return`${t}://${n}`}async function S_(r,e,t){let n=[],o;for await(let i of yh(e,r,t))n.push(i.cid),o=i;if(o==null)throw new N("No terminal element found","ERR_NO_TERMINAL_ELEMENT");return{ipfsRoots:n,terminalElement:o}}function Gw(r){return r.type==="object"}async function kh({cid:r,path:e,resource:t,options:n,blockstore:o,log:i}){try{return await S_(o,`${r.toString()}/${e}`,n)}catch(s){return n?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(s.code)?Qc(t):(i.error("error walking path %s",e,s),Zc(t,"Error walking path"))}}var A_=100,__=60*1e3;function I_(r){if(r==null)return;let e;return r?.signal===null?e=void 0:e=r?.signal,{...r,signal:e}}var R_=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function k_({headers:r,accept:e}){let n=(e??new Headers(r).get("accept")??"").split(",").map(o=>o.split(";")[0]).map(o=>o.trim());for(let o of n){if(o==="*/*")return;if(R_.includes(o??""))return o}}var tl=class{helia;ipns;log;contentTypeParser;blockstoreSessions;constructor({helia:e,ipns:t},n){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipns=t??Ly(e),this.contentTypeParser=n?.contentTypeParser,this.blockstoreSessions=new qc({max:n?.sessionCacheSize??A_,ttl:n?.sessionTTLms??__,dispose:o=>{o.close()}}),this.log.trace("created VerifiedFetch instance")}getBlockstore(e,t,n,o){let i=qw(t);if(!n)return this.helia.blockstore;let s=this.blockstoreSessions.get(i);return s==null&&(s=this.helia.blockstore.createSession(e,o),this.blockstoreSessions.set(i,s)),s}async handleIPNSRecord({resource:e,cid:t,path:n,options:o}){if(n!==""||!e.startsWith("ipns://"))return el(e,"Invalid IPNS name");let i;try{i=Lt(e.replace("ipns://",""))}catch(u){return this.log.error("could not parse peer id from IPNS url %s",e),el(e,u)}let s=ue([P("/ipns/"),i.toBytes()]),a=new xe("/dht/record/"+G(s,"base32"),!1),c=await this.helia.datastore.get(a,o),l=Or.deserialize(c),f=Fn(e,l.value);return f.headers.set("content-type","application/vnd.ipfs.ipns-record"),f}async handleCar({resource:e,cid:t,session:n,options:o}){let i=this.getBlockstore(t,e,n,o),s=Ay({blockstore:i,dagWalkers:this.helia.dagWalkers}),a=zc(s.stream(t,o)),c=Fn(e,a);return c.headers.set("content-type","application/vnd.ipld.car; version=1"),c}async handleTar({resource:e,cid:t,path:n,session:o,options:i}){if(t.code!==$t&&t.code!==ht)return Vo("only UnixFS data can be returned in a TAR file");let s=this.getBlockstore(t,e,o,i),a=zc(Uw(`/ipfs/${t}/${n}`,s,i)),c=Fn(e,a);return c.headers.set("content-type","application/x-tar"),c}async handleJson({resource:e,cid:t,path:n,accept:o,session:i,options:s}){this.log.trace("fetching %c/%s",t,n);let c=await this.getBlockstore(t,e,i,s).get(t,s),l;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let u=Xa(c);l=Bi(u)}catch(u){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",u),Vo(e)}else l=c;let f=Fn(e,l);return f.headers.set("content-type",o??"application/json"),f}async handleDagCbor({resource:e,cid:t,path:n,accept:o,session:i,options:s}){this.log.trace("fetching %c/%s",t,n);let a,c=this.getBlockstore(t,e,i,s),l=await kh({cid:t,path:n,resource:e,options:s,blockstore:c,log:this.log});if(l instanceof Response)return l;let f=l.ipfsRoots;if(Gw(l.terminalElement))a=l.terminalElement;else return this.log.error("terminal element is not a dag-cbor node"),Jc(e,"Terminal element is not a dag-cbor node");let u=a.node,p;if(o==="application/octet-stream"||o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")p=u;else if(o==="application/vnd.ipld.dag-json")try{let m=Ln(u);p=Og(m)}catch(m){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",m),Vo(e)}else try{p=vw(u)}catch(m){if(o==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',m),Vo(e);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",m),p=u}let h=Fn(e,p);return o==null&&(o=p instanceof Uint8Array?"application/octet-stream":"application/json"),h.headers.set("content-type",o),xh(h,f),h}async handleDagPb({cid:e,path:t,resource:n,session:o,options:i}){let s=!1,a=new rs(this.helia.logger,i?.headers),c=this.getBlockstore(e,n,o,i),l=await kh({cid:e,path:t,resource:n,options:i,blockstore:c,log:this.log});if(l instanceof Response)return l;let f=l.ipfsRoots,u=l.terminalElement,p=u.cid;if(u?.type==="directory"){let d=u.cid;if(t===""?!n.toString().endsWith("/"):!t.endsWith("/")){if(i?.redirect==="error")throw this.log('could not redirect to %s/ as redirect option was set to "error"',n),new TypeError("Failed to fetch");if(i?.redirect==="manual")return this.log("returning 301 permanent redirect to %s/",n),os(n,`${n}/`);n=`${n}/`,s=!0}let g="index.html";try{this.log.trace("found directory at %c/%s, looking for index.html",e,t);let b=await Uo(`/ipfs/${d}/${g}`,this.helia.blockstore,{signal:i?.signal,onProgress:i?.onProgress});this.log.trace("found root file at %c/%s with cid %c",d,g,b.cid),t=g,p=b.cid}catch(b){return i?.signal?.throwIfAborted(),this.log("error loading path %c/%s",d,g,b),Jc("Unable to find index.html for directory at given path. Support for directories with implicit root is not implemented")}finally{i?.onProgress?.(new V("verified-fetch:request:end",{cid:d,path:g}))}}a.isRangeRequest&&a.isValidRangeRequest&&u.type==="file"&&(a.setFileSize(u.unixfs.fileSize()),this.log.trace("fileSize for rangeRequest %d",a.getFileSize()));let h=a.offset,m=a.length;this.log.trace("calling exporter for %c/%s with offset=%o & length=%o",p,t,h,m);try{let y=(await Uo(p,this.helia.blockstore,{signal:i?.signal,onProgress:i?.onProgress})).content({signal:i?.signal,onProgress:i?.onProgress,offset:h,length:m});this.log("got async iterator for %c/%s",e,t);let{stream:g,firstChunk:b}=await Bw(y,t??"",this.helia.logger,{onProgress:i?.onProgress,signal:i?.signal});a.setBody(g);let x=Rh(n,a.getBody(),{byteRangeContext:a,log:this.log},{redirected:s});return await this.setContentType(b,t,x),xh(x,f),x}catch(d){return i?.signal?.throwIfAborted(),this.log.error("error streaming %c/%s",e,t,d),a.isRangeRequest&&d.code==="ERR_INVALID_PARAMS"?Xc(n):Zc(n.toString(),"Unable to stream content")}}async handleRaw({resource:e,cid:t,path:n,session:o,options:i,accept:s}){if(n!=="")return this.log.trace("404-ing raw codec request for %c/%s",t,n),Qc(e,"Raw codec does not support paths");let a=new rs(this.helia.logger,i?.headers),l=await this.getBlockstore(t,e,o,i).get(t,i);a.setBody(l);let f=Rh(e,a.getBody(),{byteRangeContext:a,log:this.log},{redirected:!1});return await this.setContentType(l,n,f,k_({headers:i?.headers,accept:s})),f}async setContentType(e,t,n,o="application/octet-stream"){let i;if(this.contentTypeParser!=null)try{let s=t.split("/").pop()?.trim();s=s===""?void 0:s;let a=this.contentTypeParser(e,s);if(B_(a)){let c=await a;c!=null&&(i=c)}else a!=null&&(i=a)}catch(s){this.log.error("error parsing content type",s)}this.log.trace('setting content type to "%s"',i??o),n.headers.set("content-type",i??o)}codecHandlers={[$t]:this.handleDagPb,[hn]:this.handleJson,[Kr]:this.handleJson,[un]:this.handleDagCbor,[ht]:this.handleRaw,[Be.code]:this.handleRaw};async fetch(e,t){this.log("fetch %s",e);let n=I_(t);n?.onProgress?.(new V("verified-fetch:request:start",{resource:e}));let o,i,s,a,c,l;try{let g=await Kw(e,{ipns:this.ipns,logger:this.helia.logger},n);o=g.cid,i=g.path,s=g.query,a=g.ttl,c=g.protocol,l=g.ipfsPath}catch(g){return n?.signal?.throwIfAborted(),this.log.error("error parsing resource %s",e,g),el(e.toString(),g)}n?.onProgress?.(new V("verified-fetch:request:resolve",{cid:o,path:i}));let f=kw({query:s,headers:n?.headers,logger:this.helia.logger}),u=_w(o,f);if(this.log("output type %s",u),f!=null&&u==null)return Vo(e.toString());let p,h,m=await zw({resource:e,options:n,logger:this.helia.logger,cid:o});if(m!=null)return m;let d={resource:e.toString(),cid:o,path:i,accept:u,session:n?.session??!0,options:n};if(u==="application/vnd.ipfs.ipns-record")h="ipns-record",p=await this.handleIPNSRecord(d);else if(u==="application/vnd.ipld.car")h="car",s.download=!0,s.filename=s.filename??`${o.toString()}.car`,p=await this.handleCar(d);else if(u==="application/vnd.ipld.raw")h="raw",s.download=!0,s.filename=s.filename??`${o.toString()}.bin`,p=await this.handleRaw(d);else if(u==="application/x-tar")h="tar",s.download=!0,s.filename=s.filename??`${o.toString()}.tar`,p=await this.handleTar(d);else{this.log.trace('finding handler for cid code "%s" and output type "%s"',o.code,u);let g=this.codecHandlers[o.code];if(g==null)return Jc(`Support for codec with code ${o.code} is not yet implemented. Please open an issue at https://github.com/ipfs/helia-verified-fetch/issues/new`);this.log.trace('calling handler "%s"',g.name),p=await g.call(this,d)}p.headers.set("etag",Aw({cid:o,reqFormat:h,weak:!1})),xw({response:p,ttl:a,protocol:c}),p.headers.set("X-Ipfs-Path",l);let y;return s.download===!0&&(y="attachment"),s.filename!=null&&(y==null&&(y="inline"),y=`${y}; ${Sw(s.filename)}`),y!=null&&p.headers.set("Content-Disposition",y),n?.onProgress?.(new V("verified-fetch:request:end",{cid:o,path:i})),p}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};function B_(r){return r?.then!=null}var is,rl=async function(e,t){return is==null&&(is=await Bh()),is(e,t)};rl.start=async function(){await is?.start()};rl.stop=async function(){await is?.stop()};async function Bh(r,e){T_(r)||(r=await cy({blockBrokers:[Mi({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})],routers:[...(r?.routers??["https://delegated-ipfs.dev"]).map(o=>Ki(o)),qi({gateways:r?.gateways??[]})],dns:N_(r?.dnsResolvers)}));let t=new tl({helia:r},e);async function n(o,i){return t.fetch(o,i)}return n.stop=t.stop.bind(t),n.start=t.start.bind(t),n}function T_(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function N_(r){if(r!=null)return Array.isArray(r)?Ei({resolvers:{".":r}}):Ei({resolvers:r})}return sb(C_);})();
18
+ `.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),MS=new RegExp(`(?:^${qe}$)|(?:^${Wc}$)`),VS=new RegExp(`^${qe}$`),HS=new RegExp(`^${Wc}$`),Lh=r=>r&&r.exact?MS:new RegExp(`(?:${ln(r)}${qe}${ln(r)})|(?:${ln(r)}${Wc}${ln(r)})`,"g");Lh.v4=r=>r&&r.exact?VS:new RegExp(`${ln(r)}${qe}${ln(r)}`,"g");Lh.v6=r=>r&&r.exact?HS:new RegExp(`${ln(r)}${Wc}${ln(r)}`,"g");var Ph=Lh;function Dh(r){let t=(...e)=>r(...e);return Object.defineProperty(t,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),t}function by(){return!1}var{toString:$S}=Object.prototype;function Oh(r){return $S.call(r)==="[object RegExp]"}var xy={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function Uh(r,t={}){if(!Oh(r))throw new TypeError("Expected a RegExp instance");let e=Object.keys(xy).map(o=>(typeof t[o]=="boolean"?t[o]:r[o])?xy[o]:"").join(""),n=new RegExp(t.source||r.source,e);return n.lastIndex=typeof t.lastIndex=="number"?t.lastIndex:r.lastIndex,n}function Fh(r,t,{timeout:e}={}){try{return Dh(()=>Uh(r).test(t),{timeout:e})()}catch(n){if(by(n))return!1;throw n}}var zS=15,qS=45,Ey={timeout:400};function Mh(r){return r.length>qS?!1:Fh(Ph.v6({exact:!0}),r,Ey)}function vy(r){return r.length>zS?!1:Fh(Ph.v4({exact:!0}),r,Ey)}var Sy={http:"80",https:"443",ws:"80",wss:"443"},KS=["http","https","ws","wss"];function Ay(r,t){t=t??{};let e=t.defaultDnsType??"dns4",{scheme:n,hostname:o,port:i}=GS(r),a="/"+[WS(o,e),jS(i,n),YS(n)].filter(c=>!!c).reduce((c,l)=>c.concat(l),[]).join("/");return Pr(a)}function GS(r){let[t]=r.split(":");KS.includes(t)||(r="http"+r.substring(t.length));let{protocol:e,hostname:n,port:o}=new URL(r);if(o==null||o===""){let i=XS(t);i!=null&&(o=i),i==null&&e==="http:"&&(o="80")}return{scheme:t,hostname:n,port:o}}function WS(r,t){if(!(r==null||r==="")){if(vy(r))return["ip4",r];if(Mh(r))return["ip6",r];if(r[0]==="["){let e=r.substring(1,r.length-1);if(Mh(e))return["ip6",e]}return[t,r]}}function jS(r,t){if(!(r==null||r===""))return t==="udp"?["udp",r]:["tcp",r]}function YS(r){if(r.match(/^tcp$|^udp$/)==null)return[r]}function XS(r){if(!(r==null||r===""||Sy[r]==null))return Sy[r]}var ZS=["https://trustless-gateway.link","https://4everland.io"],JS=2336;function QS(r){return r=r.toString(),{id:$m(L.createV1(JS,bt.digest(D(r)))),multiaddrs:[Ay(r)]}}var Vh=class{gateways;constructor(t={}){this.gateways=(t.gateways??ZS).map(e=>QS(e))}async*findProviders(t,e){yield*this.gateways.toSorted(()=>Math.random()>.5?1:-1).map(n=>({...n,protocols:["transport-ipfs-gateway-http"]}))}};function Gi(r={}){return new Vh(r)}var Dn=class{has(t,e){return Promise.reject(new Error(".has is not implemented"))}put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(t,e){for await(let{cid:n,block:o}of t)await this.put(n,o,e),yield n}get(t,e){return Promise.reject(new Error(".get is not implemented"))}async*getMany(t,e){for await(let n of t)yield{cid:n,block:await this.get(n,e)}}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(t,e){for await(let n of t)await this.delete(n,e),yield n}async*getAll(t){throw new Error(".getAll is not implemented")}};var ir=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not Found"){super(t)}};var Wi=class extends Dn{data;constructor(){super(),this.data=new Map}put(t,e){return this.data.set(St.encode(t.multihash.bytes),e),t}get(t){let e=this.data.get(St.encode(t.multihash.bytes));if(e==null)throw new ir;return e}has(t){return this.data.has(St.encode(t.multihash.bytes))}async delete(t){this.data.delete(St.encode(t.multihash.bytes))}async*getAll(){for(let[t,e]of this.data.entries())yield{cid:L.createV1(ae,wt(St.decode(t))),block:e}}};var P5=Ce("blockstore:core:tiered");var _y="SHARDING";function eA(r){return r[Symbol.asyncIterator]!=null}function rA(r){if(eA(r))return(async()=>{let e=[];for await(let n of r)e.push(n);return e})();let t=[];for(let e of r)t.push(e);return t}var Hh=rA;function nA(r){return r[Symbol.asyncIterator]!=null}function oA(r,t){return nA(r)?async function*(){yield*(await Hh(r)).sort(t)}():function*(){yield*Hh(r).sort(t)}()}var jc=oA;var Or=class{put(t,e,n){return Promise.reject(new Error(".put is not implemented"))}get(t,e){return Promise.reject(new Error(".get is not implemented"))}has(t,e){return Promise.reject(new Error(".has is not implemented"))}delete(t,e){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(t,e={}){for await(let{key:n,value:o}of t)await this.put(n,o,e),yield n}async*getMany(t,e={}){for await(let n of t)yield{key:n,value:await this.get(n,e)}}async*deleteMany(t,e={}){for await(let n of t)await this.delete(n,e),yield n}batch(){let t=[],e=[];return{put(n,o){t.push({key:n,value:o})},delete(n){e.push(n)},commit:async n=>{await ur(this.putMany(t,n)),t=[],await ur(this.deleteMany(e,n)),e=[]}}}async*_all(t,e){throw new Error("._all is not implemented")}async*_allKeys(t,e){throw new Error("._allKeys is not implemented")}query(t,e){let n=this._all(t,e);if(t.prefix!=null){let o=t.prefix;n=ve(n,i=>i.key.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,i)=>ve(o,i),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,i)=>jc(o,i),n)),t.offset!=null){let o=0,i=t.offset;n=ve(n,()=>o++>=i)}return t.limit!=null&&(n=ds(n,t.limit)),n}queryKeys(t,e){let n=this._allKeys(t,e);if(t.prefix!=null){let o=t.prefix;n=ve(n,i=>i.toString().startsWith(o))}if(Array.isArray(t.filters)&&(n=t.filters.reduce((o,i)=>ve(o,i),n)),Array.isArray(t.orders)&&(n=t.orders.reduce((o,i)=>jc(o,i),n)),t.offset!=null){let o=t.offset,i=0;n=ve(n,()=>i++>=o)}return t.limit!=null&&(n=ds(n,t.limit)),n}};var ji=class extends Or{data;constructor(){super(),this.data=new Map}put(t,e){return this.data.set(t.toString(),e),t}get(t){let e=this.data.get(t.toString());if(e==null)throw new ir;return e}has(t){return this.data.has(t.toString())}delete(t){this.data.delete(t.toString())}*_all(){for(let[t,e]of this.data.entries())yield{key:new At(t),value:e}}*_allKeys(){for(let t of this.data.keys())yield new At(t)}};var dO=new At(_y);var _O=Ce("datastore:core:tiered");async function Ty(r={}){let t=r.datastore??new ji,e=r.blockstore??new Wi,n=new Ec({...r,datastore:t,blockstore:e,blockBrokers:r.blockBrokers??[Hi()],routers:r.routers??[Ki("https://delegated-ipfs.dev"),Gi()]});return r.start!==!1&&await n.start(),n}var qh=Ot(Yc(),1);var Kh=40;function Gh(r,t){if(!r.length)throw new Error("Unexpected end of data");let e=qh.default.decode(r);return t.seek(qh.default.decode.bytes),e}function Wh(r){let t=new DataView(r.buffer,r.byteOffset,r.byteLength),e=0;return{version:2,characteristics:[t.getBigUint64(e,!0),t.getBigUint64(e+=8,!0)],dataOffset:Number(t.getBigUint64(e+=8,!0)),dataSize:Number(t.getBigUint64(e+=8,!0)),indexOffset:Number(t.getBigUint64(e+=8,!0))}}var un={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},Yi={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":un.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(un.List(r)!==void 0){for(let t=0;t<r.length;t++){let e=r[t];if(e=Yi["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](e),e===void 0)return;if(e!==r[t]){let n=r.slice(0,t);for(let o=t;o<r.length;o++){let i=r[o];if(i=Yi["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:un.Int,CarV1HeaderOrV2Pragma:r=>{if(un.Map(r)===void 0)return;let t=Object.entries(r),e=r,n=1;for(let o=0;o<t.length;o++){let[i,s]=t[o];switch(i){case"roots":{let a=Yi["CarV1HeaderOrV2Pragma > roots (anon)"](r[i]);if(a===void 0)return;if(a!==s||e!==r){if(e===r){e={};for(let c=0;c<o;c++)e[t[c][0]]=t[c][1]}e.roots=a}}break;case"version":{n--;let a=Yi.Int(r[i]);if(a===void 0)return;if(a!==s||e!==r){if(e===r){e={};for(let c=0;c<o;c++)e[t[c][0]]=t[c][1]}e.version=a}}break;default:return}}if(!(n>0))return e}},Xi={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":un.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(un.List(r)!==void 0){for(let t=0;t<r.length;t++){let e=r[t];if(e=Xi["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](e),e===void 0)return;if(e!==r[t]){let n=r.slice(0,t);for(let o=t;o<r.length;o++){let i=r[o];if(i=Xi["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](i),i===void 0)return;n.push(i)}return n}}return r}},Int:un.Int,CarV1HeaderOrV2Pragma:r=>{if(un.Map(r)===void 0)return;let t=Object.entries(r),e=r,n=1;for(let o=0;o<t.length;o++){let[i,s]=t[o];switch(i){case"roots":{let a=Xi["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||e!==r){if(e===r){e={};for(let c=0;c<o;c++)e[t[c][0]]=t[c][1]}e.roots=a}}break;case"version":{n--;let a=Xi.Int(s);if(a===void 0)return;if(a!==s||e!==r){if(e===r){e={};for(let c=0;c<o;c++)e[t[c][0]]=t[c][1]}e.version=a}}break;default:return}}if(!(n>0))return e}},jh={toTyped:Yi.CarV1HeaderOrV2Pragma,toRepresentation:Xi.CarV1HeaderOrV2Pragma};var hU=Pf();var EA=Ot(Yc(),1);var yU=[new B(w.map,2),new B(w.string,"version"),new B(w.uint,1),new B(w.string,"roots")],wU=new B(w.tag,42);async function Yh(r,t){let e=Gh(await r.upTo(8),r);if(e===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(e,!0),o=cn(n);if(jh.toTyped(o)===void 0)throw new Error("Invalid CAR header format");if(o.version!==1&&o.version!==2||t!==void 0&&o.version!==t)throw new Error(`Invalid CAR version: ${o.version}${t!==void 0?` (expected ${t})`:""}`);if(o.version===1){if(!Array.isArray(o.roots))throw new Error("Invalid CAR header format");return o}if(o.roots!==void 0)throw new Error("Invalid CAR header format");let i=Wh(await r.exactly(Kh,!0));r.seek(i.dataOffset-r.pos);let s=await Yh(r,1);return Object.assign(s,i)}function Zi(r){let t=0;return{async upTo(e){return r.subarray(t,t+Math.min(e,r.length-t))},async exactly(e,n=!1){if(e>r.length-t)throw new Error("Unexpected end of data");let o=r.subarray(t,t+e);return n&&(t+=e),o},seek(e){t+=e},get pos(){return t}}}var Xh=Ot(Yc(),1),Hy=1;function Zh(r){let t=Ao({version:Hy,roots:r}),e=Xh.default.encode(t.length),n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function $y(r){return{async setRoots(t){let e=Zh(t);await r.write(e)},async writeBlock(t){let{cid:e,bytes:n}=t;await r.write(new Uint8Array(Xh.default.encode(e.bytes.length+n.length))),await r.write(e.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return Hy}}}function Xc(){}function zy(){let r=[],t=null,e=Xc,n=!1,o=null,i=Xc,s=()=>(t||(t=new Promise(l=>{e=()=>{t=null,e=Xc,l()}})),t),a={write(l){r.push(l);let u=s();return i(),u},async end(){n=!0;let l=s();i(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&e(),{done:!1,value:l}):n?(e(),{done:!0,value:void 0}):(o||(o=new Promise(u=>{i=()=>(o=null,i=Xc,u(c.next()))})),o)}};return{writer:a,iterator:c}}var Ji=class r{constructor(t,e){this._encoder=e,this._mutex=e.setRoots(t),this._ended=!1}async put(t){if(!(t.bytes instanceof Uint8Array)||!t.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let e=L.asCID(t.cid);if(!e)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:e,bytes:t.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(t){t=IA(t);let{encoder:e,iterator:n}=qy(),o=new r(t,e),i=new Zc(n);return{writer:o,out:i}}static createAppender(){let{encoder:t,iterator:e}=qy();t.setRoots=()=>Promise.resolve();let n=new r([],t),o=new Zc(e);return{writer:n,out:o}}static async updateRootsInBytes(t,e){let n=Zi(t);await Yh(n);let o=Zh(e);if(Number(n.pos)!==o.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${o.length} bytes)`);return t.set(o,0),t}},Zc=class{constructor(t){this._iterator=t}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function qy(){let r=zy(),{writer:t,iterator:e}=r;return{encoder:$y(t),iterator:e}}function IA(r){if(r===void 0)return[];if(!Array.isArray(r)){let e=L.asCID(r);if(!e)throw new TypeError("roots must be a single CID or an array of CIDs");return[e]}let t=[];for(let e of r){let n=L.asCID(e);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");t.push(n)}return t}var kA=1,Jh=class{components;constructor(t,e){this.components=t}async import(t,e){await ur(this.components.blockstore.putMany(zt(t.blocks(),({cid:n,bytes:o})=>({cid:n,block:o})),e))}async export(t,e,n){let o=ft(),i=Array.isArray(t)?t:[t],s=new de({concurrency:kA});s.on("idle",()=>{o.resolve()}),s.on("error",a=>{s.clear(),o.reject(a)});for(let a of i)s.add(async()=>{await this.#t(a,s,async(c,l)=>{n?.blockFilter?.has(c.multihash.bytes)!==!0&&(n?.blockFilter?.add(c.multihash.bytes),await e.put({cid:c,bytes:l}))},n)}).catch(()=>{});try{await o.promise}finally{await e.close()}}async*stream(t,e){let{writer:n,out:o}=Ji.create(t);this.export(t,n,e).catch(()=>{});for await(let i of o)yield i}async#t(t,e,n,o){let i=await this.components.getCodec(t.code),s=await this.components.blockstore.get(t,o);await n(t,s);let a=ec({bytes:s,cid:t,codec:i});for await(let[,c]of a.links())e.add(async()=>{await this.#t(c,e,n,o)})}};function Ky(r,t={}){return new Jh(r,t)}W.formatters.b=r=>r==null?"undefined":Y.baseEncode(r);W.formatters.t=r=>r==null?"undefined":St.baseEncode(r);W.formatters.m=r=>r==null?"undefined":se.baseEncode(r);W.formatters.p=r=>r==null?"undefined":r.toString();W.formatters.c=r=>r==null?"undefined":r.toString();W.formatters.k=r=>r==null?"undefined":r.toString();W.formatters.a=r=>r==null?"undefined":r.toString();W.formatters.e=r=>r==null?"undefined":r.stack??r.message;function _A(r){let t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=r,t.destroy=()=>!0,t.extend=()=>t,t}function fn(r){let t=_A(`${r}:trace`);return W.enabled(`${r}:trace`)&&W.names.map(e=>e.toString()).find(e=>e.includes(":trace"))!=null&&(t=W(`${r}:trace`)),Object.assign(W(r),{error:W(`${r}:error`),trace:t})}var Qy=Ot(Do(),1);var Jc=class extends Error{static name="SignatureCreationError";constructor(t="Record signature creation failed"){super(t),this.name="SignatureCreationError"}},Ke=class extends Error{static name="SignatureVerificationError";constructor(t="Record signature verification failed"){super(t),this.name="SignatureVerificationError"}},Qc=class extends Error{static name="RecordExpiredError";constructor(t="Record has expired"){super(t),this.name="RecordExpiredError"}},On=class extends Error{static name="UnsupportedValidityError";constructor(t="The validity type is unsupported"){super(t),this.name="UnsupportedValidityError"}},tl=class extends Error{static name="RecordTooLargeError";constructor(t="The record is too large"){super(t),this.name="RecordTooLargeError"}},Qi=class extends Error{static name="InvalidValueError";constructor(t="Value must be a valid content path starting with /"){super(t),this.name="InvalidValueError"}},el=class extends Error{static name="InvalidRecordDataError";constructor(t="Invalid record data"){super(t),this.name="InvalidRecordDataError"}},ts=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(t="Invalid embedded public key"){super(t),this.name="InvalidEmbeddedPublicKeyError"}};var Ht;(function(r){let t;(function(o){o.EOL="EOL"})(t=r.ValidityType||(r.ValidityType={}));let e;(function(o){o[o.EOL=0]="EOL"})(e||(e={})),function(o){o.codec=()=>dr(e)}(t=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=le((o,i,s={})=>{s.lengthDelimited!==!1&&i.fork(),o.value!=null&&(i.uint32(10),i.bytes(o.value)),o.signatureV1!=null&&(i.uint32(18),i.bytes(o.signatureV1)),o.validityType!=null&&(i.uint32(24),r.ValidityType.codec().encode(o.validityType,i)),o.validity!=null&&(i.uint32(34),i.bytes(o.validity)),o.sequence!=null&&(i.uint32(40),i.uint64(o.sequence)),o.ttl!=null&&(i.uint32(48),i.uint64(o.ttl)),o.pubKey!=null&&(i.uint32(58),i.bytes(o.pubKey)),o.signatureV2!=null&&(i.uint32(66),i.bytes(o.signatureV2)),o.data!=null&&(i.uint32(74),i.bytes(o.data)),s.lengthDelimited!==!1&&i.ldelim()},(o,i,s={})=>{let a={},c=i==null?o.len:o.pos+i;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.value=o.bytes();break}case 2:{a.signatureV1=o.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(o);break}case 4:{a.validity=o.bytes();break}case 5:{a.sequence=o.uint64();break}case 6:{a.ttl=o.uint64();break}case 7:{a.pubKey=o.bytes();break}case 8:{a.signatureV2=o.bytes();break}case 9:{a.data=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>ce(o,r.codec()),r.decode=(o,i)=>ie(o,r.codec(),i)})(Ht||(Ht={}));var BA=fn("ipns:utils"),Gy=D("/ipns/"),TA=114,CA=0,RA=18;function Wy(r){let t;if(r.pubKey!=null)try{t=Ia(r.pubKey)}catch(e){throw BA.error(e),e}if(t!=null)return t}function jy(r,t,e){let n=D(t);return ct([r,e,n])}function nl(r){let t=D("ipns-signature:");return ct([t,r])}function Qh(r){return"signatureV1"in r?Ht.encode({value:D(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:D(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):Ht.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function sr(r){let t=Ht.decode(r);if(t.sequence!=null&&(t.sequence=BigInt(t.sequence)),t.ttl!=null&&(t.ttl=BigInt(t.ttl)),t.signatureV2==null||t.data==null)throw new Ke("Missing data or signatureV2");let e=Zy(t.data),n=NA(e.Value),o=q(e.Validity);if(t.value!=null&&t.signatureV1!=null)return LA(t),{value:n,validityType:Ht.ValidityType.EOL,validity:o,sequence:e.Sequence,ttl:e.TTL,pubKey:t.pubKey,signatureV1:t.signatureV1,signatureV2:t.signatureV2,data:t.data};if(t.signatureV2!=null)return{value:n,validityType:Ht.ValidityType.EOL,validity:o,sequence:e.Sequence,ttl:e.TTL,pubKey:t.pubKey,signatureV2:t.signatureV2,data:t.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function Fo(r){return ct([Gy,r.bytes])}function Yy(r){let t=wt(r.slice(Gy.length));if(!rl(t,CA)&&!rl(t,RA))throw new Ae("Multihash in IPNS key was not identity or sha2-256");return t}function Xy(r,t,e,n,o){let i;if(t===Ht.ValidityType.EOL)i=0;else throw new On("The validity type is unsupported");return nr({Value:r,Validity:e,ValidityType:i,Sequence:n,TTL:o})}function Zy(r){let t=Vt(r);if(t.ValidityType===0)t.ValidityType=Ht.ValidityType.EOL;else throw new On("The validity type is unsupported");return Number.isInteger(t.Sequence)&&(t.Sequence=BigInt(t.Sequence)),Number.isInteger(t.TTL)&&(t.TTL=BigInt(t.TTL)),t}function NA(r){let t=q(r).trim();if(t.startsWith("/"))return t;try{return`/ipfs/${L.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${L.parse(t).toV1().toString()}`}catch{}throw new Qi("Value must be a valid content path starting with /")}function Jy(r){if(r!=null){let t=OA(r);if(t!=null)return t.code===TA?`/ipns/${t.toString(Kt)}`:`/ipfs/${t.toV1().toString()}`;if(PA(r))return`/ipns/${Kt.encode(r.bytes)}`;let e=r.toString().trim();if(e.startsWith("/")&&e.length>1)return e}throw new Qi("Value must be a valid content path starting with /")}function LA(r){if(r.data==null)throw new el("Record data is missing");let t=Zy(r.data);if(!Z(t.Value,r.value??new Uint8Array(0)))throw new Ke('Field "value" did not match between protobuf and CBOR');if(!Z(t.Validity,r.validity??new Uint8Array(0)))throw new Ke('Field "validity" did not match between protobuf and CBOR');if(t.ValidityType!==r.validityType)throw new Ke('Field "validityType" did not match between protobuf and CBOR');if(t.Sequence!==r.sequence)throw new Ke('Field "sequence" did not match between protobuf and CBOR');if(t.TTL!==r.ttl)throw new Ke('Field "ttl" did not match between protobuf and CBOR')}function PA(r){return r.bytes instanceof Uint8Array}function DA(r){return typeof r?.toCID=="function"}function OA(r){if(DA(r))return r.toCID();try{return L.parse(r)}catch{}return L.asCID(r)}function rl(r,t){return r.code===t}var UA=fn("ipns"),tw=60*60*1e9,FA="/ipns/",LF=FA.length,ew={v1Compatible:!0,ttlNs:tw};async function rw(r,t,e,n,o=ew){let i=new Qy.default(Date.now()+Number(n)),s=Ht.ValidityType.EOL,a=BigInt(o.ttlNs??tw);return MA(r,t,e,s,i.toString(),a,o)}var MA=async(r,t,e,n,o,i,s=ew)=>{e=BigInt(e);let a=D(o),c=Jy(t),l=D(c),u=Xy(l,n,a,e,i),f=nl(u),d=await r.sign(f),h;if(r.type==="RSA"&&(h=so(r.publicKey)),s.v1Compatible===!0){let m=await VA(r,l,n,a),p={value:c,signatureV1:m,validity:o,validityType:n,sequence:e,ttl:i,signatureV2:d,data:u};return h!=null&&(p.pubKey=h),p}else{let m={value:c,validity:o,validityType:n,sequence:e,ttl:i,signatureV2:d,data:u};return h!=null&&(m.pubKey=h),m}},VA=async(r,t,e,n)=>{try{let o=jy(t,e,n);return await r.sign(o)}catch(o){throw UA.error("record signature creation failed",o),new Jc("Record signature creation failed")}};var td=Ot(Do(),1);function nw(r,t){let e=t.map((n,o)=>({record:sr(n),index:o}));return e.sort((n,o)=>{let i=n.record.sequence,s=o.record.sequence;if(i>s)return-1;if(i<s)return 1;if(n.record.validityType===Ht.ValidityType.EOL&&o.record.validityType===Ht.ValidityType.EOL){let a=td.default.fromString(n.record.validity).toDate(),c=td.default.fromString(o.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),e[0].index}var ow=Ot(Do(),1);var ol=fn("ipns:validator"),HA=1024*10,$A=async(r,t)=>{let e=sr(t),n;try{let o=nl(e.data);n=await r.verify(o,e.signatureV2)}catch{n=!1}if(!n)throw ol.error("record signature verification failed"),new Ke("Record signature verification failed");if(e.validityType===Ht.ValidityType.EOL){if(ow.default.fromString(e.validity).toDate().getTime()<Date.now())throw ol.error("record has expired"),new Qc("record has expired")}else if(e.validityType!=null)throw ol.error("the validity type is unsupported"),new On("The validity type is unsupported");ol("ipns record for %s is valid",e.value)};async function ed(r,t){if(t.byteLength>HA)throw new tl("The record is too large");let e=Yy(r),n;rl(e,0)&&(n=rn(e));let o=sr(t),i=Wy(o)??n;if(i==null)throw new ts("Could not extract public key from IPNS record or routing key");let s=Fo(i.toMultihash());if(!Z(r,s))throw new ts("Embedded public key did not match routing key");await $A(i,t)}var iw=Symbol.for("nodejs.util.inspect.custom"),zA=114,es=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[$n]=!0;toString(){return this.string==null&&(this.string=Y.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return L.createV1(zA,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Z(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Z(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[iw](){return`PeerId(${this.toString()})`}},il=class extends es{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},sl=class extends es{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},al=class extends es{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},qA=2336,cl=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=bt.digest(D(this.url))}[iw](){return`PeerId(${this.url})`}[$n]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return L.createV1(qA,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=q(t)),t.toString()===this.toString())}};function sw(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=wt(Y.decode(`z${r}`));else{if(t==null)throw new gt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=wt(t.decode(r))}return KA(e)}function KA(r){if(WA(r))return new il({multihash:r});if(GA(r))try{let t=rn(r);if(t.type==="Ed25519")return new sl({multihash:r,publicKey:t});if(t.type==="secp256k1")return new al({multihash:r,publicKey:t})}catch{let e=q(r.digest);return new cl(new URL(e))}throw new Ae("Supplied PeerID Multihash is invalid")}function GA(r){return r.code===bt.code}function WA(r){return r.code===Xe.code}var ll=class extends Error{static name="DNSLinkNotFoundError";constructor(t="DNSLink not found"){super(t),this.name="DNSLinkNotFoundError"}},ul=class extends Error{static name="RecordsFailedValidationError";constructor(t="Records failed validation"){super(t),this.name="RecordsFailedValidationError"}},fl=class extends Error{static name="UnsupportedMultibasePrefixError";constructor(t="Unsupported multibase prefix"){super(t),this.name="UnsupportedMultibasePrefixError"}},hl=class extends Error{static name="UnsupportedMultihashCodecError";constructor(t="Unsupported multihash codec"){super(t),this.name="UnsupportedMultihashCodecError"}},dl=class extends Error{static name="InvalidValueError";constructor(t="Invalid value"){super(t),this.name="InvalidValueError"}};var jA=32;async function aw(r,t,e,n,o={}){if(t===0)throw new Error("recursion limit exceeded");n("query %s for TXT and CNAME records",r);let s=((await e.query(r,{...o,types:[pe.TXT]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d TXT records for %s",s.length,r);for(let l of s)try{let u=l.data;if(u.startsWith('"')&&u.endsWith('"')&&(u=u.substring(1,u.length-1)),!u.startsWith("dnslink="))continue;n("%s TXT %s",l.name,u),u=u.replace("dnslink=","");let[,f,d,...h]=u.split("/");if(f==="ipfs")try{return{value:`/ipfs/${L.parse(d)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}else if(f==="ipns"){try{return{value:`/ipns/${sw(d)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}return await pl(d,t-1,e,n,o)}else{if(f==="dnslink")return await pl(d,t-1,e,n,o);n('unknown protocol "%s" in DNSLink record for domain: %s',f,r);continue}}catch(u){n.error("could not parse DNS link record for domain %s, %s",r,l.data,u)}n("no DNSLink records found for %s, falling back to CNAME",r);let c=((await e.query(r,{...o,types:[pe.CNAME]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d CNAME records for %s",c.length,r);for(let l of c)try{return await pl(l.data,t-1,e,n,o)}catch(u){n.error("domain %s cname %s had no DNSLink records",r,l.data,u)}throw new ll(`No DNSLink records found for domain: ${r}`)}async function pl(r,t,e,n,o={}){if(t===0)throw new Error("recursion limit exceeded");r.startsWith("_dnslink.")||(r=`_dnslink.${r}`);try{return await aw(r,t,e,n,o)}catch(i){if(i.code!=="ENOTFOUND"&&i.code!=="ENODATA"&&i.name!=="DNSLinkNotFoundError"&&i.name!=="NotFoundError")throw i;return r.startsWith("_dnslink.")?r=r.replace("_dnslink.",""):r=`_dnslink.${r}`,aw(r,t,e,n,o)}}async function cw(r,t,e,n={}){return pl(r,n.maxRecursiveDepth??jA,t,e,n)}var rd=class{routing;constructor(t){this.routing=t}async put(t,e,n={}){try{await this.routing.put(t,e,n)}catch(o){n.onProgress?.(new H("ipns:routing:helia:error",o))}}async get(t,e={}){try{return await this.routing.get(t,e)}catch(n){e.onProgress?.(new H("ipns:routing:helia:error",n))}throw new Error("Not found")}};function lw(r){return new rd(r)}var rs;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.key!=null&&e.key.byteLength>0&&(n.uint32(10),n.bytes(e.key)),e.value!=null&&e.value.byteLength>0&&(n.uint32(18),n.bytes(e.value)),e.timeReceived!=null&&e.timeReceived!==""&&(n.uint32(42),n.string(e.timeReceived)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let i={key:re(0),value:re(0),timeReceived:""},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let a=e.uint32();switch(a>>>3){case 1:{i.key=e.bytes();break}case 2:{i.value=e.bytes();break}case 5:{i.timeReceived=e.string();break}default:{e.skipType(a&7);break}}}return i})),t),r.encode=e=>ce(e,r.codec()),r.decode=(e,n)=>ie(e,r.codec(),n)})(rs||(rs={}));function uw(r){let t=r.getUTCFullYear(),e=String(r.getUTCMonth()+1).padStart(2,"0"),n=String(r.getUTCDate()).padStart(2,"0"),o=String(r.getUTCHours()).padStart(2,"0"),i=String(r.getUTCMinutes()).padStart(2,"0"),s=String(r.getUTCSeconds()).padStart(2,"0"),a=r.getUTCMilliseconds(),c=String(a*1e3*1e3).padStart(9,"0");return`${t}-${e}-${n}T${o}:${i}:${s}.${c}Z`}function fw(r){let t=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),e=String(r).trim().match(t);if(e==null)throw new Error("Invalid format");let n=parseInt(e[1],10),o=parseInt(e[2],10)-1,i=parseInt(e[3],10),s=parseInt(e[4],10),a=parseInt(e[5],10),c=parseInt(e[6],10),l=parseInt(e[7].slice(0,-6),10);return new Date(Date.UTC(n,o,i,s,a,c,l))}var ar=class r{key;value;timeReceived;constructor(t,e,n){if(!(t instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(e instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=t,this.value=e,this.timeReceived=n}serialize(){return rs.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:uw(this.timeReceived)}}static deserialize(t){let e=rs.decode(t);return new r(e.key,e.value,new Date(e.timeReceived))}static fromDeserialized(t){let e=fw(t.timeReceived);if(t.key==null)throw new Error("key missing from deserialized object");if(t.value==null)throw new Error("value missing from deserialized object");return new r(t.key,t.value,e)}};var ml=globalThis.CustomEvent??Event;async function*Un(r,t={}){let e=t.concurrency??1/0;e<1&&(e=1/0);let n=t.ordered==null?!1:t.ordered,o=new EventTarget,i=[],s=ft(),a=ft(),c=!1,l,u=!1;o.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(i.length===e&&(s=ft(),await s.promise),u)break;let p={done:!1};i.push(p),m().then(y=>{p.done=!0,p.ok=!0,p.value=y,o.dispatchEvent(new ml("task-complete"))},y=>{p.done=!0,p.err=y,o.dispatchEvent(new ml("task-complete"))})}c=!0,o.dispatchEvent(new ml("task-complete"))}catch(m){l=m,o.dispatchEvent(new ml("task-complete"))}});function f(){return n?i[0]?.done:!!i.find(m=>m.done)}function*d(){for(;i.length>0&&i[0].done;){let m=i[0];if(i.shift(),m.ok)yield m.value;else throw u=!0,s.resolve(),m.err;s.resolve()}}function*h(){for(;f();)for(let m=0;m<i.length;m++)if(i[m].done){let p=i[m];if(i.splice(m,1),m--,p.ok)yield p.value;else throw u=!0,s.resolve(),p.err;s.resolve()}}for(;;){if(f()||(a=ft(),await a.promise),l!=null)throw l;if(n?yield*d():yield*h(),c&&i.length===0)break}}var hw;(function(r){r[r.SEND_QUERY=0]="SEND_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADD_PEER=6]="ADD_PEER",r[r.DIAL_PEER=7]="DIAL_PEER"})(hw||(hw={}));function gl(r){return new At("/dht/record/"+q(r,"base32"),!1)}function dw(r){return{async put(t,e,n={}){try{let o=gl(t);try{let s=await r.get(o),a=ar.deserialize(s);if(Z(a.value,e))return}catch(s){if(s.name!=="NotFoundError")throw s}let i=new ar(t,e,new Date);n.onProgress?.(new H("ipns:routing:datastore:put")),await r.put(o,i.serialize(),n)}catch(o){throw n.onProgress?.(new H("ipns:routing:datastore:error",o)),o}},async get(t,e={}){try{let n=gl(t);e.onProgress?.(new H("ipns:routing:datastore:get"));let o=await r.get(n,e),i=ar.deserialize(o);return{record:i.value,created:i.timeReceived}}catch(n){throw e.onProgress?.(new H("ipns:routing:datastore:error",n)),n}},async has(t,e={}){let n=gl(t);return r.has(n,e)},async delete(t,e){let n=gl(t);return r.delete(n,e)}}}function nd(r,t){return r.code===t}var Ur=fn("helia:ipns"),JA=60*1e3,sd=60*JA,QA=24*sd,od=23*sd,tI=BigInt(sd)*1000000n,pw={[Kt.prefix]:Kt,[Y.prefix]:Y},id=class{routers;localStore;timeout;dns;log;constructor(t,e=[]){this.routers=[lw(t.routing),...e],this.localStore=dw(t.datastore),this.dns=t.dns,this.log=t.logger.forComponent("helia:ipns")}async publish(t,e,n={}){try{let o=1n,i=Fo(t.publicKey.toMultihash());if(await this.localStore.has(i,n)){let{record:c}=await this.localStore.get(i,n);o=sr(c).sequence+1n}let s=await rw(t,e,o,n.lifetime??QA,n),a=Qh(s);return await this.localStore.put(i,a,n),n.offline!==!0&&await Promise.all(this.routers.map(async c=>{await c.put(i,a,n)})),s}catch(o){throw n.onProgress?.(new H("ipns:publish:error",o)),o}}async resolve(t,e={}){let n=Td(t)?t.toMultihash():t,o=Fo(n),i=await this.#r(o,e);return{...await this.#t(i.value,e),record:i}}async resolveDNSLink(t,e={}){let n=await cw(t,this.dns,this.log,e);return{...await this.#t(n.value,e),answer:n.answer}}republish(t={}){if(this.timeout!=null)throw new Error("Republish is already running");t.signal?.addEventListener("abort",()=>{clearTimeout(this.timeout)});async function e(){let n=Date.now();t.onProgress?.(new H("ipns:republish:start"));let i=Date.now()-n,s=od-i;s<0&&(s=t.interval??od),setTimeout(()=>{e().catch(a=>{Ur.error("error republishing",a)})},s)}this.timeout=setTimeout(()=>{e().catch(n=>{Ur.error("error republishing",n)})},t.interval??od)}async#t(t,e={}){let n=t.split("/");try{let o=n[1];if(o==="ipns"){let i=n[2],s=i.substring(0,1),a;if(s==="1"||s==="Q")a=Y.decode(`z${i}`);else if(pw[s]!=null)a=pw[s].decode(i);else throw new fl(`Unsupported multibase prefix "${s}"`);let c;try{c=wt(a)}catch{c=L.decode(a).multihash}if(!nd(c,0)&&!nd(c,18))throw new hl(`Unsupported multihash codec "${c.code}"`);let{cid:l}=await this.resolve(c,e),u=n.slice(3).join("/");return{cid:l,path:u}}else if(o==="ipfs"){let i=L.parse(n[2]),s=n.slice(3).join("/");return{cid:i,path:s}}}catch(o){Ur.error("error parsing ipfs path",o)}throw Ur.error("invalid ipfs path %s",t),new dl("Invalid value")}async#r(t,e={}){let n=[];if(await this.localStore.has(t,e))if(Ur("record is present in the cache"),e.nocache!==!0)try{let{record:a,created:c}=await this.localStore.get(t,e);this.log("record retrieved from cache"),await ed(t,a),this.log("record was valid");let l=sr(a),u=Number((l.ttl??tI)/1000000n);if(c.getTime()+u>Date.now())return this.log("record TTL was valid"),l;if(e.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),l;this.log("record TTL has been reached, searching routing for updates"),n.push(a)}catch(a){this.log("cached record was invalid",a),await this.localStore.delete(t,e)}else Ur("ignoring local cache due to nocache=true option");if(e.offline===!0)throw new _t("Record was not present in the cache or has expired");Ur("did not have record locally");let i=0;if(await Promise.all(this.routers.map(async a=>{let c;try{c=await a.get(t,{...e,validate:!1})}catch(l){Ur.error("error finding IPNS record",l);return}try{await ed(t,c),n.push(c)}catch(l){i++,Ur.error("error finding IPNS record",l)}})),n.length===0)throw i>0?new ul(`${i>1?`${i} records`:"Record"} found for routing key ${i>1?"were":"was"} invalid`):new _t("Could not find record for routing key");let s=n[nw(t,n)];return await this.localStore.put(t,s,e),sr(s)}};function mw(r,{routers:t=[]}={}){return new id(r,t)}var gw;(function(r){r[r.SEND_QUERY=0]="SEND_QUERY",r[r.PEER_RESPONSE=1]="PEER_RESPONSE",r[r.FINAL_PEER=2]="FINAL_PEER",r[r.QUERY_ERROR=3]="QUERY_ERROR",r[r.PROVIDER=4]="PROVIDER",r[r.VALUE=5]="VALUE",r[r.ADD_PEER=6]="ADD_PEER",r[r.DIAL_PEER=7]="DIAL_PEER"})(gw||(gw={}));function eI(r){return r[Symbol.asyncIterator]!=null}function rI(r){if(eI(r))return(async()=>{let e;for await(let n of r)e=n;return e})();let t;for(let e of r)t=e;return t}var yw=rI;var yl=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(t="Bad path"){super(t)}},Re=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(t="Not found"){super(t)}},wl=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(t="No resolver"){super(t)}},Ct=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(t="Not UnixFS"){super(t)}},bl=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(t="Over read"){super(t)}},xl=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(t="Under read"){super(t)}},El=class r extends Error{static name="NoPropError";static code="ERR_NO_PROP";name=r.name;code=r.code;constructor(t="No Property found"){super(t)}},Fn=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(t="Invalid parameters"){super(t)}};function Mo(r,t,e,n,o,i,s){let a=r,c=o;for(;i.length>0;){let l=i[0];if(l in a){i.shift(),c=`${c}/${l}`;let u=L.asCID(a[l]);if(u!=null)return{entry:{type:"object",name:n,path:o,cid:e,node:t,depth:s,size:BigInt(t.length),content:async function*(){yield r}},next:{cid:u,name:l,path:c,toResolve:i}};a=a[l]}else throw new El(`No property named ${l} found in node ${e}`)}return{entry:{type:"object",name:n,path:o,cid:e,node:t,depth:s,size:BigInt(t.length),content:async function*(){yield r}}}}var nI=async(r,t,e,n,o,i,s,a)=>{let c=await s.get(r,a),l=cn(c);return Mo(l,c,r,t,e,n,i)},ww=nI;var oI=async(r,t,e,n,o,i,s,a)=>{let c=await s.get(r,a),l=ko(c);return Mo(l,c,r,t,e,n,i)},bw=oI;function iI(r,t,e,n){let o=BigInt(r.length),i=BigInt(t+o);return e>=i||n<t?new Uint8Array(0):(n>=t&&n<i&&(r=r.subarray(0,Number(n-t))),e>=t&&e<i&&(r=r.subarray(Number(e-t))),r)}var Mn=iI;var sI=(r,t=0,e=r)=>{let n=BigInt(r),o=BigInt(t??0),i=BigInt(e);if(i!==n&&(i=o+i),i>n&&(i=n),o<0n)throw new Fn("Offset must be greater than or equal to 0");if(o>n)throw new Fn("Offset must be less than the file size");if(i<0n)throw new Fn("Length must be greater than or equal to 0");if(i>n)throw new Fn("Length must be less than the file size");return{start:o,end:i}},Vo=sI;var aI=r=>{async function*t(e={}){let{start:n,end:o}=Vo(r.length,e.offset,e.length),i=Mn(r,0n,n,o);e.onProgress?.(new H("unixfs:exporter:progress:identity",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return t},cI=async(r,t,e,n,o,i,s,a)=>{if(n.length>0)throw new Re(`No link named ${e} found in raw node ${r}`);let c=wt(r.multihash.bytes);return{entry:{type:"identity",name:t,path:e,cid:r,content:aI(c.digest),depth:i,size:BigInt(c.digest.length),node:c.digest}}},xw=cI;var lI=async(r,t,e,n,o,i,s,a)=>{let c=await s.get(r,a),l=Su(c);return Mo(l,c,r,t,e,n,i)},Ew=lI;var uI=r=>{async function*t(e={}){let{start:n,end:o}=Vo(r.length,e.offset,e.length),i=Mn(r,0n,n,o);e.onProgress?.(new H("unixfs:exporter:progress:raw",{bytesRead:BigInt(i.byteLength),totalBytes:o-n,fileSize:BigInt(r.byteLength)})),yield i}return t},fI=async(r,t,e,n,o,i,s,a)=>{if(n.length>0)throw new Re(`No link named ${e} found in raw node ${r}`);let c=await s.get(r,a);return{entry:{type:"raw",name:t,path:e,cid:r,content:uI(c),depth:i,size:BigInt(c.length),node:c}}},vw=fI;var ns=class r extends Error{static name="InvalidTypeError";static code="ERR_INVALID_TYPE";name=r.name;code=r.code;constructor(t="Invalid type"){super(t)}};var Ge;(function(r){let t;(function(o){o.Raw="Raw",o.Directory="Directory",o.File="File",o.Metadata="Metadata",o.Symlink="Symlink",o.HAMTShard="HAMTShard"})(t=r.DataType||(r.DataType={}));let e;(function(o){o[o.Raw=0]="Raw",o[o.Directory=1]="Directory",o[o.File=2]="File",o[o.Metadata=3]="Metadata",o[o.Symlink=4]="Symlink",o[o.HAMTShard=5]="HAMTShard"})(e||(e={})),function(o){o.codec=()=>dr(e)}(t=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=le((o,i,s={})=>{if(s.lengthDelimited!==!1&&i.fork(),o.Type!=null&&(i.uint32(8),r.DataType.codec().encode(o.Type,i)),o.Data!=null&&(i.uint32(18),i.bytes(o.Data)),o.filesize!=null&&(i.uint32(24),i.uint64(o.filesize)),o.blocksizes!=null)for(let a of o.blocksizes)i.uint32(32),i.uint64(a);o.hashType!=null&&(i.uint32(40),i.uint64(o.hashType)),o.fanout!=null&&(i.uint32(48),i.uint64(o.fanout)),o.mode!=null&&(i.uint32(56),i.uint32(o.mode)),o.mtime!=null&&(i.uint32(66),vl.codec().encode(o.mtime,i)),s.lengthDelimited!==!1&&i.ldelim()},(o,i)=>{let s={blocksizes:[]},a=i==null?o.len:o.pos+i;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:s.Type=r.DataType.codec().decode(o);break;case 2:s.Data=o.bytes();break;case 3:s.filesize=o.uint64();break;case 4:s.blocksizes.push(o.uint64());break;case 5:s.hashType=o.uint64();break;case 6:s.fanout=o.uint64();break;case 7:s.mode=o.uint32();break;case 8:s.mtime=vl.codec().decode(o,o.uint32());break;default:o.skipType(c&7);break}}return s})),n),r.encode=o=>ce(o,r.codec()),r.decode=o=>ie(o,r.codec())})(Ge||(Ge={}));var vl;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Seconds!=null&&(n.uint32(8),n.int64(e.Seconds)),e.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(e.FractionalNanoseconds)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let s=e.uint32();switch(s>>>3){case 1:o.Seconds=e.int64();break;case 2:o.FractionalNanoseconds=e.fixed32();break;default:e.skipType(s&7);break}}return o})),t),r.encode=e=>ce(e,r.codec()),r.decode=e=>ie(e,r.codec())})(vl||(vl={}));var Sw;(function(r){let t;r.codec=()=>(t==null&&(t=le((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.MimeType!=null&&(n.uint32(10),n.string(e.MimeType)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let s=e.uint32();switch(s>>>3){case 1:o.MimeType=e.string();break;default:e.skipType(s&7);break}}return o})),t),r.encode=e=>ce(e,r.codec()),r.decode=e=>ie(e,r.codec())})(Sw||(Sw={}));var Aw={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},hI=["directory","hamt-sharded-directory"],Iw=parseInt("0644",8),kw=parseInt("0755",8),cr=class r{static unmarshal(t){let e=Ge.decode(t),n=new r({type:Aw[e.Type!=null?e.Type.toString():"File"],data:e.Data,blockSizes:e.blocksizes,mode:e.mode,mtime:e.mtime!=null?{secs:e.mtime.Seconds??0n,nsecs:e.mtime.FractionalNanoseconds}:void 0,fanout:e.fanout});return n._originalMode=e.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(t={type:"file"}){let{type:e,data:n,blockSizes:o,hashType:i,fanout:s,mtime:a,mode:c}=t;if(e!=null&&!Object.values(Aw).includes(e))throw new ns("Type: "+e+" is not valid");this.type=e??"file",this.data=n,this.hashType=i,this.fanout=s,this.blockSizes=o??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(t){t==null?this._mode=this.isDirectory()?kw:Iw:this._mode=t&4095}get mode(){return this._mode}isDirectory(){return hI.includes(this.type)}addBlockSize(t){this.blockSizes.push(t)}removeBlockSize(t){this.blockSizes.splice(t,1)}fileSize(){if(this.isDirectory())return 0n;let t=0n;return this.blockSizes.forEach(e=>{t+=e}),this.data!=null&&(t+=BigInt(this.data.length)),t}marshal(){let t;switch(this.type){case"raw":t=Ge.DataType.Raw;break;case"directory":t=Ge.DataType.Directory;break;case"file":t=Ge.DataType.File;break;case"metadata":t=Ge.DataType.Metadata;break;case"symlink":t=Ge.DataType.Symlink;break;case"hamt-sharded-directory":t=Ge.DataType.HAMTShard;break;default:throw new ns(`Type: ${t} is not valid`)}let e=this.data;(this.data==null||this.data.length===0)&&(e=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===Iw&&!this.isDirectory()&&(n=void 0),n===kw&&this.isDirectory()&&(n=void 0));let o;return this.mtime!=null&&(o={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Ge.encode({Type:t,Data:e,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:o})}};var Sl=Ot(yf(),1);function dI(r){let t=new Array(4);for(let e=0;e<4;e++)t[e]=r&255,r=r>>8;return new Uint8Array(t)}var NM=bn({name:"murmur3-32",code:35,encode:r=>dI(Sl.default.x86.hash32(r))}),_w=bn({name:"murmur3-128",code:34,encode:r=>yn.fromHex(Sl.default.x64.hash128(r))}),LM=bn({name:"murmur3-x64-64",code:34,encode:r=>yn.fromHex(Sl.default.x64.hash128(r)).subarray(0,8)});var Rw=Ot(Cw(),1);var Vn=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(t,e,n=0){this._options=t,this._popCount=0,this._parent=e,this._posAtParent=n,this._children=new Rw.default,this.key=null}async put(t,e){let n=await this._findNewBucketAndPos(t);n.bucket._putAt(n,t,e)}async get(t){let e=await this._findChild(t);if(e!=null)return e.value}async del(t){let e=await this._findPlace(t),n=e.bucket._at(e.pos);n!=null&&n.key===t&&e.bucket._delAt(e.pos)}leafCount(){return this._children.compactArray().reduce((e,n)=>n instanceof r?e+n.leafCount():e+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let t=this._children.compactArray();for(let e of t)e instanceof r?yield*e.eachLeafSeries():yield e}serialize(t,e){let n=[];return e(this._children.reduce((o,i,s)=>(i!=null&&(i instanceof r?o.push(i.serialize(t,e)):o.push(t(i,s))),o),n))}async asyncTransform(t,e){return Nw(this,t,e)}toJSON(){return this.serialize(wI,bI)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(t){let e=await this._findPlace(t),n=e.bucket._at(e.pos);if(!(n instanceof r)&&n!=null&&n.key===t)return n}async _findPlace(t){let e=this._options.hash(typeof t=="string"?D(t):t),n=await e.take(this._options.bits),o=this._children.get(n);return o instanceof r?o._findPlace(e):{bucket:this,pos:n,hash:e,existingChild:o}}async _findNewBucketAndPos(t){let e=await this._findPlace(t);if(e.existingChild!=null&&e.existingChild.key!==t){let n=new r(this._options,e.bucket,e.pos);e.bucket._putObjectAt(e.pos,n);let o=await n._findPlace(e.existingChild.hash);return o.bucket._putAt(o,e.existingChild.key,e.existingChild.value),n._findNewBucketAndPos(e.hash)}return e}_putAt(t,e,n){this._putObjectAt(t.pos,{key:e,value:n,hash:t.hash})}_putObjectAt(t,e){this._children.get(t)==null&&this._popCount++,this._children.set(t,e)}_delAt(t){if(t===-1)throw new Error("Invalid position");this._children.get(t)!=null&&this._popCount--,this._children.unset(t),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let t=this._children.find(yI);if(t!=null&&!(t instanceof r)){let e=t.hash;e.untake(this._options.bits);let n={pos:this._posAtParent,hash:e,bucket:this._parent};this._parent._putAt(n,t.key,t.value)}}else this._parent._delAt(this._posAtParent)}_at(t){return this._children.get(t)}};function yI(r){return!!r}function wI(r,t){return r.key}function bI(r){return r}async function Nw(r,t,e){let n=[];for(let o of r._children.compactArray())if(o instanceof Vn)await Nw(o,t,e);else{let i=await t(o);n.push({bitField:r._children.bitField(),children:i})}return e(n)}var xI=[255,254,252,248,240,224,192,128],EI=[1,3,7,15,31,63,127,255],Al=class{_value;_currentBytePos;_currentBitPos;constructor(t){this._value=t,this._currentBytePos=t.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(t){let e=t,n=0;for(;e>0&&this._haveBits();){let o=this._value[this._currentBytePos],i=this._currentBitPos+1,s=Math.min(i,e),a=vI(o,i-s,s);n=(n<<s)+a,e-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(t){for(this._currentBitPos+=t;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function vI(r,t,e){let n=SI(t,e);return(r&n)>>>t}function SI(r,t){return xI[r]&EI[Math.min(t+r-1,7)]}function Lw(r){function t(e){return e instanceof Il?e:new Il(e,r)}return t}var Il=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(t,e){if(!(t instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=t,this._hashFn=e,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(t){let e=t;for(;this._availableBits<e;)await this._produceMoreBits();let n=0;for(;e>0;){let o=this._buffers[this._currentBufferIndex],i=Math.min(o.availableBits(),e),s=o.take(i);n=(n<<i)+s,e-=i,this._availableBits-=i,o.availableBits()===0&&this._currentBufferIndex++}return n}untake(t){let e=t;for(;e>0;){let n=this._buffers[this._currentBufferIndex],o=Math.min(n.totalBits()-n.availableBits(),e);n.untake(o),e-=o,this._availableBits+=o,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let t=this._depth>0?ct([this._value,Uint8Array.from([this._depth])]):this._value,e=await this._hashFn(t),n=new Al(e);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Pw(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let t={bits:r.bits??8,hash:Lw(r.hashFn)};return new Vn(t)}var AI=async function(r){return(await _w.encode(r)).slice(0,8).reverse()},II=async(r,t,e)=>{let n=(t.tableSize()-1).toString(16).length;await Promise.all(r.map(async o=>{if(o.Name==null)throw new Error("Unexpected Link without a Name");if(o.Name.length===n){let i=parseInt(o.Name,16);t._putObjectAt(i,new Vn({hash:e._options.hash,bits:e._options.bits},t,i));return}await e.put(o.Name.substring(2),!0)}))},Dw=(r,t)=>r.toString(16).toUpperCase().padStart(t,"0").substring(0,t),kI=r=>{let t=r.bucket,e=[];for(;t._parent!=null;)e.push(t),t=t._parent;return e.push(t),e.reverse()},Ow=async(r,t,e,n,o)=>{if(n==null){if(r.Data==null)throw new Ct("no data in PBNode");let f;try{f=cr.unmarshal(r.Data)}catch(h){throw new Ct(h.message)}if(f.type!=="hamt-sharded-directory")throw new Ct("not a HAMT");if(f.fanout==null)throw new Ct("missing fanout");let d=Pw({hashFn:AI,bits:Math.log2(Number(f.fanout))});n={rootBucket:d,hamtDepth:1,lastBucket:d}}let i=(n.lastBucket.tableSize()-1).toString(16).length;await II(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(t),a=Dw(s.pos,i),c=kI(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=Dw(n.lastBucket._posAtParent,i));let l=r.Links.find(f=>{if(f.Name==null)return!1;let d=f.Name.substring(0,i),h=f.Name.substring(i);return!(d!==a||h!==""&&h!==t)});if(l==null)return;if(l.Name!=null&&l.Name.substring(i)===t)return l.Hash;n.hamtDepth++;let u=await e.get(l.Hash,o);return r=Nr(u),Ow(r,t,e,n,o)},Uw=Ow;var _I=(r,t,e,n,o,i,s)=>{async function*a(c={}){let l=c.offset??0,u=c.length??t.Links.length,f=t.Links.slice(l,u);c.onProgress?.(new H("unixfs:exporter:walk:directory",{cid:r})),yield*Ye(f,d=>zt(d,h=>async()=>{let m=h.Name??"",p=`${n}/${m}`;return(await o(h.Hash,m,p,[],i+1,s,c)).entry}),d=>Un(d,{ordered:!0,concurrency:c.blockReadConcurrency}),d=>ve(d,h=>h!=null))}return a},Fw=_I;async function Mw(r,t,e,n,o,i,s){if(t instanceof Uint8Array){let l=Mn(t,n,o,i);e.push(l);return}if(t.Data==null)throw new Ct("no data in PBNode");let a;try{a=cr.unmarshal(t.Data)}catch(l){throw new Ct(l.message)}if(a.data!=null){let l=a.data,u=Mn(l,n,o,i);e.push(u),n+=BigInt(u.byteLength)}let c=[];if(t.Links.length!==a.blockSizes.length)throw new Ct("Inconsistent block sizes and dag links");for(let l=0;l<t.Links.length;l++){let u=t.Links[l],f=n,d=f+a.blockSizes[l];if((o>=f&&o<d||i>=f&&i<=d||o<f&&i>d)&&c.push({link:u,blockStart:n}),n=d,n>i)break}await Ye(c,l=>zt(l,u=>async()=>{let f=await r.get(u.link.Hash,s);return{...u,block:f}}),l=>Un(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:u,block:f,blockStart:d}of l){let h;switch(u.Hash.code){case Te:h=Nr(f);break;case ae:h=f;break;default:e.end(new Ct(`Unsupported codec: ${u.Hash.code}`));return}let m=new de({concurrency:1});m.on("error",p=>{e.end(p)}),m.add(async()=>{s.onProgress?.(new H("unixfs:exporter:walk:file",{cid:u.Hash})),await Mw(r,h,e,d,o,i,s)}),await m.onIdle()}}),n>=i&&e.end()}var BI=(r,t,e,n,o,i,s)=>{async function*a(c={}){let l=e.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:u,end:f}=Vo(l,c.offset,c.length);if(f===0n)return;let d=0n,h=f-u,m=We();c.onProgress?.(new H("unixfs:exporter:walk:file",{cid:r})),Mw(s,t,m,0n,u,f,c).catch(p=>{m.end(p)});for await(let p of m)if(p!=null){if(d+=BigInt(p.byteLength),d>h)throw m.end(),new bl("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");d===h&&m.end(),c.onProgress?.(new H("unixfs:exporter:progress:unixfs:file",{bytesRead:d,totalBytes:h,fileSize:l})),yield p}if(d<h)throw new xl("Traversed entire DAG but did not read enough bytes")}return a},ad=BI;var TI=(r,t,e,n,o,i,s)=>{function a(c={}){return c.onProgress?.(new H("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),Vw(t,n,o,i,s,c)}return a};async function*Vw(r,t,e,n,o,i){let s=r.Links;if(r.Data==null)throw new Ct("no data in PBNode");let a;try{a=cr.unmarshal(r.Data)}catch(u){throw new Ct(u.message)}if(a.fanout==null)throw new Ct("missing fanout");let c=(a.fanout-1n).toString(16).length,l=Ye(s,u=>zt(u,f=>async()=>{let d=f.Name!=null?f.Name.substring(c):null;if(d!=null&&d!==""){let h=await e(f.Hash,d,`${t}/${d}`,[],n+1,o,i);return{entries:h.entry==null?[]:[h.entry]}}else{let h=await o.get(f.Hash,i);return r=Nr(h),i.onProgress?.(new H("unixfs:exporter:walk:hamt-sharded-directory",{cid:f.Hash})),{entries:Vw(r,t,e,n,o,i)}}}),u=>Un(u,{ordered:!0,concurrency:i.blockReadConcurrency}));for await(let{entries:u}of l)yield*u}var Hw=TI;var CI=(r,t)=>r.Links.find(n=>n.Name===t)?.Hash,RI={raw:ad,file:ad,directory:Fw,"hamt-sharded-directory":Hw,metadata:(r,t,e,n,o,i,s)=>()=>[],symlink:(r,t,e,n,o,i,s)=>()=>[]},NI=async(r,t,e,n,o,i,s,a)=>{let c=await s.get(r,a),l=Nr(c),u,f;if(t==null&&(t=r.toString()),l.Data==null)throw new Ct("no data in PBNode");try{u=cr.unmarshal(l.Data)}catch(h){throw new Ct(h.message)}if(e==null&&(e=t),n.length>0){let h;if(u?.type==="hamt-sharded-directory"?h=await Uw(l,n[0],s):h=CI(l,n[0]),h==null)throw new Re("file does not exist");let m=n.shift(),p=`${e}/${m}`;f={cid:h,toResolve:n,name:m??"",path:p}}let d=RI[u.type](r,l,u,e,o,i,s);if(d==null)throw new Re("could not find content exporter");return u.isDirectory()?{entry:{type:"directory",name:t,path:e,cid:r,content:d,unixfs:u,depth:i,node:l,size:u.fileSize()},next:f}:{entry:{type:"file",name:t,path:e,cid:r,content:d,unixfs:u,depth:i,node:l,size:u.fileSize()},next:f}},$w=NI;var LI={[Te]:$w,[ae]:vw,[Cr]:ww,[Rr]:bw,[bt.code]:xw,[hr]:Ew},zw=async(r,t,e,n,o,i,s)=>{let a=LI[r.code];if(a==null)throw new wl(`No resolver for code ${r.code}`);return a(r,t,e,n,zw,o,i,s)},qw=zw;var PI=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),DI=r=>{if(r instanceof Uint8Array)return{cid:L.decode(r),toResolve:[]};let t=L.asCID(r);if(t!=null)return{cid:t,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let e=PI(r);return{cid:L.parse(e[0]),toResolve:e.slice(1)}}throw new yl(`Unknown path type ${r}`)};async function*cd(r,t,e={}){let{cid:n,toResolve:o}=DI(r),i=n.toString(),s=i,a=o.length;for(;;){let c=await qw(n,i,s,o,a,t,e);if(c.entry==null&&c.next==null)throw new Re(`Could not resolve ${r}`);if(c.entry!=null&&(yield c.entry),c.next==null)return;o=c.next.toResolve,n=c.next.cid,i=c.next.name,s=c.next.path}}async function Ho(r,t,e={}){let n=await yw(cd(r,t,e));if(n==null)throw new Re(`Could not resolve ${r}`);return n}async function*Kw(r,t,e={}){let n=await Ho(r,t,e);if(n==null)return;if(yield n,n.type==="directory")for await(let i of o(n,e))yield i;async function*o(i,s){for await(let a of i.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*o(a,s))}}function Gw(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function kl(r,t={}){let e=Gw(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(o){try{let{value:i,done:s}=await e.next();if(this._cancelled)return;if(s===!0){o.close();return}o.enqueue(i)}catch(i){o.error(i)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,t)}var $o=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,jw=new Set,ld=typeof process=="object"&&process?process:{},Yw=(r,t,e,n)=>{typeof ld.emitWarning=="function"?ld.emitWarning(r,t,e,n):console.error(`[${e}] ${t}: ${r}`)},_l=globalThis.AbortController,Ww=globalThis.AbortSignal;if(typeof _l>"u"){Ww=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,o){this._onabort.push(o)}},_l=class{constructor(){t()}signal=new Ww;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let o of this.signal._onabort)o(n);this.signal.onabort?.(n)}}};let r=ld.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{r&&(r=!1,Yw("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var OI=r=>!jw.has(r),ZV=Symbol("type"),hn=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),Xw=r=>hn(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?zo:null:null,zo=class extends Array{constructor(t){super(t),this.fill(0)}},ud=class r{heap;length;static#t=!1;static create(t){let e=Xw(t);if(!e)return[];r.#t=!0;let n=new r(t,e);return r.#t=!1,n}constructor(t,e){if(!r.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},Bl=class r{#t;#r;#a;#c;#g;#S;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#y;#n;#i;#e;#h;#l;#d;#u;#b;#f;#x;#E;#m;#w;#A;#p;static unsafeExposeInternals(t){return{starts:t.#E,ttls:t.#m,sizes:t.#x,keyMap:t.#n,keyList:t.#i,valList:t.#e,next:t.#h,prev:t.#l,get head(){return t.#d},get tail(){return t.#u},free:t.#b,isBackgroundFetch:e=>t.#s(e),backgroundFetch:(e,n,o,i)=>t.#D(e,n,o,i),moveToTail:e=>t.#N(e),indexes:e=>t.#k(e),rindexes:e=>t.#_(e),isStale:e=>t.#v(e)}}get max(){return this.#t}get maxSize(){return this.#r}get calculatedSize(){return this.#y}get size(){return this.#o}get fetchMethod(){return this.#g}get memoMethod(){return this.#S}get dispose(){return this.#a}get disposeAfter(){return this.#c}constructor(t){let{max:e=0,ttl:n,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:s,updateAgeOnHas:a,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:f,noUpdateTTL:d,maxSize:h=0,maxEntrySize:m=0,sizeCalculation:p,fetchMethod:y,memoMethod:g,noDeleteOnFetchRejection:x,noDeleteOnStaleGet:b,allowStaleOnFetchRejection:E,allowStaleOnFetchAbort:k,ignoreFetchAbort:T}=t;if(e!==0&&!hn(e))throw new TypeError("max option must be a nonnegative integer");let S=e?Xw(e):Array;if(!S)throw new Error("invalid max value: "+e);if(this.#t=e,this.#r=h,this.maxEntrySize=m||this.#r,this.sizeCalculation=p,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(g!==void 0&&typeof g!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#S=g,y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#g=y,this.#A=!!y,this.#n=new Map,this.#i=new Array(e).fill(void 0),this.#e=new Array(e).fill(void 0),this.#h=new S(e),this.#l=new S(e),this.#d=0,this.#u=0,this.#b=ud.create(e),this.#o=0,this.#y=0,typeof l=="function"&&(this.#a=l),typeof u=="function"?(this.#c=u,this.#f=[]):(this.#c=void 0,this.#f=void 0),this.#w=!!this.#a,this.#p=!!this.#c,this.noDisposeOnSet=!!f,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!x,this.allowStaleOnFetchRejection=!!E,this.allowStaleOnFetchAbort=!!k,this.ignoreFetchAbort=!!T,this.maxEntrySize!==0){if(this.#r!==0&&!hn(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!hn(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#H()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!b,this.updateAgeOnGet=!!s,this.updateAgeOnHas=!!a,this.ttlResolution=hn(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!hn(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#C()}if(this.#t===0&&this.ttl===0&&this.#r===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#r){let v="LRU_CACHE_UNBOUNDED";OI(v)&&(jw.add(v),Yw("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",v,r))}}getRemainingTTL(t){return this.#n.has(t)?1/0:0}#C(){let t=new zo(this.#t),e=new zo(this.#t);this.#m=t,this.#E=e,this.#O=(i,s,a=$o.now())=>{if(e[i]=s!==0?a:0,t[i]=s,s!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#v(i)&&this.#B(this.#i[i],"expire")},s+1);c.unref&&c.unref()}},this.#I=i=>{e[i]=t[i]!==0?$o.now():0},this.#T=(i,s)=>{if(t[s]){let a=t[s],c=e[s];if(!a||!c)return;i.ttl=a,i.start=c,i.now=n||o();let l=i.now-c;i.remainingTTL=a-l}};let n=0,o=()=>{let i=$o.now();if(this.ttlResolution>0){n=i;let s=setTimeout(()=>n=0,this.ttlResolution);s.unref&&s.unref()}return i};this.getRemainingTTL=i=>{let s=this.#n.get(i);if(s===void 0)return 0;let a=t[s],c=e[s];if(!a||!c)return 1/0;let l=(n||o())-c;return a-l},this.#v=i=>{let s=e[i],a=t[i];return!!a&&!!s&&(n||o())-s>a}}#I=()=>{};#T=()=>{};#O=()=>{};#v=()=>!1;#H(){let t=new zo(this.#t);this.#y=0,this.#x=t,this.#R=e=>{this.#y-=t[e],t[e]=0},this.#U=(e,n,o,i)=>{if(this.#s(n))return 0;if(!hn(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(n,e),!hn(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#L=(e,n,o)=>{if(t[e]=n,this.#r){let i=this.#r-t[e];for(;this.#y>i;)this.#P(!0)}this.#y+=t[e],o&&(o.entrySize=n,o.totalCalculatedSize=this.#y)}}#R=t=>{};#L=(t,e,n)=>{};#U=(t,e,n,o)=>{if(n||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:t=this.allowStale}={}){if(this.#o)for(let e=this.#u;!(!this.#F(e)||((t||!this.#v(e))&&(yield e),e===this.#d));)e=this.#l[e]}*#_({allowStale:t=this.allowStale}={}){if(this.#o)for(let e=this.#d;!(!this.#F(e)||((t||!this.#v(e))&&(yield e),e===this.#u));)e=this.#h[e]}#F(t){return t!==void 0&&this.#n.get(this.#i[t])===t}*entries(){for(let t of this.#k())this.#e[t]!==void 0&&this.#i[t]!==void 0&&!this.#s(this.#e[t])&&(yield[this.#i[t],this.#e[t]])}*rentries(){for(let t of this.#_())this.#e[t]!==void 0&&this.#i[t]!==void 0&&!this.#s(this.#e[t])&&(yield[this.#i[t],this.#e[t]])}*keys(){for(let t of this.#k()){let e=this.#i[t];e!==void 0&&!this.#s(this.#e[t])&&(yield e)}}*rkeys(){for(let t of this.#_()){let e=this.#i[t];e!==void 0&&!this.#s(this.#e[t])&&(yield e)}}*values(){for(let t of this.#k())this.#e[t]!==void 0&&!this.#s(this.#e[t])&&(yield this.#e[t])}*rvalues(){for(let t of this.#_())this.#e[t]!==void 0&&!this.#s(this.#e[t])&&(yield this.#e[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let n of this.#k()){let o=this.#e[n],i=this.#s(o)?o.__staleWhileFetching:o;if(i!==void 0&&t(i,this.#i[n],this))return this.get(this.#i[n],e)}}forEach(t,e=this){for(let n of this.#k()){let o=this.#e[n],i=this.#s(o)?o.__staleWhileFetching:o;i!==void 0&&t.call(e,i,this.#i[n],this)}}rforEach(t,e=this){for(let n of this.#_()){let o=this.#e[n],i=this.#s(o)?o.__staleWhileFetching:o;i!==void 0&&t.call(e,i,this.#i[n],this)}}purgeStale(){let t=!1;for(let e of this.#_({allowStale:!0}))this.#v(e)&&(this.#B(this.#i[e],"expire"),t=!0);return t}info(t){let e=this.#n.get(t);if(e===void 0)return;let n=this.#e[e],o=this.#s(n)?n.__staleWhileFetching:n;if(o===void 0)return;let i={value:o};if(this.#m&&this.#E){let s=this.#m[e],a=this.#E[e];if(s&&a){let c=s-($o.now()-a);i.ttl=c,i.start=Date.now()}}return this.#x&&(i.size=this.#x[e]),i}dump(){let t=[];for(let e of this.#k({allowStale:!0})){let n=this.#i[e],o=this.#e[e],i=this.#s(o)?o.__staleWhileFetching:o;if(i===void 0||n===void 0)continue;let s={value:i};if(this.#m&&this.#E){s.ttl=this.#m[e];let a=$o.now()-this.#E[e];s.start=Math.floor(Date.now()-a)}this.#x&&(s.size=this.#x[e]),t.unshift([n,s])}return t}load(t){this.clear();for(let[e,n]of t){if(n.start){let o=Date.now()-n.start;n.start=$o.now()-o}this.set(e,n.value,n)}}set(t,e,n={}){if(e===void 0)return this.delete(t),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:s=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=n,{noUpdateTTL:l=this.noUpdateTTL}=n,u=this.#U(t,e,n.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#B(t,"set"),this;let f=this.#o===0?void 0:this.#n.get(t);if(f===void 0)f=this.#o===0?this.#u:this.#b.length!==0?this.#b.pop():this.#o===this.#t?this.#P(!1):this.#o,this.#i[f]=t,this.#e[f]=e,this.#n.set(t,f),this.#h[this.#u]=f,this.#l[f]=this.#u,this.#u=f,this.#o++,this.#L(f,u,c),c&&(c.set="add"),l=!1;else{this.#N(f);let d=this.#e[f];if(e!==d){if(this.#A&&this.#s(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:h}=d;h!==void 0&&!s&&(this.#w&&this.#a?.(h,t,"set"),this.#p&&this.#f?.push([h,t,"set"]))}else s||(this.#w&&this.#a?.(d,t,"set"),this.#p&&this.#f?.push([d,t,"set"]));if(this.#R(f),this.#L(f,u,c),this.#e[f]=e,c){c.set="replace";let h=d&&this.#s(d)?d.__staleWhileFetching:d;h!==void 0&&(c.oldValue=h)}}else c&&(c.set="update")}if(o!==0&&!this.#m&&this.#C(),this.#m&&(l||this.#O(f,o,i),c&&this.#T(c,f)),!s&&this.#p&&this.#f){let d=this.#f,h;for(;h=d?.shift();)this.#c?.(...h)}return this}pop(){try{for(;this.#o;){let t=this.#e[this.#d];if(this.#P(!0),this.#s(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#p&&this.#f){let t=this.#f,e;for(;e=t?.shift();)this.#c?.(...e)}}}#P(t){let e=this.#d,n=this.#i[e],o=this.#e[e];return this.#A&&this.#s(o)?o.__abortController.abort(new Error("evicted")):(this.#w||this.#p)&&(this.#w&&this.#a?.(o,n,"evict"),this.#p&&this.#f?.push([o,n,"evict"])),this.#R(e),t&&(this.#i[e]=void 0,this.#e[e]=void 0,this.#b.push(e)),this.#o===1?(this.#d=this.#u=0,this.#b.length=0):this.#d=this.#h[e],this.#n.delete(n),this.#o--,e}has(t,e={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:o}=e,i=this.#n.get(t);if(i!==void 0){let s=this.#e[i];if(this.#s(s)&&s.__staleWhileFetching===void 0)return!1;if(this.#v(i))o&&(o.has="stale",this.#T(o,i));else return n&&this.#I(i),o&&(o.has="hit",this.#T(o,i)),!0}else o&&(o.has="miss");return!1}peek(t,e={}){let{allowStale:n=this.allowStale}=e,o=this.#n.get(t);if(o===void 0||!n&&this.#v(o))return;let i=this.#e[o];return this.#s(i)?i.__staleWhileFetching:i}#D(t,e,n,o){let i=e===void 0?void 0:this.#e[e];if(this.#s(i))return i;let s=new _l,{signal:a}=n;a?.addEventListener("abort",()=>s.abort(a.reason),{signal:s.signal});let c={signal:s.signal,options:n,context:o},l=(p,y=!1)=>{let{aborted:g}=s.signal,x=n.ignoreFetchAbort&&p!==void 0;if(n.status&&(g&&!y?(n.status.fetchAborted=!0,n.status.fetchError=s.signal.reason,x&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),g&&!x&&!y)return f(s.signal.reason);let b=h;return this.#e[e]===h&&(p===void 0?b.__staleWhileFetching?this.#e[e]=b.__staleWhileFetching:this.#B(t,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(t,p,c.options))),p},u=p=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=p),f(p)),f=p=>{let{aborted:y}=s.signal,g=y&&n.allowStaleOnFetchAbort,x=g||n.allowStaleOnFetchRejection,b=x||n.noDeleteOnFetchRejection,E=h;if(this.#e[e]===h&&(!b||E.__staleWhileFetching===void 0?this.#B(t,"fetch"):g||(this.#e[e]=E.__staleWhileFetching)),x)return n.status&&E.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),E.__staleWhileFetching;if(E.__returned===E)throw p},d=(p,y)=>{let g=this.#g?.(t,i,c);g&&g instanceof Promise&&g.then(x=>p(x===void 0?void 0:x),y),s.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(p(void 0),n.allowStaleOnFetchAbort&&(p=x=>l(x,!0)))})};n.status&&(n.status.fetchDispatched=!0);let h=new Promise(d).then(l,u),m=Object.assign(h,{__abortController:s,__staleWhileFetching:i,__returned:void 0});return e===void 0?(this.set(t,m,{...c.options,status:void 0}),e=this.#n.get(t)):this.#e[e]=m,m}#s(t){if(!this.#A)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof _l}async fetch(t,e={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:s=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:f=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:p,forceRefresh:y=!1,status:g,signal:x}=e;if(!this.#A)return g&&(g.fetch="get"),this.get(t,{allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:g});let b={allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:s,noDisposeOnSet:a,size:c,sizeCalculation:l,noUpdateTTL:u,noDeleteOnFetchRejection:f,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:m,ignoreFetchAbort:h,status:g,signal:x},E=this.#n.get(t);if(E===void 0){g&&(g.fetch="miss");let k=this.#D(t,E,b,p);return k.__returned=k}else{let k=this.#e[E];if(this.#s(k)){let z=n&&k.__staleWhileFetching!==void 0;return g&&(g.fetch="inflight",z&&(g.returnedStale=!0)),z?k.__staleWhileFetching:k.__returned=k}let T=this.#v(E);if(!y&&!T)return g&&(g.fetch="hit"),this.#N(E),o&&this.#I(E),g&&this.#T(g,E),k;let S=this.#D(t,E,b,p),_=S.__staleWhileFetching!==void 0&&n;return g&&(g.fetch=T?"stale":"refresh",_&&T&&(g.returnedStale=!0)),_?S.__staleWhileFetching:S.__returned=S}}async forceFetch(t,e={}){let n=await this.fetch(t,e);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(t,e={}){let n=this.#S;if(!n)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:i,...s}=e,a=this.get(t,s);if(!i&&a!==void 0)return a;let c=n(t,a,{options:s,context:o});return this.set(t,c,s),c}get(t,e={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:s}=e,a=this.#n.get(t);if(a!==void 0){let c=this.#e[a],l=this.#s(c);return s&&this.#T(s,a),this.#v(a)?(s&&(s.get="stale"),l?(s&&n&&c.__staleWhileFetching!==void 0&&(s.returnedStale=!0),n?c.__staleWhileFetching:void 0):(i||this.#B(t,"expire"),s&&n&&(s.returnedStale=!0),n?c:void 0)):(s&&(s.get="hit"),l?c.__staleWhileFetching:(this.#N(a),o&&this.#I(a),c))}else s&&(s.get="miss")}#M(t,e){this.#l[e]=t,this.#h[t]=e}#N(t){t!==this.#u&&(t===this.#d?this.#d=this.#h[t]:this.#M(this.#l[t],this.#h[t]),this.#M(this.#u,t),this.#u=t)}delete(t){return this.#B(t,"delete")}#B(t,e){let n=!1;if(this.#o!==0){let o=this.#n.get(t);if(o!==void 0)if(n=!0,this.#o===1)this.#V(e);else{this.#R(o);let i=this.#e[o];if(this.#s(i)?i.__abortController.abort(new Error("deleted")):(this.#w||this.#p)&&(this.#w&&this.#a?.(i,t,e),this.#p&&this.#f?.push([i,t,e])),this.#n.delete(t),this.#i[o]=void 0,this.#e[o]=void 0,o===this.#u)this.#u=this.#l[o];else if(o===this.#d)this.#d=this.#h[o];else{let s=this.#l[o];this.#h[s]=this.#h[o];let a=this.#h[o];this.#l[a]=this.#l[o]}this.#o--,this.#b.push(o)}}if(this.#p&&this.#f?.length){let o=this.#f,i;for(;i=o?.shift();)this.#c?.(...i)}return n}clear(){return this.#V("delete")}#V(t){for(let e of this.#_({allowStale:!0})){let n=this.#e[e];if(this.#s(n))n.__abortController.abort(new Error("deleted"));else{let o=this.#i[e];this.#w&&this.#a?.(n,o,t),this.#p&&this.#f?.push([n,o,t])}}if(this.#n.clear(),this.#e.fill(void 0),this.#i.fill(void 0),this.#m&&this.#E&&(this.#m.fill(0),this.#E.fill(0)),this.#x&&this.#x.fill(0),this.#d=0,this.#u=0,this.#b.length=0,this.#y=0,this.#o=0,this.#p&&this.#f){let e=this.#f,n;for(;n=e?.shift();)this.#c?.(...n)}}};var Se=class extends Error{static name="InvalidRangeError";constructor(t="Invalid range request"){super(t),this.name="InvalidRangeError"}},Tl=class extends Error{static name="NoContentError";constructor(t="No content found"){super(t),this.name="NoContentError"}},Cl=class extends Error{static name="SubdomainNotSupportedError";constructor(t="Subdomain not supported"){super(t),this.name="SubdomainNotSupportedError"}};function Zw(r,t){if(r==null)return;if(r instanceof Headers)return r.get(t)??void 0;if(Array.isArray(r))return r.find(([o])=>o.toLowerCase()===t.toLowerCase())?.[1];let e=Object.keys(r).find(n=>n.toLowerCase()===t.toLowerCase());if(e!=null)return r[e]}function Jw(r,t,e){if((r??0)>(t??1/0))throw new Se("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(t??0)>=(e??1/0))throw new Se("Invalid range: Range-end index is greater than or equal to the size of the file.");if(r==null&&(t??0)>(e??1/0))throw new Se("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new Se("Invalid range: Range-start index cannot be negative.");if(r!=null&&t!=null)return{byteSize:t-r+1,start:r,end:t};if(r==null&&t!=null)return e==null?{end:t}:t===e?{byteSize:e,start:0,end:e-1}:{byteSize:t,start:e-t,end:e-1};if(r!=null&&t==null){if(e==null)return{start:r};let n=e-1;return{byteSize:e-r,start:r,end:n}}return{byteSize:e,start:0,end:e!=null?e-1:0}}function Qw({ttl:r,protocol:t,response:e}){let n;t==="ipfs"?n="public, max-age=29030400, immutable":r==null?n="public, max-age=300":n=`public, max-age=${r}`,e.headers.set("cache-control",n)}function tb({byteStart:r,byteEnd:t,byteSize:e}){let n=e??"*";if((t??0)>=(e??1/0))throw new Se("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(e??1/0))throw new Se("Invalid range: Range-start index is greater than or equal to the size of the file.");if(r!=null&&t==null)return e==null?`bytes */${n}`:`bytes ${r}-${e-1}/${e}`;if(r==null&&t!=null){if(e==null)return`bytes */${n}`;let o=e-1;return`bytes ${o-t+1}-${o}/${e}`}return r==null&&t==null?`bytes */${n}`:`bytes ${r}-${t}/${n}`}function fd(r,t){t!=null&&r.headers.set("X-Ipfs-Roots",t.map(e=>e.toV1().toString()).join(","))}function UI(r){return typeof r=="string"?r.length:r instanceof ArrayBuffer||r instanceof Uint8Array?r.byteLength:r instanceof Blob?r.size:(r instanceof ReadableStream,null)}function FI(r){let t=r.match(/^bytes=(?<start>\d+)?-(?<end>\d+)?$/);if(t?.groups==null)throw new Se("Invalid range request");let{start:e,end:n}=t.groups;return{start:e,end:n}}var os=class{headers;isRangeRequest;_fileSize;_body=null;rangeRequestHeader;log;requestRangeStart;requestRangeEnd;byteStart;byteEnd;byteSize;constructor(t,e){if(this.headers=e,this.log=t.forComponent("helia:verified-fetch:byte-range-context"),this.rangeRequestHeader=Zw(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{start:n,end:o}=FI(this.rangeRequestHeader);this.requestRangeStart=n!=null?parseInt(n):null,this.requestRangeEnd=o!=null?parseInt(o):null}catch(n){this.log.error("error parsing range request header: %o",n),this.requestRangeStart=null,this.requestRangeEnd=null}this.setOffsetDetails()}else this.log.trace("no range request detected"),this.isRangeRequest=!1,this.requestRangeStart=null,this.requestRangeEnd=null}setBody(t){this._body=t,this.setFileSize(this._fileSize??UI(t)),this.log.trace("set request body with fileSize %o",this._fileSize)}getBody(){let t=this._body;if(t==null)return this.log.trace("body is null"),t;if(!this.isRangeRequest||!this.isValidRangeRequest)return this.log.trace("returning body unmodified for non-range, or invalid range, request"),t;let e=this.byteStart,n=this.byteEnd,o=this.byteSize;return e!=null||n!=null?(this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",e,n,o),t instanceof ReadableStream?t:this.getSlicedBody(t)):(this.log.error("returning unmodified body for valid range request"),t)}getSlicedBody(t){let e=this.byteStart??0,n=this.byteEnd==null?void 0:this.byteEnd+1;return this.log.trace("returning body with offset %o and length %o",e,n),t.slice(e,n)}setFileSize(t){this._fileSize=t!=null?Number(t):null,this.log.trace("set _fileSize to %o",this._fileSize),this.setOffsetDetails()}getFileSize(){return this._fileSize}isValidByteStart(){return!(this.byteStart!=null&&(this.byteStart<0||this._fileSize!=null&&this.byteStart>=this._fileSize||this.byteEnd!=null&&this.byteStart>this.byteEnd))}isValidByteEnd(){return!(this.byteEnd!=null&&(this.byteEnd<0||this._fileSize!=null&&this.byteEnd>=this._fileSize||this.byteStart!=null&&this.byteEnd<this.byteStart))}get isValidRangeRequest(){if(!this.isRangeRequest)return!1;if(this.requestRangeStart==null&&this.requestRangeEnd==null)return this.log.trace("invalid range request, range request values not provided"),!1;if(!this.isValidByteStart())return this.log.trace("invalid range request, byteStart is less than 0 or greater than fileSize"),!1;if(!this.isValidByteEnd())return this.log.trace("invalid range request, byteEnd is less than 0 or greater than fileSize"),!1;if(this.requestRangeEnd!=null&&this.requestRangeStart!=null){if(this.requestRangeStart>this.requestRangeEnd)return this.log.trace("invalid range request, start is greater than end"),!1;if(this.requestRangeStart<0)return this.log.trace("invalid range request, start is less than 0"),!1;if(this.requestRangeEnd<0)return this.log.trace("invalid range request, end is less than 0"),!1}return this.byteEnd==null&&this.byteStart==null&&this.byteSize==null?(this.log.trace("invalid range request, could not calculate byteStart, byteEnd, or byteSize"),!1):!0}get offset(){return this.byteStart??0}get length(){return this.byteEnd!=null&&this.byteStart!=null&&this.byteStart===this.byteEnd?1:this.byteEnd!=null?this.byteEnd+1:this.byteSize!=null?this.byteSize-1:void 0}setOffsetDetails(){if(this.requestRangeStart==null&&this.requestRangeEnd==null){this.log.trace("requestRangeStart and requestRangeEnd are null");return}try{let{start:t,end:e,byteSize:n}=Jw(this.requestRangeStart??void 0,this.requestRangeEnd??void 0,this._fileSize??void 0);this.log.trace("set byteStart to %o, byteEnd to %o, byteSize to %o",t,e,n),this.byteStart=t,this.byteEnd=e,this.byteSize=n}catch(t){this.log.error("error setting offset details: %o",t),this.byteStart=void 0,this.byteEnd=void 0,this.byteSize=void 0}}get contentRangeHeaderValue(){if(!this.isValidRangeRequest)throw this.log.error("cannot get contentRangeHeaderValue for invalid range request"),new Se("Invalid range request");return tb({byteStart:this.byteStart,byteEnd:this.byteEnd,byteSize:this._fileSize??void 0})}};function eb(r){let t=Vt(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(Ni(t))}function rb(r){let t=MI(r);return t===r?`filename="${r}"`:`filename="${t}"; filename*=UTF-8''${encodeURIComponent(r)}`}function MI(r){return r.replace(/[^\x00-\x7F]/g,"_")}function nb({cid:r,reqFormat:t,weak:e,rangeStart:n,rangeEnd:o}){let i=e===!0?"W/":"",s=t==null?"":`.${t}`;return(n!=null||o!=null)&&(s+=`.${n??"0"}-${o??"N"}`),`${i}"${r.toString()}${s}"`}var VI={[Cr]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Rr]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[hr]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Te]:["application/octet-stream","application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car","application/x-tar"],[ae]:["application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.dag-json","application/vnd.ipld.car","application/x-tar"]};function ob(r,t){let e=VI[r.code];if(t!=null)return HI(t,e)}function HI(r,t){let e=r.split(",").map(n=>{let o=n.trim().split(";");return{mimeType:`${o[0]}`.trim(),weight:$I(o[1])}}).sort((n,o)=>n.weight===o.weight?0:n.weight>o.weight?-1:1).map(n=>n.mimeType);for(let n of e)for(let o of t)if(n.includes(o)||n==="*/*"||n.startsWith("*/")&&o.split("/")[1]===n.split("/")[1]||n.endsWith("/*")&&o.split("/")[0]===n.split("/")[0])return o}function $I(r){if(r!=null&&(r=r.trim()),r?.startsWith("q=")!==!0)return 1;let t=parseFloat(r.replace("q=",""));return isNaN(t)?0:t}var Rl={raw:"application/vnd.ipld.raw",car:"application/vnd.ipld.car","dag-json":"application/vnd.ipld.dag-json","dag-cbor":"application/vnd.ipld.dag-cbor",json:"application/json",cbor:"application/cbor","ipns-record":"application/vnd.ipfs.ipns-record",tar:"application/x-tar"};function ib(r){if(r!=null)return Rl[r]}function hd(r){let t=r.get("accept");return!!(t!=null&&Object.values(Rl).includes(t))}function dd(r){let t=r?.format;return!!(t!=null&&Object.keys(Rl).includes(t))}function sb({query:r,headers:t}){return hd(t)||dd(r)}function ab({query:r,headers:t,logger:e}){let n=e.forComponent("helia:verified-fetch:get-resolved-accept-header"),o=new Headers(t),i=o.get("accept")??void 0;if(i!=null&&n('incoming accept header "%s"',i),!sb({query:r,headers:o}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",i),i;let s=ib(r?.format);r?.format!=null&&n('incoming query format "%s", mapped to %s',r.format,s);let a=i;return!hd(o)&&dd(r)&&(n("accept header not recognized, but query format provided, setting accept header to %s",s),a=s),n('resolved accept header to "%s"',a),a}async function cb(r,t,e,n){let o=e.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),i=r[Symbol.asyncIterator](),{value:s,done:a}=await i.next();if(a===!0)throw o.error("no content found for path",t),new Tl;return{stream:new ReadableStream({async start(l){n?.onProgress?.(new H("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:u,done:f}=await i.next();if(n?.signal?.aborted===!0){l.error(new Ne(n.signal.reason??"signal aborted by user")),l.close();return}if(f===!0){u!=null&&(n?.onProgress?.(new H("verified-fetch:request:progress:chunk")),l.enqueue(u)),l.close();return}n?.onProgress?.(new H("verified-fetch:request:progress:chunk")),l.enqueue(u)}}),firstChunk:s}}var Nl=class extends Error{name;code;constructor(t,e,n){super(t),this.name=e,this.code=n}},is=class extends Nl{constructor(t="not a Unixfs node"){super(t,"NotUnixFSError","ERR_NOT_UNIXFS")}};var Ll=class extends Nl{constructor(t="path does not exist"){super(t,"DoesNotExistError","ERR_DOES_NOT_EXIST")}};var P9=D("ustar\0","binary"),D9=D("ustar ","binary"),O9=D(" \0","binary");var db=Ot(ub(),1);function qI(r){return r[Symbol.asyncIterator]!=null}function KI(r){if(qI(r))return(async()=>{let n=new Uint8Array(0);for await(let o of r)n=ct([n,o],n.length+o.length);return n})();let t=[],e=0;for(let n of r)t.push(n),e+=n.byteLength;return ct(t,e)}var fb=KI;var GI="0000000000000000000",WI="7777777777777777777",jI=48,YI=D("ustar\0","binary"),XI=D("00","binary"),ZI=parseInt("7777",8),JI=257,QI=263,tk=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},ek=function(r){let t=256;for(let e=0;e<148;e++)t+=r[e];for(let e=156;e<512;e++)t+=r[e];return t},dn=function(r,t){let e=r.toString(8);return e.length>t?D(WI.slice(0,t)+" "):D(GI.slice(0,t-e.length)+e+" ")},pd=function(r){let t=D(r).byteLength,e=Math.floor(Math.log(t)/Math.log(10))+1;return t+e>=Math.pow(10,e)&&e++,`${t+e}${r}`};function hb(r){let t="";r.name!=null&&(t+=pd(" path="+r.name+`
19
+ `)),r.linkname!=null&&(t+=pd(" linkpath="+r.linkname+`
20
+ `));let e=r.pax;if(e!=null)for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t+=pd(" "+n+"="+e[n]+`
21
+ `));return D(t)}function Pl(r){let t=new Uint8Array(512),e=r.name,n="";if(r.typeflag===5&&e[e.length-1]!=="/"&&(e+="/"),D(e).byteLength!==e.length)return null;for(;D(e).byteLength>100;){let o=e.indexOf("/");if(o===-1)return null;n+=n!==""?"/"+e.slice(0,o):e.slice(0,o),e=e.slice(o+1)}return D(e).byteLength>100||D(n).byteLength>155||r.linkname!=null&&D(r.linkname).byteLength>100?null:(t.set(D(e),0),t.set(dn(r.mode&ZI,6),100),t.set(dn(r.uid,6),108),t.set(dn(r.gid,6),116),t.set(dn(r.size,11),124),t.set(dn(r.mtime.getTime()/1e3|0,11),136),t[156]=jI+tk(r.type),r.linkname!=null&&t.set(D(r.linkname),157),t.set(YI,JI),t.set(XI,QI),r.uname!=null&&t.set(D(r.uname),265),r.gname!=null&&t.set(D(r.gname),297),t.set(dn(r.devmajor??0,6),329),t.set(dn(r.devminor??0,6),337),n!=null&&t.set(D(n),345),t.set(dn(ek(t),6),148),t)}var{S_IFMT:nk,S_IFBLK:ok,S_IFCHR:ik,S_IFDIR:sk,S_IFIFO:ak,S_IFLNK:ck}=db.default,lk=parseInt("755",8),uk=parseInt("644",8),pb=new Uint8Array(1024);function fk(r=0){switch(r&nk){case ok:return"block-device";case ik:return"character-device";case sk:return"directory";case ak:return"fifo";case ck:return"symlink";default:return"file"}}function gd(r){return r&=511,r!==0?pb.subarray(0,512-r):new Uint8Array(0)}function md(r){if(r.pax==null){let t=Pl(r);if(t!=null)return t}return hk(r)}function hk(r){let t=hb(r),e={name:"PaxHeader",mode:r.mode,uid:r.uid,gid:r.gid,size:t.length,mtime:r.mtime,type:"pax-header",linkname:r.linkname,uname:r.uname,gname:r.gname,devmajor:r.devmajor,devminor:r.devminor};return new fr(Pl(e)??new Uint8Array(0),t,gd(t.length),Pl({...e,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function Dl(){return async function*(r){for await(let{header:t,body:e}of r){let n={...t,size:t.type==="symlink"?0:t.size??0,type:t.type??fk(t.mode),mode:t.mode??(t.type==="directory"?lk:uk),uid:t.uid??0,gid:t.gid??0,mtime:t.mtime??new Date};if(typeof e=="string"&&(e=D(e)),e instanceof Uint8Array||je(e)){n.size=e.length,yield md(n),yield je(e)?e.subarray():e,yield gd(n.size);continue}if(n.type==="symlink"&&n.linkname==null){if(e==null)throw new Error("type was symlink but no linkname or body specified");n.linkname=q(await fb(e)),yield md(n);continue}if(yield md(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let o=0;for await(let i of e??[])o+=i.length,yield je(i)?i.subarray():i;if(o!==n.size)throw new Error(`size mismatch, wrote ${o} of ${n.size} bytes`);yield gd(n.size)}yield pb}}var dk=["file","raw","directory"];function pk(r){let t,e;return(r.type==="file"||r.type==="directory")&&(t=r.unixfs.mode,e=r.unixfs.mtime!=null?new Date(Number(r.unixfs.mtime.secs*1000n)):void 0),{name:r.path,mode:t,mtime:e,size:Number(r.size),type:r.type==="directory"?"directory":"file"}}function mb(r){if(!dk.includes(r.type))throw new is(`${r.type} is not a UnixFS node`);let t={header:pk(r)};return(r.type==="file"||r.type==="raw")&&(t.body=r.content()),t}async function*gb(r,t,e){let n=await Ho(r,t,e);if(n.type==="file"||n.type==="raw"){yield*Ye([mb(n)],Dl());return}if(n.type==="directory"){yield*Ye(Kw(r,t,e),o=>zt(o,i=>mb(i)),Dl());return}throw new is("Not a UnixFS node")}var yb=Ot(If(),1),Ol=class{lru;constructor(t){this.lru=(0,yb.default)(t)}get(t){let e=this.lru.get(t);if(e!=null){if(e.expire!=null&&e.expire<Date.now()){this.lru.remove(t);return}return e.value}}set(t,e,n){this.lru.set(t,{value:e,expire:Date.now()+n})}has(t){return this.get(t)!=null}remove(t){this.lru.remove(t)}clear(){this.lru.clear()}};var wb=new Ol(1e3),mk=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,gk=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,yk=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,wk=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function bk(r){let t=r?.protocol;if(t==null)return!1;let e=r?.cidOrPeerIdOrDnsLink;if(e==null)return!1;let n=r?.path,o=r?.queryString;return["ipns","ipfs"].includes(t)&&typeof e=="string"&&(n==null||typeof n=="string")&&(o==null||typeof o=="string")}function ss(r){for(let t of[wk,mk,yk,gk]){let e=r.match(t);if(bk(e?.groups))return e.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function xk(r){if(r==null)return;let t=r.answer?.TTL,e=r.record?.ttl,n=e!=null?Number(e/BigInt(1e9)):void 0;return t??n}var Ek=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function vk(r){return Ek.test(r)&&r.includes("-")&&!r.includes(".")}function Sk(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function bb({urlString:r,ipns:t,logger:e},n){let o=e.forComponent("helia:verified-fetch:parse-url-string"),{protocol:i,cidOrPeerIdOrDnsLink:s,path:a,queryString:c}=ss(r),l,u,f=[],d;if(i==="ipfs")try{l=L.parse(s)}catch(p){o.error(p),f.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(d=wb.get(s),d!=null)l=d.cid,u=d.path,o.trace("resolved %s to %c from cache",s,l);else{o.trace("Attempting to resolve PeerId for %s",s);let p;try{if(p=mo(s),p.publicKey==null)throw new TypeError("cidOrPeerIdOrDnsLink contains no public key");d=await t.resolve(p.publicKey,n),l=d?.cid,u=d?.path,o.trace("resolved %s to %c",s,l)}catch(y){n?.signal?.throwIfAborted(),p==null?(o.error('could not parse PeerId string "%s"',s,y),f.push(new TypeError(`Could not parse PeerId in ipns url "${s}", ${y.message}`))):(o.error("could not resolve PeerId %c",p,y),f.push(new TypeError(`Could not resolve PeerId "${s}", ${y.message}`)))}if(l==null){let y=s;vk(s)&&(y=Sk(s),o.trace('decoded dnslink from "%s" to "%s"',s,y)),o.trace("Attempting to resolve DNSLink for %s",y);try{d=await t.resolveDNSLink(y,n),l=d?.cid,u=d?.path,o.trace("resolved %s to %c",y,l)}catch(g){n?.signal?.throwIfAborted(),o.error('could not resolve DnsLink for "%s"',s,g),f.push(g)}}}if(l==null)throw f.length===1?f[0]:new AggregateError(f,`Invalid resource. Cannot determine CID from URL "${r}"`);let h=xk(d);d!=null&&(h=h??60*2,o.trace("caching %s resolved to %s with TTL: %s",s,l,h),wb.set(s,d,h*1e3));let m={};if(c!=null&&c.length>0){let p=c.split("&");for(let y of p){let[g,x]=y.split("=");m[g]=decodeURIComponent(x)}m.download!=null&&(m.download=m.download==="true"),m.filename!=null&&(m.filename=m.filename.toString())}return{protocol:i,cid:l,path:Ak(u,a??""),query:m,ttl:h,ipfsPath:`/${i}/${s}${a!=null&&a!==""?`/${a}`:""}`}}function Ak(r,t){let e="";return r!=null&&(e+=r),t.length>0&&(e=`${e.length>0?`${e}/`:e}${t}`),e=e.replace(/\/(\/)+/g,"/"),e.startsWith("/")&&(e=e.substring(1)),e.split("/").map(decodeURIComponent).join("/")}function yd(r,t,e){Object.defineProperty(r,t,{enumerable:!0,configurable:!1,set:()=>{},get:()=>e})}function Fr(r,t){yd(r,"type",t)}function Mr(r,t){yd(r,"url",t)}function xb(r){yd(r,"redirected",!0)}function Hn(r,t,e){let n=new Response(t,{...e??{},status:200,statusText:"OK"});return e?.redirected===!0&&xb(n),Fr(n,"basic"),Mr(n,r),n.headers.set("Accept-Ranges","bytes"),n}function Fl(r,t,e){let n=new Response(t,{...e??{},status:502,statusText:"Bad Gateway"});return Fr(n,"basic"),Mr(n,r),n}function Ml(r,t,e){let n=new Response(t,{...e??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),Fr(n,"basic"),Mr(n,r),n}function qo(r,t,e){let n=new Response(t,{...e??{},status:406,statusText:"Not Acceptable"});return Fr(n,"basic"),Mr(n,r),n}function Vl(r,t,e){let n=new Response(t,{...e??{},status:404,statusText:"Not Found"});return Fr(n,"basic"),Mr(n,r),n}function Hl(r,t,e){t instanceof Error&&(t=t.message);let n=new Response(t,{...e??{},status:400,statusText:"Bad Request"});return Fr(n,"basic"),Mr(n,r),n}function as(r,t,e){let n=new Response(null,{...e??{},status:301,statusText:"Moved Permanently",headers:{...e?.headers??{},location:t}});return Fr(n,"basic"),Mr(n,r),n}function wd(r,t,{byteRangeContext:e,log:n},o){if(!e.isRangeRequest)return Hn(r,t,o);if(!e.isValidRangeRequest)return Ul(r,t,o);let i;try{i=new Response(t,{...o??{},status:206,statusText:"Partial Content",headers:{...o?.headers??{},"content-range":e.contentRangeHeaderValue}})}catch(s){return n?.error("failed to create range response",s),Ul(r,t,o)}return o?.redirected===!0&&xb(i),Fr(i,"basic"),Mr(i,r),i.headers.set("Accept-Ranges","bytes"),i}function Ul(r,t,e){let n=new Response(t,{...e??{},status:416,statusText:"Requested Range Not Satisfiable"});return Fr(n,"basic"),Mr(n,r),n}function Eb(r){return r.match(/\.[a-zA-Z0-9]{1,4}$/)!=null||r.endsWith("/")?r:`${r}/`}async function vb({resource:r,options:t,logger:e,cid:n,fetch:o=globalThis.fetch}){let i=e.forComponent("helia:verified-fetch:get-redirect-response");if(typeof r!="string"||t==null||["ipfs://","ipns://"].some(u=>r.startsWith(u)))return null;let s=new Headers(t?.headers),a=s.get("x-forwarded-host"),c=s.get("host");if(s.get("x-forwarded-for")==null&&a==null&&c==null)return i.trace("no redirect info found in headers"),null;i.trace("checking for redirect info");try{let u=ss(r),f=new URL(r),d=a??f.host,h=new URL(f);if(u.protocol==="ipfs"&&n.version===0?h.host=`${n.toV1()}.ipfs.${d}`:h.host=`${u.cidOrPeerIdOrDnsLink}.${u.protocol}.${d}`,c?.includes(u.protocol)===!0&&h.host.includes(c))return i.trace("request was for a subdomain already, not setting location header"),null;if(c!=null&&!h.host.includes(c))return i.trace("host header is not the same as the subdomain url host, not setting location header"),null;if(f.host===h.host)return i.trace("req url is the same as the subdomain url, not setting location header"),null;h.pathname=Eb(f.pathname.replace(`/${u.cidOrPeerIdOrDnsLink}`,"").replace(`/${u.protocol}`,"")),i.trace("subdomain url %s",h.href);let m=new URL(f,`${f.protocol}//${d}`);m.pathname=Eb(f.pathname),i.trace("path url %s",m.href);try{let p=await o(h,{method:"HEAD"});if(p.ok)return i("subdomain supported, redirecting to subdomain"),as(r.toString(),h.href);throw i("subdomain not supported, subdomain failed with status %s %s",p.status,p.statusText),new Cl("subdomain not supported")}catch(p){return i("subdomain not supported",p),m.href===f.href?(i("path url is the same as the request url, not setting location header"),null):as(r.toString(),m.href)}}catch(u){i.error("error setting location header for x-forwarded-host",u)}return null}async function Sb(r,{ipns:t,logger:e},n){if(typeof r=="string")return bb({urlString:r,ipns:t,logger:e},n);let o=L.asCID(r);if(o!=null)return{cid:o,protocol:"ipfs",path:"",query:{},ipfsPath:`/ipfs/${o.toString()}`,ttl:29030400};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function Ab(r){let t=L.asCID(r);if(t!=null)return`ipfs://${t}`;try{return`ipfs://${L.parse(r.toString())}`}catch{}let{protocol:e,cidOrPeerIdOrDnsLink:n}=ss(r.toString());return`${e}://${n}`}async function Ik(r,t,e){let n=[],o;for await(let i of cd(t,r,e))n.push(i.cid),o=i;if(o==null)throw new Ll("No terminal element found");return{ipfsRoots:n,terminalElement:o}}function Ib(r){return r.type==="object"}async function bd({cid:r,path:t,resource:e,options:n,blockstore:o,log:i}){try{return await Ik(o,`${r.toString()}/${t}`,n)}catch(s){return n?.signal?.throwIfAborted(),["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(s.code)?Vl(e):(i.error("error walking path %s",t,s),Fl(e,"Error walking path"))}}var kk=100,_k=60*1e3;function Bk(r){if(r==null)return;let t;return r?.signal===null?t=void 0:t=r?.signal,{...r,signal:t}}var Tk=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function Ck({headers:r,accept:t}){let n=(t??new Headers(r).get("accept")??"").split(",").map(o=>o.split(";")[0]).map(o=>o.trim());for(let o of n){if(o==="*/*")return;if(Tk.includes(o??""))return o}}var $l=class{helia;ipns;log;contentTypeParser;blockstoreSessions;constructor({helia:t,ipns:e},n){this.helia=t,this.log=t.logger.forComponent("helia:verified-fetch"),this.ipns=e??mw(t),this.contentTypeParser=n?.contentTypeParser,this.blockstoreSessions=new Bl({max:n?.sessionCacheSize??kk,ttl:n?.sessionTTLms??_k,dispose:o=>{o.close()}}),this.log.trace("created VerifiedFetch instance")}getBlockstore(t,e,n,o){let i=Ab(e);if(!n)return this.helia.blockstore;let s=this.blockstoreSessions.get(i);return s==null&&(s=this.helia.blockstore.createSession(t,o),this.blockstoreSessions.set(i,s)),s}async handleIPNSRecord({resource:t,cid:e,path:n,options:o}){if(n!==""||!t.startsWith("ipns://"))return Hl(t,"Invalid IPNS name");let i;try{i=mo(t.replace("ipns://",""))}catch(f){return this.log.error("could not parse peer id from IPNS url %s",t),Hl(t,f)}let s=ct([D("/ipns/"),i.toMultihash().bytes]),a=new At("/dht/record/"+q(s,"base32"),!1),c=await this.helia.datastore.get(a,o),l=ar.deserialize(c),u=Hn(t,l.value);return u.headers.set("content-type","application/vnd.ipfs.ipns-record"),u}async handleCar({resource:t,cid:e,session:n,options:o}){let i=this.getBlockstore(e,t,n,o),s=Ky({blockstore:i,getCodec:this.helia.getCodec}),a=kl(s.stream(e,o)),c=Hn(t,a);return c.headers.set("content-type","application/vnd.ipld.car; version=1"),c}async handleTar({resource:t,cid:e,path:n,session:o,options:i}){if(e.code!==Te&&e.code!==ae)return qo("only UnixFS data can be returned in a TAR file");let s=this.getBlockstore(e,t,o,i),a=kl(gb(`/ipfs/${e}/${n}`,s,i)),c=Hn(t,a);return c.headers.set("content-type","application/x-tar"),c}async handleJson({resource:t,cid:e,path:n,accept:o,session:i,options:s}){this.log.trace("fetching %c/%s",e,n);let c=await this.getBlockstore(e,t,i,s).get(e,s),l;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let f=ko(c);l=Ao(f)}catch(f){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",f),qo(t)}else l=c;let u=Hn(t,l);return u.headers.set("content-type",o??"application/json"),u}async handleDagCbor({resource:t,cid:e,path:n,accept:o,session:i,options:s}){this.log.trace("fetching %c/%s",e,n);let a,c=this.getBlockstore(e,t,i,s),l=await bd({cid:e,path:n,resource:t,options:s,blockstore:c,log:this.log});if(l instanceof Response)return l;let u=l.ipfsRoots;if(Ib(l.terminalElement))a=l.terminalElement;else return this.log.error("terminal element is not a dag-cbor node"),Ml(t,"Terminal element is not a dag-cbor node");let f=a.node,d;if(o==="application/octet-stream"||o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")d=f;else if(o==="application/vnd.ipld.dag-json")try{let m=cn(f);d=hc(m)}catch(m){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",m),qo(t)}else try{d=eb(f)}catch(m){if(o==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',m),qo(t);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",m),d=f}let h=Hn(t,d);return o==null&&(o=d instanceof Uint8Array?"application/octet-stream":"application/json"),h.headers.set("content-type",o),fd(h,u),h}async handleDagPb({cid:t,path:e,resource:n,session:o,options:i}){let s=!1,a=new os(this.helia.logger,i?.headers),c=this.getBlockstore(t,n,o,i),l=await bd({cid:t,path:e,resource:n,options:i,blockstore:c,log:this.log});if(l instanceof Response)return l;let u=l.ipfsRoots,f=l.terminalElement,d=f.cid;if(f?.type==="directory"){let p=f.cid;if(e===""?!n.toString().endsWith("/"):!e.endsWith("/")){if(i?.redirect==="error")throw this.log('could not redirect to %s/ as redirect option was set to "error"',n),new TypeError("Failed to fetch");if(i?.redirect==="manual")return this.log("returning 301 permanent redirect to %s/",n),as(n,`${n}/`);n=`${n}/`,s=!0}let g="index.html";try{this.log.trace("found directory at %c/%s, looking for index.html",t,e);let x=await Ho(`/ipfs/${p}/${g}`,this.helia.blockstore,{signal:i?.signal,onProgress:i?.onProgress});this.log.trace("found root file at %c/%s with cid %c",p,g,x.cid),e=g,d=x.cid}catch(x){return i?.signal?.throwIfAborted(),this.log("error loading path %c/%s",p,g,x),Ml("Unable to find index.html for directory at given path. Support for directories with implicit root is not implemented")}finally{i?.onProgress?.(new H("verified-fetch:request:end",{cid:p,path:g}))}}a.isRangeRequest&&a.isValidRangeRequest&&f.type==="file"&&(a.setFileSize(f.unixfs.fileSize()),this.log.trace("fileSize for rangeRequest %d",a.getFileSize()));let h=a.offset,m=a.length;this.log.trace("calling exporter for %c/%s with offset=%o & length=%o",d,e,h,m);try{let y=(await Ho(d,this.helia.blockstore,{signal:i?.signal,onProgress:i?.onProgress})).content({signal:i?.signal,onProgress:i?.onProgress,offset:h,length:m});this.log("got async iterator for %c/%s",t,e);let{stream:g,firstChunk:x}=await cb(y,e??"",this.helia.logger,{onProgress:i?.onProgress,signal:i?.signal});a.setBody(g);let b=wd(n,a.getBody(),{byteRangeContext:a,log:this.log},{redirected:s});return await this.setContentType(x,e,b),fd(b,u),b}catch(p){return i?.signal?.throwIfAborted(),this.log.error("error streaming %c/%s",t,e,p),a.isRangeRequest&&p.code==="ERR_INVALID_PARAMS"?Ul(n):Fl(n.toString(),"Unable to stream content")}}async handleRaw({resource:t,cid:e,path:n,session:o,options:i,accept:s}){if(n!=="")return this.log.trace("404-ing raw codec request for %c/%s",e,n),Vl(t,"Raw codec does not support paths");let a=new os(this.helia.logger,i?.headers),l=await this.getBlockstore(e,t,o,i).get(e,i);a.setBody(l);let u=wd(t,a.getBody(),{byteRangeContext:a,log:this.log},{redirected:!1});return await this.setContentType(l,n,u,Ck({headers:i?.headers,accept:s})),u}async setContentType(t,e,n,o="application/octet-stream"){let i;if(this.contentTypeParser!=null)try{let s=e.split("/").pop()?.trim();s=s===""?void 0:s;let a=this.contentTypeParser(t,s);if(Rk(a)){let c=await a;c!=null&&(i=c)}else a!=null&&(i=a)}catch(s){this.log.error("error parsing content type",s)}this.log.trace('setting content type to "%s"',i??o),n.headers.set("content-type",i??o)}codecHandlers={[Te]:this.handleDagPb,[Rr]:this.handleJson,[hr]:this.handleJson,[Cr]:this.handleDagCbor,[ae]:this.handleRaw,[bt.code]:this.handleRaw};async fetch(t,e){this.log("fetch %s",t);let n=Bk(e);n?.onProgress?.(new H("verified-fetch:request:start",{resource:t}));let o,i,s,a,c,l;try{let g=await Sb(t,{ipns:this.ipns,logger:this.helia.logger},n);o=g.cid,i=g.path,s=g.query,a=g.ttl,c=g.protocol,l=g.ipfsPath}catch(g){return n?.signal?.throwIfAborted(),this.log.error("error parsing resource %s",t,g),Hl(t.toString(),g)}n?.onProgress?.(new H("verified-fetch:request:resolve",{cid:o,path:i}));let u=ab({query:s,headers:n?.headers,logger:this.helia.logger}),f=ob(o,u);if(this.log("output type %s",f),u!=null&&f==null)return qo(t.toString());let d,h,m=await vb({resource:t,options:n,logger:this.helia.logger,cid:o});if(m!=null)return m;let p={resource:t.toString(),cid:o,path:i,accept:f,session:n?.session??!0,options:n};if(f==="application/vnd.ipfs.ipns-record")h="ipns-record",d=await this.handleIPNSRecord(p);else if(f==="application/vnd.ipld.car")h="car",s.download=!0,s.filename=s.filename??`${o.toString()}.car`,d=await this.handleCar(p);else if(f==="application/vnd.ipld.raw")h="raw",s.download=!0,s.filename=s.filename??`${o.toString()}.bin`,d=await this.handleRaw(p);else if(f==="application/x-tar")h="tar",s.download=!0,s.filename=s.filename??`${o.toString()}.tar`,d=await this.handleTar(p);else{this.log.trace('finding handler for cid code "%s" and output type "%s"',o.code,f);let g=this.codecHandlers[o.code];if(g==null)return Ml(`Support for codec with code ${o.code} is not yet implemented. Please open an issue at https://github.com/ipfs/helia-verified-fetch/issues/new`);this.log.trace('calling handler "%s"',g.name),d=await g.call(this,p)}d.headers.set("etag",nb({cid:o,reqFormat:h,weak:!1})),Qw({response:d,ttl:a,protocol:c}),d.headers.set("X-Ipfs-Path",l);let y;return s.download===!0&&(y="attachment"),s.filename!=null&&(y==null&&(y="inline"),y=`${y}; ${rb(s.filename)}`),y!=null&&d.headers.set("Content-Disposition",y),n?.onProgress?.(new H("verified-fetch:request:end",{cid:o,path:i})),d}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};function Rk(r){return r?.then!=null}var cs,zl=async function(t,e){return cs==null&&(cs=await xd()),cs(t,e)};zl.start=async function(){await cs?.start()};zl.stop=async function(){await cs?.stop()};async function xd(r,t){Nk(r)||(r=await Ty({blockBrokers:[Hi({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})],routers:[...(r?.routers??["https://delegated-ipfs.dev"]).map(o=>Ki(o)),Gi({gateways:r?.gateways??["https://trustless-gateway.link"]})],dns:Lk(r?.dnsResolvers)}));let e=new $l({helia:r},t);async function n(o,i){return e.fetch(o,i)}return n.stop=e.stop.bind(e),n.start=e.start.bind(e),n}function Nk(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function Lk(r){if(r!=null)return Array.isArray(r)?Ai({resolvers:{".":r}}):Ai({resolvers:r})}return Mb(Pk);})();
23
22
  /*! Bundled license information:
24
23
 
25
24
  pvtsutils/build/index.js: